From dc13ba168b70ca59c0d70f538e3c02893f8be80f Mon Sep 17 00:00:00 2001 From: Baz Utsahajit Date: Mon, 18 Dec 2023 19:12:16 +0000 Subject: [PATCH] Chore: Create v7.x Snapshot + Make Working Docs the Pre-Release v8 --- docs/pixi-version.json | 16 +- docusaurus.config.js | 7 +- pixi-versions.json | 11 + .../v8.0.0-rc/advanced/collisionDetection.js | 179 ++++++++ src/examples/v8.0.0-rc/advanced/mouseTrail.js | 101 +++++ .../v8.0.0-rc/advanced/scratchCard.js | 83 ++++ src/examples/v8.0.0-rc/advanced/screenShot.js | 58 +++ src/examples/v8.0.0-rc/advanced/slots.js | 239 ++++++++++ src/examples/v8.0.0-rc/advanced/spinners.js | 427 ++++++++++++++++++ src/examples/v8.0.0-rc/advanced/starWarp.js | 89 ++++ src/examples/v8.0.0-rc/assets/async.js | 26 ++ src/examples/v8.0.0-rc/assets/background.js | 37 ++ src/examples/v8.0.0-rc/assets/bundle.js | 91 ++++ src/examples/v8.0.0-rc/assets/multiple.js | 32 ++ src/examples/v8.0.0-rc/assets/promise.js | 24 + src/examples/v8.0.0-rc/basic/blendModes.js | 92 ++++ src/examples/v8.0.0-rc/basic/cacheAsBitmap.js | 73 +++ src/examples/v8.0.0-rc/basic/container.js | 39 ++ .../v8.0.0-rc/basic/particleContainer.js | 102 +++++ src/examples/v8.0.0-rc/basic/simplePlane.js | 32 ++ src/examples/v8.0.0-rc/basic/tinting.js | 85 ++++ .../v8.0.0-rc/basic/transparentBackground.js | 23 + src/examples/v8.0.0-rc/events/click.js | 36 ++ .../v8.0.0-rc/events/customHitarea.js | 116 +++++ .../v8.0.0-rc/events/customMouseIcon.js | 104 +++++ src/examples/v8.0.0-rc/events/dragging.js | 81 ++++ .../events/hitTestingWithSpatialHash.js | 219 +++++++++ .../v8.0.0-rc/events/interactivity.js | 111 +++++ src/examples/v8.0.0-rc/events/logger.js | 86 ++++ .../events/nestedBoundaryWithProjection.js | 231 ++++++++++ .../v8.0.0-rc/events/pointerTracker.js | 34 ++ src/examples/v8.0.0-rc/events/slider.js | 84 ++++ src/examples/v8.0.0-rc/examplesData.json | 108 +++++ .../v8.0.0-rc/filtersAdvanced/custom.js | 47 ++ .../filtersAdvanced/mouseBlending.js | 58 +++ .../shaderToyFilterRenderTexture.js | 116 +++++ src/examples/v8.0.0-rc/filtersBasic/blur.js | 42 ++ .../v8.0.0-rc/filtersBasic/colorMatrix.js | 90 ++++ .../filtersBasic/displacementMapCrawlies.js | 111 +++++ .../filtersBasic/displacementMapFlag.js | 46 ++ src/examples/v8.0.0-rc/graphics/advanced.js | 105 +++++ src/examples/v8.0.0-rc/graphics/dynamic.js | 98 ++++ src/examples/v8.0.0-rc/graphics/simple.js | 99 ++++ src/examples/v8.0.0-rc/index.ts | 286 ++++++++++++ src/examples/v8.0.0-rc/masks/filter.js | 42 ++ src/examples/v8.0.0-rc/masks/graphics.js | 100 ++++ src/examples/v8.0.0-rc/masks/sprite.js | 46 ++ .../meshAndShaders/instancedGeometry.js | 76 ++++ .../meshAndShaders/interleavingGeometry.js | 86 ++++ .../meshAndShaders/mergingGeometry.js | 114 +++++ .../multiPassShaderGeneratedMesh.js | 235 ++++++++++ .../v8.0.0-rc/meshAndShaders/shaderToyMesh.js | 155 +++++++ .../v8.0.0-rc/meshAndShaders/sharedShader.js | 124 +++++ .../meshAndShaders/sharingGeometry.js | 104 +++++ .../meshAndShaders/texturedMeshAdvanced.js | 64 +++ .../meshAndShaders/texturedMeshBasic.js | 43 ++ .../v8.0.0-rc/meshAndShaders/triangle.js | 40 ++ .../v8.0.0-rc/meshAndShaders/triangleColor.js | 77 ++++ .../meshAndShaders/triangleTextured.js | 100 ++++ .../v8.0.0-rc/meshAndShaders/uniforms.js | 92 ++++ .../v8.0.0-rc/offscreenCanvas/basic.js | 44 ++ .../v8.0.0-rc/offscreenCanvas/webWorker.js | 84 ++++ .../sprite/animatedSpriteAnimationSpeed.js | 47 ++ .../sprite/animatedSpriteExplosion.js | 36 ++ .../v8.0.0-rc/sprite/animatedSpriteJet.js | 40 ++ src/examples/v8.0.0-rc/sprite/basic.js | 26 ++ src/examples/v8.0.0-rc/sprite/textureSwap.js | 38 ++ src/examples/v8.0.0-rc/sprite/tilingSprite.js | 29 ++ src/examples/v8.0.0-rc/sprite/video.js | 53 +++ src/examples/v8.0.0-rc/text/bitmapText.js | 19 + src/examples/v8.0.0-rc/text/fromFont.js | 29 ++ src/examples/v8.0.0-rc/text/pixiText.js | 62 +++ src/examples/v8.0.0-rc/text/webFont.js | 42 ++ .../v8.0.0-rc/textures/gradientBasic.js | 43 ++ .../v8.0.0-rc/textures/gradientResource.js | 72 +++ .../textures/renderTextureAdvanced.js | 96 ++++ .../v8.0.0-rc/textures/renderTextureBasic.js | 48 ++ .../v8.0.0-rc/textures/textureRotate.js | 65 +++ .../v8.0.0-rc/gettingStarted/index.ts | 36 ++ .../v8.0.0-rc/gettingStarted/step1-code.js | 8 + .../v8.0.0-rc/gettingStarted/step1-content.md | 15 + .../v8.0.0-rc/gettingStarted/step2-code.js | 8 + .../gettingStarted/step2-completed-code.js | 21 + .../v8.0.0-rc/gettingStarted/step2-content.md | 29 ++ .../v8.0.0-rc/gettingStarted/step3-code.js | 20 + .../gettingStarted/step3-completed-code.js | 29 ++ .../v8.0.0-rc/gettingStarted/step3-content.md | 15 + .../v8.0.0-rc/gettingStarted/step4-code.js | 29 ++ .../v8.0.0-rc/gettingStarted/step4-content.md | 3 + src/tutorials/v8.0.0-rc/index.ts | 26 ++ src/tutorials/v8.0.0-rc/tutorialsData.json | 1 + versioned_docs/version-7.3.2/branding.md | 68 +++ .../version-7.3.2/examples/index.md | 17 + versioned_docs/version-7.3.2/faq.md | 40 ++ .../guides/basics/architecture-overview.md | 25 + .../guides/basics/getting-started.md | 176 ++++++++ .../guides/basics/render-loop.md | 35 ++ .../guides/basics/scene-graph.md | 152 +++++++ .../guides/basics/what-pixijs-is-not.md | 39 ++ .../guides/basics/what-pixijs-is.md | 31 ++ .../version-7.3.2/guides/components/assets.md | 161 +++++++ .../guides/components/containers.md | 96 ++++ .../guides/components/display-object.md | 21 + .../guides/components/graphics.md | 104 +++++ .../guides/components/interaction.md | 110 +++++ .../guides/components/sprite-sheets.md | 84 ++++ .../guides/components/sprites.md | 41 ++ .../version-7.3.2/guides/components/text.md | 106 +++++ .../guides/components/textures.md | 75 +++ versioned_docs/version-7.3.2/guides/index.md | 14 + .../guides/migrations/upgrading.md | 17 + .../version-7.3.2/guides/migrations/v5.md | 224 +++++++++ .../version-7.3.2/guides/migrations/v6.md | 34 ++ .../version-7.3.2/guides/migrations/v7.md | 249 ++++++++++ .../guides/production/performance-tips.md | 71 +++ .../version-7.3.2/pixi-version.json | 10 + .../version-7.3.2/playground/index.md | 11 + .../version-7.3.2/tutorials/index.md | 11 + .../version-7.3.2-sidebars.json | 59 +++ versions.json | 3 + 120 files changed, 8860 insertions(+), 9 deletions(-) create mode 100644 src/examples/v8.0.0-rc/advanced/collisionDetection.js create mode 100644 src/examples/v8.0.0-rc/advanced/mouseTrail.js create mode 100644 src/examples/v8.0.0-rc/advanced/scratchCard.js create mode 100644 src/examples/v8.0.0-rc/advanced/screenShot.js create mode 100644 src/examples/v8.0.0-rc/advanced/slots.js create mode 100644 src/examples/v8.0.0-rc/advanced/spinners.js create mode 100644 src/examples/v8.0.0-rc/advanced/starWarp.js create mode 100644 src/examples/v8.0.0-rc/assets/async.js create mode 100644 src/examples/v8.0.0-rc/assets/background.js create mode 100644 src/examples/v8.0.0-rc/assets/bundle.js create mode 100644 src/examples/v8.0.0-rc/assets/multiple.js create mode 100644 src/examples/v8.0.0-rc/assets/promise.js create mode 100644 src/examples/v8.0.0-rc/basic/blendModes.js create mode 100644 src/examples/v8.0.0-rc/basic/cacheAsBitmap.js create mode 100644 src/examples/v8.0.0-rc/basic/container.js create mode 100644 src/examples/v8.0.0-rc/basic/particleContainer.js create mode 100644 src/examples/v8.0.0-rc/basic/simplePlane.js create mode 100644 src/examples/v8.0.0-rc/basic/tinting.js create mode 100644 src/examples/v8.0.0-rc/basic/transparentBackground.js create mode 100644 src/examples/v8.0.0-rc/events/click.js create mode 100644 src/examples/v8.0.0-rc/events/customHitarea.js create mode 100644 src/examples/v8.0.0-rc/events/customMouseIcon.js create mode 100644 src/examples/v8.0.0-rc/events/dragging.js create mode 100644 src/examples/v8.0.0-rc/events/hitTestingWithSpatialHash.js create mode 100644 src/examples/v8.0.0-rc/events/interactivity.js create mode 100644 src/examples/v8.0.0-rc/events/logger.js create mode 100644 src/examples/v8.0.0-rc/events/nestedBoundaryWithProjection.js create mode 100644 src/examples/v8.0.0-rc/events/pointerTracker.js create mode 100644 src/examples/v8.0.0-rc/events/slider.js create mode 100644 src/examples/v8.0.0-rc/examplesData.json create mode 100644 src/examples/v8.0.0-rc/filtersAdvanced/custom.js create mode 100644 src/examples/v8.0.0-rc/filtersAdvanced/mouseBlending.js create mode 100644 src/examples/v8.0.0-rc/filtersAdvanced/shaderToyFilterRenderTexture.js create mode 100644 src/examples/v8.0.0-rc/filtersBasic/blur.js create mode 100644 src/examples/v8.0.0-rc/filtersBasic/colorMatrix.js create mode 100644 src/examples/v8.0.0-rc/filtersBasic/displacementMapCrawlies.js create mode 100644 src/examples/v8.0.0-rc/filtersBasic/displacementMapFlag.js create mode 100644 src/examples/v8.0.0-rc/graphics/advanced.js create mode 100644 src/examples/v8.0.0-rc/graphics/dynamic.js create mode 100644 src/examples/v8.0.0-rc/graphics/simple.js create mode 100644 src/examples/v8.0.0-rc/index.ts create mode 100644 src/examples/v8.0.0-rc/masks/filter.js create mode 100644 src/examples/v8.0.0-rc/masks/graphics.js create mode 100644 src/examples/v8.0.0-rc/masks/sprite.js create mode 100644 src/examples/v8.0.0-rc/meshAndShaders/instancedGeometry.js create mode 100644 src/examples/v8.0.0-rc/meshAndShaders/interleavingGeometry.js create mode 100644 src/examples/v8.0.0-rc/meshAndShaders/mergingGeometry.js create mode 100644 src/examples/v8.0.0-rc/meshAndShaders/multiPassShaderGeneratedMesh.js create mode 100644 src/examples/v8.0.0-rc/meshAndShaders/shaderToyMesh.js create mode 100644 src/examples/v8.0.0-rc/meshAndShaders/sharedShader.js create mode 100644 src/examples/v8.0.0-rc/meshAndShaders/sharingGeometry.js create mode 100644 src/examples/v8.0.0-rc/meshAndShaders/texturedMeshAdvanced.js create mode 100644 src/examples/v8.0.0-rc/meshAndShaders/texturedMeshBasic.js create mode 100644 src/examples/v8.0.0-rc/meshAndShaders/triangle.js create mode 100644 src/examples/v8.0.0-rc/meshAndShaders/triangleColor.js create mode 100644 src/examples/v8.0.0-rc/meshAndShaders/triangleTextured.js create mode 100644 src/examples/v8.0.0-rc/meshAndShaders/uniforms.js create mode 100644 src/examples/v8.0.0-rc/offscreenCanvas/basic.js create mode 100644 src/examples/v8.0.0-rc/offscreenCanvas/webWorker.js create mode 100644 src/examples/v8.0.0-rc/sprite/animatedSpriteAnimationSpeed.js create mode 100644 src/examples/v8.0.0-rc/sprite/animatedSpriteExplosion.js create mode 100644 src/examples/v8.0.0-rc/sprite/animatedSpriteJet.js create mode 100644 src/examples/v8.0.0-rc/sprite/basic.js create mode 100644 src/examples/v8.0.0-rc/sprite/textureSwap.js create mode 100644 src/examples/v8.0.0-rc/sprite/tilingSprite.js create mode 100644 src/examples/v8.0.0-rc/sprite/video.js create mode 100644 src/examples/v8.0.0-rc/text/bitmapText.js create mode 100644 src/examples/v8.0.0-rc/text/fromFont.js create mode 100644 src/examples/v8.0.0-rc/text/pixiText.js create mode 100644 src/examples/v8.0.0-rc/text/webFont.js create mode 100644 src/examples/v8.0.0-rc/textures/gradientBasic.js create mode 100644 src/examples/v8.0.0-rc/textures/gradientResource.js create mode 100644 src/examples/v8.0.0-rc/textures/renderTextureAdvanced.js create mode 100644 src/examples/v8.0.0-rc/textures/renderTextureBasic.js create mode 100644 src/examples/v8.0.0-rc/textures/textureRotate.js create mode 100644 src/tutorials/v8.0.0-rc/gettingStarted/index.ts create mode 100644 src/tutorials/v8.0.0-rc/gettingStarted/step1-code.js create mode 100644 src/tutorials/v8.0.0-rc/gettingStarted/step1-content.md create mode 100644 src/tutorials/v8.0.0-rc/gettingStarted/step2-code.js create mode 100644 src/tutorials/v8.0.0-rc/gettingStarted/step2-completed-code.js create mode 100644 src/tutorials/v8.0.0-rc/gettingStarted/step2-content.md create mode 100644 src/tutorials/v8.0.0-rc/gettingStarted/step3-code.js create mode 100644 src/tutorials/v8.0.0-rc/gettingStarted/step3-completed-code.js create mode 100644 src/tutorials/v8.0.0-rc/gettingStarted/step3-content.md create mode 100644 src/tutorials/v8.0.0-rc/gettingStarted/step4-code.js create mode 100644 src/tutorials/v8.0.0-rc/gettingStarted/step4-content.md create mode 100644 src/tutorials/v8.0.0-rc/index.ts create mode 100644 src/tutorials/v8.0.0-rc/tutorialsData.json create mode 100644 versioned_docs/version-7.3.2/branding.md create mode 100644 versioned_docs/version-7.3.2/examples/index.md create mode 100644 versioned_docs/version-7.3.2/faq.md create mode 100644 versioned_docs/version-7.3.2/guides/basics/architecture-overview.md create mode 100644 versioned_docs/version-7.3.2/guides/basics/getting-started.md create mode 100644 versioned_docs/version-7.3.2/guides/basics/render-loop.md create mode 100644 versioned_docs/version-7.3.2/guides/basics/scene-graph.md create mode 100644 versioned_docs/version-7.3.2/guides/basics/what-pixijs-is-not.md create mode 100644 versioned_docs/version-7.3.2/guides/basics/what-pixijs-is.md create mode 100644 versioned_docs/version-7.3.2/guides/components/assets.md create mode 100644 versioned_docs/version-7.3.2/guides/components/containers.md create mode 100644 versioned_docs/version-7.3.2/guides/components/display-object.md create mode 100644 versioned_docs/version-7.3.2/guides/components/graphics.md create mode 100644 versioned_docs/version-7.3.2/guides/components/interaction.md create mode 100644 versioned_docs/version-7.3.2/guides/components/sprite-sheets.md create mode 100644 versioned_docs/version-7.3.2/guides/components/sprites.md create mode 100644 versioned_docs/version-7.3.2/guides/components/text.md create mode 100644 versioned_docs/version-7.3.2/guides/components/textures.md create mode 100644 versioned_docs/version-7.3.2/guides/index.md create mode 100644 versioned_docs/version-7.3.2/guides/migrations/upgrading.md create mode 100644 versioned_docs/version-7.3.2/guides/migrations/v5.md create mode 100644 versioned_docs/version-7.3.2/guides/migrations/v6.md create mode 100644 versioned_docs/version-7.3.2/guides/migrations/v7.md create mode 100644 versioned_docs/version-7.3.2/guides/production/performance-tips.md create mode 100644 versioned_docs/version-7.3.2/pixi-version.json create mode 100644 versioned_docs/version-7.3.2/playground/index.md create mode 100644 versioned_docs/version-7.3.2/tutorials/index.md create mode 100644 versioned_sidebars/version-7.3.2-sidebars.json create mode 100644 versions.json diff --git a/docs/pixi-version.json b/docs/pixi-version.json index 1830703e9..5e1f9c3b2 100644 --- a/docs/pixi-version.json +++ b/docs/pixi-version.json @@ -1,10 +1,10 @@ { - "versionLabel": "v7.x (Latest)", - "version": "7.3.2", - "releaseNotes": "https://github.com/pixijs/pixijs/releases/tag/v7.3.2", - "build": "https://pixijs.download/v7.3.2/pixi.min.js", - "docs": "https://pixijs.download/v7.3.2/docs/index.html", - "npm": "7.3.2", - "prerelease": false, - "latest": true + "versionLabel": "prerelease-v8", + "version": "8.0.0-rc", + "releaseNotes": "https://github.com/pixijs/pixijs/releases/tag/v8.0.0-rc", + "build": "https://pixijs.download/v8.0.0-rc/pixi.min.js", + "docs": "https://pixijs.download/v8.0.0-rc/docs/index.html", + "npm": "8.0.0-rc", + "prerelease": true, + "latest": false } diff --git a/docusaurus.config.js b/docusaurus.config.js index 17775420a..6e2dac826 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -43,8 +43,13 @@ const config = { editUrl: 'https://github.com/pixijs/pixijs.com/tree/main/', routeBasePath: '/', versions: { - current: { + '7.3.2': { label: 'v7.x (Latest)', + path: '7.3.2', + }, + + current: { + label: 'prerelease-v8', }, }, }, diff --git a/pixi-versions.json b/pixi-versions.json index 5c639ba7f..b3ee5f1ac 100644 --- a/pixi-versions.json +++ b/pixi-versions.json @@ -8,6 +8,17 @@ "npm": "7.3.2", "prerelease": false, "latest": true, + "isCurrent": false + }, + { + "versionLabel": "prerelease-v8", + "version": "8.0.0-rc", + "releaseNotes": "https://github.com/pixijs/pixijs/releases/tag/v8.0.0-rc", + "build": "https://pixijs.download/v8.0.0-rc/pixi.min.js", + "docs": "https://pixijs.download/v8.0.0-rc/docs/index.html", + "npm": "8.0.0-rc", + "prerelease": true, + "latest": false, "isCurrent": true } ] \ No newline at end of file diff --git a/src/examples/v8.0.0-rc/advanced/collisionDetection.js b/src/examples/v8.0.0-rc/advanced/collisionDetection.js new file mode 100644 index 000000000..454a7ca6c --- /dev/null +++ b/src/examples/v8.0.0-rc/advanced/collisionDetection.js @@ -0,0 +1,179 @@ +import * as PIXI from 'pixi.js'; + +// Based somewhat on this article by Spicy Yoghurt +// URL for further reading: https://spicyyoghurt.com/tutorials/html5-javascript-game-development/collision-detection-physics +const app = new PIXI.Application({ background: '#111', resizeTo: window }); + +document.body.appendChild(app.view); + +// Options for how objects interact +// How fast the red square moves +const movementSpeed = 0.05; + +// Strength of the impulse push between two objects +const impulsePower = 5; + +// Test For Hit +// A basic AABB check between two different squares +function testForAABB(object1, object2) +{ + const bounds1 = object1.getBounds(); + const bounds2 = object2.getBounds(); + + return ( + bounds1.x < bounds2.x + bounds2.width + && bounds1.x + bounds1.width > bounds2.x + && bounds1.y < bounds2.y + bounds2.height + && bounds1.y + bounds1.height > bounds2.y + ); +} + +// Calculates the results of a collision, allowing us to give an impulse that +// shoves objects apart +function collisionResponse(object1, object2) +{ + if (!object1 || !object2) + { + return new PIXI.Point(0); + } + + const vCollision = new PIXI.Point(object2.x - object1.x, object2.y - object1.y); + + const distance = Math.sqrt( + (object2.x - object1.x) * (object2.x - object1.x) + (object2.y - object1.y) * (object2.y - object1.y), + ); + + const vCollisionNorm = new PIXI.Point(vCollision.x / distance, vCollision.y / distance); + + const vRelativeVelocity = new PIXI.Point( + object1.acceleration.x - object2.acceleration.x, + object1.acceleration.y - object2.acceleration.y, + ); + + const speed = vRelativeVelocity.x * vCollisionNorm.x + vRelativeVelocity.y * vCollisionNorm.y; + + const impulse = (impulsePower * speed) / (object1.mass + object2.mass); + + return new PIXI.Point(impulse * vCollisionNorm.x, impulse * vCollisionNorm.y); +} + +// Calculate the distance between two given points +function distanceBetweenTwoPoints(p1, p2) +{ + const a = p1.x - p2.x; + const b = p1.y - p2.y; + + return Math.hypot(a, b); +} + +// The green square we will knock about +const greenSquare = new PIXI.Sprite(PIXI.Texture.WHITE); + +greenSquare.position.set((app.screen.width - 100) / 2, (app.screen.height - 100) / 2); +greenSquare.width = 100; +greenSquare.height = 100; +greenSquare.tint = 0x00ff00; +greenSquare.acceleration = new PIXI.Point(0); +greenSquare.mass = 3; + +// The square you move around +const redSquare = new PIXI.Sprite(PIXI.Texture.WHITE); + +redSquare.position.set(0, 0); +redSquare.width = 100; +redSquare.height = 100; +redSquare.tint = 0xff0000; +redSquare.acceleration = new PIXI.Point(0); +redSquare.mass = 1; + +const mouseCoords = { x: 0, y: 0 }; + +app.stage.eventMode = 'static'; +app.stage.hitArea = app.screen; +app.stage.on('mousemove', (event) => +{ + mouseCoords.x = event.global.x; + mouseCoords.y = event.global.y; +}); + +// Listen for animate update +app.ticker.add((delta) => +{ + // Applied deacceleration for both squares, done by reducing the + // acceleration by 0.01% of the acceleration every loop + redSquare.acceleration.set(redSquare.acceleration.x * 0.99, redSquare.acceleration.y * 0.99); + greenSquare.acceleration.set(greenSquare.acceleration.x * 0.99, greenSquare.acceleration.y * 0.99); + + // Check whether the green square ever moves off the screen + // If so, reverse acceleration in that direction + if (greenSquare.x < 0 || greenSquare.x > app.screen.width - 100) + { + greenSquare.acceleration.x = -greenSquare.acceleration.x; + } + + if (greenSquare.y < 0 || greenSquare.y > app.screen.height - 100) + { + greenSquare.acceleration.y = -greenSquare.acceleration.y; + } + + // If the green square pops out of the cordon, it pops back into the + // middle + if ( + greenSquare.x < -30 + || greenSquare.x > app.screen.width + 30 + || greenSquare.y < -30 + || greenSquare.y > app.screen.height + 30 + ) + { + greenSquare.position.set((app.screen.width - 100) / 2, (app.screen.height - 100) / 2); + } + + // If the mouse is off screen, then don't update any further + if (app.screen.width > mouseCoords.x || mouseCoords.x > 0 || app.screen.height > mouseCoords.y || mouseCoords.y > 0) + { + // Get the red square's center point + const redSquareCenterPosition = new PIXI.Point( + redSquare.x + redSquare.width * 0.5, + redSquare.y + redSquare.height * 0.5, + ); + + // Calculate the direction vector between the mouse pointer and + // the red square + const toMouseDirection = new PIXI.Point( + mouseCoords.x - redSquareCenterPosition.x, + mouseCoords.y - redSquareCenterPosition.y, + ); + + // Use the above to figure out the angle that direction has + const angleToMouse = Math.atan2(toMouseDirection.y, toMouseDirection.x); + + // Figure out the speed the square should be travelling by, as a + // function of how far away from the mouse pointer the red square is + const distMouseRedSquare = distanceBetweenTwoPoints(mouseCoords, redSquareCenterPosition); + const redSpeed = distMouseRedSquare * movementSpeed; + + // Calculate the acceleration of the red square + redSquare.acceleration.set(Math.cos(angleToMouse) * redSpeed, Math.sin(angleToMouse) * redSpeed); + } + + // If the two squares are colliding + if (testForAABB(greenSquare, redSquare)) + { + // Calculate the changes in acceleration that should be made between + // each square as a result of the collision + const collisionPush = collisionResponse(greenSquare, redSquare); + // Set the changes in acceleration for both squares + + redSquare.acceleration.set(collisionPush.x * greenSquare.mass, collisionPush.y * greenSquare.mass); + greenSquare.acceleration.set(-(collisionPush.x * redSquare.mass), -(collisionPush.y * redSquare.mass)); + } + + greenSquare.x += greenSquare.acceleration.x * delta; + greenSquare.y += greenSquare.acceleration.y * delta; + + redSquare.x += redSquare.acceleration.x * delta; + redSquare.y += redSquare.acceleration.y * delta; +}); + +// Add to stage +app.stage.addChild(redSquare, greenSquare); diff --git a/src/examples/v8.0.0-rc/advanced/mouseTrail.js b/src/examples/v8.0.0-rc/advanced/mouseTrail.js new file mode 100644 index 000000000..e0457e944 --- /dev/null +++ b/src/examples/v8.0.0-rc/advanced/mouseTrail.js @@ -0,0 +1,101 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +// Get the texture for rope. +const trailTexture = PIXI.Texture.from('https://pixijs.com/assets/trail.png'); +const historyX = []; +const historyY = []; +// historySize determines how long the trail will be. +const historySize = 20; +// ropeSize determines how smooth the trail will be. +const ropeSize = 100; +const points = []; + +// Create history array. +for (let i = 0; i < historySize; i++) +{ + historyX.push(0); + historyY.push(0); +} +// Create rope points. +for (let i = 0; i < ropeSize; i++) +{ + points.push(new PIXI.Point(0, 0)); +} + +// Create the rope +const rope = new PIXI.SimpleRope(trailTexture, points); + +// Set the blendmode +rope.blendmode = PIXI.BLEND_MODES.ADD; + +app.stage.addChild(rope); + +let mouseposition = null; + +app.stage.eventMode = 'static'; +app.stage.hitArea = app.screen; +app.stage.on('mousemove', (event) => +{ + mouseposition = mouseposition || { x: 0, y: 0 }; + mouseposition.x = event.global.x; + mouseposition.y = event.global.y; +}); + +// Listen for animate update +app.ticker.add(() => +{ + if (!mouseposition) return; + + // Update the mouse values to history + historyX.pop(); + historyX.unshift(mouseposition.x); + historyY.pop(); + historyY.unshift(mouseposition.y); + // Update the points to correspond with history. + for (let i = 0; i < ropeSize; i++) + { + const p = points[i]; + + // Smooth the curve with cubic interpolation to prevent sharp edges. + const ix = cubicInterpolation(historyX, (i / ropeSize) * historySize); + const iy = cubicInterpolation(historyY, (i / ropeSize) * historySize); + + p.x = ix; + p.y = iy; + } +}); + +/** + * Cubic interpolation based on https://github.com/osuushi/Smooth.js + */ +function clipInput(k, arr) +{ + if (k < 0) k = 0; + if (k > arr.length - 1) k = arr.length - 1; + + return arr[k]; +} + +function getTangent(k, factor, array) +{ + return (factor * (clipInput(k + 1, array) - clipInput(k - 1, array))) / 2; +} + +function cubicInterpolation(array, t, tangentFactor) +{ + if (tangentFactor === null) tangentFactor = 1; + + const k = Math.floor(t); + const m = [getTangent(k, tangentFactor, array), getTangent(k + 1, tangentFactor, array)]; + const p = [clipInput(k, array), clipInput(k + 1, array)]; + + t -= k; + const t2 = t * t; + const t3 = t * t2; + + return (2 * t3 - 3 * t2 + 1) * p[0] + (t3 - 2 * t2 + t) * m[0] + (-2 * t3 + 3 * t2) * p[1] + (t3 - t2) * m[1]; +} diff --git a/src/examples/v8.0.0-rc/advanced/scratchCard.js b/src/examples/v8.0.0-rc/advanced/scratchCard.js new file mode 100644 index 000000000..b5e2b0274 --- /dev/null +++ b/src/examples/v8.0.0-rc/advanced/scratchCard.js @@ -0,0 +1,83 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +// prepare circle texture, that will be our brush +const brush = new PIXI.Graphics().beginFill(0xffffff).drawCircle(0, 0, 50); + +// Create a line that will interpolate the drawn points +const line = new PIXI.Graphics(); + +PIXI.Assets.add('t1', 'https://pixijs.com/assets/bg_grass.jpg'); +PIXI.Assets.add('t2', 'https://pixijs.com/assets/bg_rotate.jpg'); +PIXI.Assets.load(['t1', 't2']).then(setup); + +function setup() +{ + const { width, height } = app.screen; + const stageSize = { width, height }; + + const background = Object.assign(PIXI.Sprite.from('t1'), stageSize); + const imageToReveal = Object.assign(PIXI.Sprite.from('t2'), stageSize); + const renderTexture = PIXI.RenderTexture.create(stageSize); + const renderTextureSprite = new PIXI.Sprite(renderTexture); + + imageToReveal.mask = renderTextureSprite; + + app.stage.addChild(background, imageToReveal, renderTextureSprite); + + app.stage.eventMode = 'static'; + app.stage.hitArea = app.screen; + app.stage + .on('pointerdown', pointerDown) + .on('pointerup', pointerUp) + .on('pointerupoutside', pointerUp) + .on('pointermove', pointerMove); + + let dragging = false; + let lastDrawnPoint = null; + + function pointerMove({ global: { x, y } }) + { + if (dragging) + { + brush.position.set(x, y); + app.renderer.render(brush, { + renderTexture, + clear: false, + skipUpdateTransform: false, + }); + // Smooth out the drawing a little bit to make it look nicer + // this connects the previous drawn point to the current one + // using a line + if (lastDrawnPoint) + { + line.clear() + .lineStyle({ width: 100, color: 0xffffff }) + .moveTo(lastDrawnPoint.x, lastDrawnPoint.y) + .lineTo(x, y); + app.renderer.render(line, { + renderTexture, + clear: false, + skipUpdateTransform: false, + }); + } + lastDrawnPoint = lastDrawnPoint || new PIXI.Point(); + lastDrawnPoint.set(x, y); + } + } + + function pointerDown(event) + { + dragging = true; + pointerMove(event); + } + + function pointerUp(event) + { + dragging = false; + lastDrawnPoint = null; + } +} diff --git a/src/examples/v8.0.0-rc/advanced/screenShot.js b/src/examples/v8.0.0-rc/advanced/screenShot.js new file mode 100644 index 000000000..06cbd30cc --- /dev/null +++ b/src/examples/v8.0.0-rc/advanced/screenShot.js @@ -0,0 +1,58 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ backgroundColor: '#111', resizeTo: window }); + +document.body.appendChild(app.view); + +const texture = PIXI.Texture.from('https://pixijs.com/assets/bunny.png'); +const bunnyContainer = new PIXI.Container(); + +async function takeScreenshot() +{ + app.stop(); + const url = await app.renderer.extract.base64(bunnyContainer); + const a = document.createElement('a'); + + document.body.append(a); + a.download = 'screenshot'; + a.href = url; + a.click(); + a.remove(); + app.start(); +} + +app.stage.eventMode = 'static'; +app.stage.hitArea = app.screen; +app.stage.on('pointerdown', takeScreenshot); + +for (let i = 0; i < 25; i++) +{ + const bunny = new PIXI.Sprite(texture); + + bunny.anchor.set(0.5); + bunny.x = (i % 5) * 40; + bunny.y = Math.floor(i / 5) * 40; + bunnyContainer.addChild(bunny); +} + +bunnyContainer.x = 400; +bunnyContainer.y = 300; +bunnyContainer.pivot.x = bunnyContainer.width / 2; +bunnyContainer.pivot.y = bunnyContainer.height / 2; + +app.ticker.add((delta) => +{ + bunnyContainer.rotation += 0.01 * delta; +}); + +const style = new PIXI.TextStyle({ + fontFamily: 'Roboto', + fill: '#999', +}); + +const screenshotText = new PIXI.Text('Click To Take Screenshot', style); + +screenshotText.x = Math.round((app.screen.width - screenshotText.width) / 2); +screenshotText.y = Math.round(screenshotText.height / 2); + +app.stage.addChild(screenshotText, bunnyContainer); diff --git a/src/examples/v8.0.0-rc/advanced/slots.js b/src/examples/v8.0.0-rc/advanced/slots.js new file mode 100644 index 000000000..d25099efd --- /dev/null +++ b/src/examples/v8.0.0-rc/advanced/slots.js @@ -0,0 +1,239 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +PIXI.Assets.load([ + 'https://pixijs.com/assets/eggHead.png', + 'https://pixijs.com/assets/flowerTop.png', + 'https://pixijs.com/assets/helmlok.png', + 'https://pixijs.com/assets/skully.png', +]).then(onAssetsLoaded); + +const REEL_WIDTH = 160; +const SYMBOL_SIZE = 150; + +// onAssetsLoaded handler builds the example. +function onAssetsLoaded() +{ + // Create different slot symbols. + const slotTextures = [ + PIXI.Texture.from('https://pixijs.com/assets/eggHead.png'), + PIXI.Texture.from('https://pixijs.com/assets/flowerTop.png'), + PIXI.Texture.from('https://pixijs.com/assets/helmlok.png'), + PIXI.Texture.from('https://pixijs.com/assets/skully.png'), + ]; + + // Build the reels + const reels = []; + const reelContainer = new PIXI.Container(); + + for (let i = 0; i < 5; i++) + { + const rc = new PIXI.Container(); + + rc.x = i * REEL_WIDTH; + reelContainer.addChild(rc); + + const reel = { + container: rc, + symbols: [], + position: 0, + previousPosition: 0, + blur: new PIXI.filters.BlurFilter(), + }; + + reel.blur.blurX = 0; + reel.blur.blurY = 0; + rc.filters = [reel.blur]; + + // Build the symbols + for (let j = 0; j < 4; j++) + { + const symbol = new PIXI.Sprite(slotTextures[Math.floor(Math.random() * slotTextures.length)]); + // Scale the symbol to fit symbol area. + + symbol.y = j * SYMBOL_SIZE; + symbol.scale.x = symbol.scale.y = Math.min(SYMBOL_SIZE / symbol.width, SYMBOL_SIZE / symbol.height); + symbol.x = Math.round((SYMBOL_SIZE - symbol.width) / 2); + reel.symbols.push(symbol); + rc.addChild(symbol); + } + reels.push(reel); + } + app.stage.addChild(reelContainer); + + // Build top & bottom covers and position reelContainer + const margin = (app.screen.height - SYMBOL_SIZE * 3) / 2; + + reelContainer.y = margin; + reelContainer.x = Math.round(app.screen.width - REEL_WIDTH * 5); + const top = new PIXI.Graphics(); + + top.beginFill(0, 1); + top.drawRect(0, 0, app.screen.width, margin); + const bottom = new PIXI.Graphics(); + + bottom.beginFill(0, 1); + bottom.drawRect(0, SYMBOL_SIZE * 3 + margin, app.screen.width, margin); + + // Add play text + const style = new PIXI.TextStyle({ + fontFamily: 'Arial', + fontSize: 36, + fontStyle: 'italic', + fontWeight: 'bold', + fill: ['#ffffff', '#00ff99'], // gradient + stroke: '#4a1850', + strokeThickness: 5, + dropShadow: true, + dropShadowColor: '#000000', + dropShadowBlur: 4, + dropShadowAngle: Math.PI / 6, + dropShadowDistance: 6, + wordWrap: true, + wordWrapWidth: 440, + }); + + const playText = new PIXI.Text('Spin the wheels!', style); + + playText.x = Math.round((bottom.width - playText.width) / 2); + playText.y = app.screen.height - margin + Math.round((margin - playText.height) / 2); + bottom.addChild(playText); + + // Add header text + const headerText = new PIXI.Text('PIXI MONSTER SLOTS!', style); + + headerText.x = Math.round((top.width - headerText.width) / 2); + headerText.y = Math.round((margin - headerText.height) / 2); + top.addChild(headerText); + + app.stage.addChild(top); + app.stage.addChild(bottom); + + // Set the interactivity. + bottom.eventMode = 'static'; + bottom.cursor = 'pointer'; + bottom.addListener('pointerdown', () => + { + startPlay(); + }); + + let running = false; + + // Function to start playing. + function startPlay() + { + if (running) return; + running = true; + + for (let i = 0; i < reels.length; i++) + { + const r = reels[i]; + const extra = Math.floor(Math.random() * 3); + const target = r.position + 10 + i * 5 + extra; + const time = 2500 + i * 600 + extra * 600; + + tweenTo(r, 'position', target, time, backout(0.5), null, i === reels.length - 1 ? reelsComplete : null); + } + } + + // Reels done handler. + function reelsComplete() + { + running = false; + } + + // Listen for animate update. + app.ticker.add((delta) => + { + // Update the slots. + for (let i = 0; i < reels.length; i++) + { + const r = reels[i]; + // Update blur filter y amount based on speed. + // This would be better if calculated with time in mind also. Now blur depends on frame rate. + + r.blur.blurY = (r.position - r.previousPosition) * 8; + r.previousPosition = r.position; + + // Update symbol positions on reel. + for (let j = 0; j < r.symbols.length; j++) + { + const s = r.symbols[j]; + const prevy = s.y; + + s.y = ((r.position + j) % r.symbols.length) * SYMBOL_SIZE - SYMBOL_SIZE; + if (s.y < 0 && prevy > SYMBOL_SIZE) + { + // Detect going over and swap a texture. + // This should in proper product be determined from some logical reel. + s.texture = slotTextures[Math.floor(Math.random() * slotTextures.length)]; + s.scale.x = s.scale.y = Math.min(SYMBOL_SIZE / s.texture.width, SYMBOL_SIZE / s.texture.height); + s.x = Math.round((SYMBOL_SIZE - s.width) / 2); + } + } + } + }); +} + +// Very simple tweening utility function. This should be replaced with a proper tweening library in a real product. +const tweening = []; + +function tweenTo(object, property, target, time, easing, onchange, oncomplete) +{ + const tween = { + object, + property, + propertyBeginValue: object[property], + target, + easing, + time, + change: onchange, + complete: oncomplete, + start: Date.now(), + }; + + tweening.push(tween); + + return tween; +} +// Listen for animate update. +app.ticker.add((delta) => +{ + const now = Date.now(); + const remove = []; + + for (let i = 0; i < tweening.length; i++) + { + const t = tweening[i]; + const phase = Math.min(1, (now - t.start) / t.time); + + t.object[t.property] = lerp(t.propertyBeginValue, t.target, t.easing(phase)); + if (t.change) t.change(t); + if (phase === 1) + { + t.object[t.property] = t.target; + if (t.complete) t.complete(t); + remove.push(t); + } + } + for (let i = 0; i < remove.length; i++) + { + tweening.splice(tweening.indexOf(remove[i]), 1); + } +}); + +// Basic lerp funtion. +function lerp(a1, a2, t) +{ + return a1 * (1 - t) + a2 * t; +} + +// Backout function from tweenjs. +// https://github.com/CreateJS/TweenJS/blob/master/src/tweenjs/Ease.js +function backout(amount) +{ + return (t) => --t * t * ((amount + 1) * t + amount) + 1; +} diff --git a/src/examples/v8.0.0-rc/advanced/spinners.js b/src/examples/v8.0.0-rc/advanced/spinners.js new file mode 100644 index 000000000..3503c3719 --- /dev/null +++ b/src/examples/v8.0.0-rc/advanced/spinners.js @@ -0,0 +1,427 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +/* --------------------------------------- + Spinner 1. Square with radial completion. + -------------------------------------- */ +const generateSpinner1 = (position) => +{ + const container = new PIXI.Container(); + + container.position = position; + app.stage.addChild(container); + + const base = PIXI.Sprite.from('https://pixijs.com/assets/bg_scene_rotate.jpg'); + const size = 100; + + base.width = size; + base.height = size; + + const bottom = PIXI.Sprite.from('https://pixijs.com/assets/bg_rotate.jpg'); + + bottom.width = size; + bottom.height = size; + + const mask = new PIXI.Graphics(); + + mask.position.set(size / 2, size / 2); + base.mask = mask; + window.mask = mask; + + container.addChild(bottom); + container.addChild(base); + container.addChild(mask); + + let phase = 0; + + return (delta) => + { + // Update phase + phase += delta / 60; + phase %= Math.PI * 2; + + // Calculate target point. + const x = Math.cos(phase - Math.PI / 2) * size; + const y = Math.sin(phase - Math.PI / 2) * size; + + const segments = [ + [-size / 2, -size / 2, size / 2, -size / 2], // top segment + [size / 2, -size / 2, size / 2, size / 2], // right + [-size / 2, size / 2, size / 2, size / 2], // bottom + [-size / 2, -size / 2, -size / 2, size / 2], // left + ]; + + // Find the intersecting segment. + let intersection = null; + let winding = 0; + + for (let i = 0; i < segments.length; i++) + { + const segment = segments[i]; + const hit = intersect(0, 0, x, y, segment[0], segment[1], segment[2], segment[3]); + + if (hit) + { + intersection = hit; + if (i === 0) winding = hit.x > 0 ? 0 : 4; + else winding = i; + break; + } + } + + const corners = [ + size / 2, + -size / 2, // Top right + size / 2, + size / 2, // Bottom right + -size / 2, + size / 2, // Bottom left + -size / 2, + -size / 2, // Top left, + 0, + -size / 2, // End point + ]; + + // Redraw mask + mask.clear(); + mask.lineStyle(2, 0xff0000, 1); + mask.beginFill(0xff0000, 1); + mask.moveTo(0, -size / 2); + mask.lineTo(0, 0); + + mask.lineTo(intersection.x, intersection.y); + + // fill the corners + for (let i = winding; i < corners.length / 2; i++) + { + mask.lineTo(corners[i * 2], corners[i * 2 + 1]); + } + mask.endFill(); + }; +}; + +/* ----------------------- + Spinner 2. Scaling balls. + ---------------------- */ +const generateSpinner2 = (position) => +{ + const container = new PIXI.Container(); + + container.position = position; + app.stage.addChild(container); + + const size = 100; + const ballAmount = 7; + const balls = []; + + for (let i = 0; i < ballAmount; i++) + { + const ball = PIXI.Sprite.from('https://pixijs.com/assets/circle.png'); + + ball.anchor.set(0.5); + container.addChild(ball); + ball.position.set( + size / 2 + (Math.cos((i / ballAmount) * Math.PI * 2) * size) / 3, + size / 2 + (Math.sin((i / ballAmount) * Math.PI * 2) * size) / 3, + ); + balls.push(ball); + } + + let phase = 0; + + return (delta) => + { + // Update phase + phase += delta / 60; + phase %= Math.PI * 2; + + // Update ball scales + balls.forEach((b, i) => + { + const sin = Math.sin((i / ballAmount) * Math.PI - phase); + // Multiply sin with itself to get more steeper edge. + + b.scale.set(Math.abs(sin * sin * sin * 0.5) + 0.5); + }); + }; +}; + +/* --------------------- + Spinner 3. Radial mask. + -------------------- */ +const generateSpinner3 = (position) => +{ + const container = new PIXI.Container(); + + container.position = position; + app.stage.addChild(container); + + const base = PIXI.Sprite.from('https://pixijs.com/assets/bg_scene_rotate.jpg'); + const size = 100; + + base.width = size; + base.height = size; + + const mask = new PIXI.Graphics(); + + mask.position.set(size / 2, size / 2); + base.mask = mask; + window.mask = mask; + + container.addChild(base); + container.addChild(mask); + + let phase = 0; + + return (delta) => + { + // Update phase + phase += delta / 60; + phase %= Math.PI * 2; + + const angleStart = 0 - Math.PI / 2; + const angle = phase + angleStart; + const radius = 50; + + const x1 = Math.cos(angleStart) * radius; + const y1 = Math.sin(angleStart) * radius; + + // Redraw mask + mask.clear(); + mask.lineStyle(2, 0xff0000, 1); + mask.beginFill(0xff0000, 1); + mask.moveTo(0, 0); + mask.lineTo(x1, y1); + mask.arc(0, 0, radius, angleStart, angle, false); + mask.lineTo(0, 0); + mask.endFill(); + }; +}; + +/* --------------------------------- + Spinner 4. Rounded rectangle edges. + ------------------------------- */ +const generateSpinner4 = (position) => +{ + const container = new PIXI.Container(); + + container.position = position; + app.stage.addChild(container); + + const size = 100; + const arcRadius = 15; + + const base = PIXI.Sprite.from('https://pixijs.com/assets/bg_scene_rotate.jpg'); + + base.width = size; + base.height = size; + + // For better performance having assets prerounded would be better than masking. + const roundingMask = new PIXI.Graphics(); + + roundingMask.beginFill(0, 1); + roundingMask.lineStyle(1, 0xff0000, 1); + roundingMask.drawRoundedRect(0, 0, size, size, arcRadius); + roundingMask.endFill(); + base.mask = roundingMask; + + // The edge could be replaced with image as well. + const lineSize = 5; + const edge = new PIXI.Graphics(); + + edge.lineStyle(lineSize, 0xff0000, 1); + edge.drawRoundedRect(0, 0, size, size, arcRadius); + edge.endFill(); + + // Mask in this example works basically the same way as in example 1. + // Except it is reversed and calculates the mask in straight lines in edges. + const mask = new PIXI.Graphics(); + + mask.position.set(size / 2, size / 2); + edge.mask = mask; + + container.addChild(base); + container.addChild(roundingMask); + container.addChild(edge); + container.addChild(mask); + + let phase = 0; + + return (delta) => + { + // Update phase + phase += delta / 160; + phase %= Math.PI * 2; + + // Calculate target point. + const x = Math.cos(phase - Math.PI / 2) * size; + const y = Math.sin(phase - Math.PI / 2) * size; + // Line segments + const segments = [ + [-size / 2 + lineSize, -size / 2 + lineSize, size / 2 - lineSize, -size / 2 + lineSize], // top segment + [size / 2 - lineSize, -size / 2 + lineSize, size / 2 - lineSize, size / 2 - lineSize], // right + [-size / 2 + lineSize, size / 2 - lineSize, size / 2 - lineSize, size / 2 - lineSize], // bottom + [-size / 2 + lineSize, -size / 2 + lineSize, -size / 2 + lineSize, size / 2 - lineSize], // left + ]; + // To which dir should mask continue at each segment + let outDir = [ + [0, -1], + [1, 0], + [0, 1], + [-1, 0], + ]; + + // Find the intersecting segment. + let intersection = null; + let winding = 0; + // What direction should the line continue after hit has been found before hitting the line size + + for (let i = 0; i < segments.length; i++) + { + const segment = segments[i]; + const hit = intersect(0, 0, x, y, segment[0], segment[1], segment[2], segment[3]); + + if (hit) + { + intersection = hit; + if (i === 0) winding = hit.x < 0 ? 0 : 4; + else winding = 4 - i; + outDir = outDir[i]; + break; + } + } + + const corners = [ + -size / 2 - lineSize, + -size / 2 - lineSize, // Top left, + -size / 2 - lineSize, + size / 2 + lineSize, // Bottom left + size / 2 + lineSize, + size / 2 + lineSize, // Bottom right + size / 2 + lineSize, + -size / 2 - lineSize, // Top right + ]; + + // Redraw mask + mask.clear(); + mask.lineStyle(2, 0x00ff00, 1); + mask.beginFill(0xff0000, 1); + + mask.moveTo(0, 0); + mask.moveTo(0, -size / 2 - lineSize); + + // fill the corners + for (let i = 0; i < winding; i++) + { + mask.lineTo(corners[i * 2], corners[i * 2 + 1]); + } + + mask.lineTo(intersection.x + outDir[0] * lineSize * 2, intersection.y + outDir[1] * lineSize * 2); + mask.lineTo(intersection.x, intersection.y); + mask.lineTo(0, 0); + + mask.endFill(); + }; +}; + +/* --------------------- + Spinner 5. Rounded rectangle fixed length spinner by jonlepage + -------------------- */ +const generateSpinner5 = (position) => +{ + const container = new PIXI.Container(); + + container.position = position; + app.stage.addChild(container); + + const halfCircle = new PIXI.Graphics(); + + halfCircle.beginFill(0xff0000); + halfCircle.lineStyle(2, 0xffffff); + halfCircle.arc(0, 0, 100, 0, Math.PI); + halfCircle.endFill(); + halfCircle.position.set(50, 50); + + const rectangle = new PIXI.Graphics(); + + rectangle.lineStyle(2, 0xffffff, 1); + rectangle.drawRoundedRect(0, 0, 100, 100, 16); + rectangle.endFill(); + rectangle.mask = halfCircle; + + container.addChild(rectangle); + container.addChild(halfCircle); + + let phase = 0; + + return (delta) => + { + // Update phase + phase += delta / 6; + phase %= Math.PI * 2; + + halfCircle.rotation = phase; + }; +}; + +const onTick = [ + generateSpinner1(new PIXI.Point(50, 50)), + generateSpinner2(new PIXI.Point(160, 50)), + generateSpinner3(new PIXI.Point(270, 50)), + generateSpinner4(new PIXI.Point(380, 50)), + generateSpinner5(new PIXI.Point(490, 50)), +]; + +// Listen for animate update +app.ticker.add((delta) => +{ + // Call tick handling for each spinner. + onTick.forEach((cb) => + { + cb(delta); + }); +}); + +/** + * Helper functions + + line intercept math by Paul Bourke http://paulbourke.net/geometry/pointlineplane/ + Determine the intersection point of two line segments + Return FALSE if the lines don't intersect + + Code modified from original to match pixi examples linting rules. +*/ +function intersect(x1, y1, x2, y2, x3, y3, x4, y4) +{ + // Check if none of the lines are of length 0 + if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) + { + return false; + } + + const denominator = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); + + // Lines are parallel + if (denominator === 0) + { + return false; + } + + const ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denominator; + const ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denominator; + + // is the intersection along the segments + if (ua < 0 || ua > 1 || ub < 0 || ub > 1) + { + return false; + } + + // Return a object with the x and y coordinates of the intersection + const x = x1 + ua * (x2 - x1); + const y = y1 + ua * (y2 - y1); + + return { x, y }; +} diff --git a/src/examples/v8.0.0-rc/advanced/starWarp.js b/src/examples/v8.0.0-rc/advanced/starWarp.js new file mode 100644 index 000000000..c715e6723 --- /dev/null +++ b/src/examples/v8.0.0-rc/advanced/starWarp.js @@ -0,0 +1,89 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +// Get the texture for star. +const starTexture = PIXI.Texture.from('https://pixijs.com/assets/star.png'); + +const starAmount = 1000; +let cameraZ = 0; +const fov = 20; +const baseSpeed = 0.025; +let speed = 0; +let warpSpeed = 0; +const starStretch = 5; +const starBaseSize = 0.05; + +// Create the stars +const stars = []; + +for (let i = 0; i < starAmount; i++) +{ + const star = { + sprite: new PIXI.Sprite(starTexture), + z: 0, + x: 0, + y: 0, + }; + + star.sprite.anchor.x = 0.5; + star.sprite.anchor.y = 0.7; + randomizeStar(star, true); + app.stage.addChild(star.sprite); + stars.push(star); +} + +function randomizeStar(star, initial) +{ + star.z = initial ? Math.random() * 2000 : cameraZ + Math.random() * 1000 + 2000; + + // Calculate star positions with radial random coordinate so no star hits the camera. + const deg = Math.random() * Math.PI * 2; + const distance = Math.random() * 50 + 1; + + star.x = Math.cos(deg) * distance; + star.y = Math.sin(deg) * distance; +} + +// Change flight speed every 5 seconds +setInterval(() => +{ + warpSpeed = warpSpeed > 0 ? 0 : 1; +}, 5000); + +// Listen for animate update +app.ticker.add((delta) => +{ + // Simple easing. This should be changed to proper easing function when used for real. + speed += (warpSpeed - speed) / 20; + cameraZ += delta * 10 * (speed + baseSpeed); + for (let i = 0; i < starAmount; i++) + { + const star = stars[i]; + + if (star.z < cameraZ) randomizeStar(star); + + // Map star 3d position to 2d with really simple projection + const z = star.z - cameraZ; + + star.sprite.x = star.x * (fov / z) * app.renderer.screen.width + app.renderer.screen.width / 2; + star.sprite.y = star.y * (fov / z) * app.renderer.screen.width + app.renderer.screen.height / 2; + + // Calculate star scale & rotation. + const dxCenter = star.sprite.x - app.renderer.screen.width / 2; + const dyCenter = star.sprite.y - app.renderer.screen.height / 2; + const distanceCenter = Math.sqrt(dxCenter * dxCenter + dyCenter * dyCenter); + const distanceScale = Math.max(0, (2000 - z) / 2000); + + star.sprite.scale.x = distanceScale * starBaseSize; + // Star is looking towards center so that y axis is towards center. + // Scale the star depending on how fast we are moving, what the stretchfactor is + // and depending on how far away it is from the center. + star.sprite.scale.y + = distanceScale * starBaseSize + + (distanceScale * speed * starStretch * distanceCenter) / app.renderer.screen.width; + star.sprite.rotation = Math.atan2(dyCenter, dxCenter) + Math.PI / 2; + } +}); diff --git a/src/examples/v8.0.0-rc/assets/async.js b/src/examples/v8.0.0-rc/assets/async.js new file mode 100644 index 000000000..8b4b501ce --- /dev/null +++ b/src/examples/v8.0.0-rc/assets/async.js @@ -0,0 +1,26 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +// await can only be used inside an async function +async function init() +{ + const texture = await PIXI.Assets.load('https://pixijs.com/assets/bunny.png'); + + // create a new Sprite from the awaited loaded Texture + const bunny = PIXI.Sprite.from(texture); + + // center the sprite's anchor point + bunny.anchor.set(0.5); + + // move the sprite to the center of the screen + bunny.x = app.screen.width / 2; + bunny.y = app.screen.height / 2; + + app.stage.addChild(bunny); +} + +// Call that async function +init(); diff --git a/src/examples/v8.0.0-rc/assets/background.js b/src/examples/v8.0.0-rc/assets/background.js new file mode 100644 index 000000000..295d6667a --- /dev/null +++ b/src/examples/v8.0.0-rc/assets/background.js @@ -0,0 +1,37 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +// Add the assets to load +PIXI.Assets.add('flowerTop', 'https://pixijs.com/assets/flowerTop.png'); +PIXI.Assets.add('eggHead', 'https://pixijs.com/assets/eggHead.png'); + +// Allow the assets to load in the background +PIXI.Assets.backgroundLoad(['flowerTop', 'eggHead']); + +// If the background load hasn't loaded this asset yet, calling load forces this asset to load now. +PIXI.Assets.load('eggHead').then((texture) => +{ + // auxiliar flag for toggling the texture + let isEggHead = true; + + // create a new Sprite from the resolved loaded texture + const character = new PIXI.Sprite(texture); + + character.anchor.set(0.5); + character.x = app.screen.width / 2; + character.y = app.screen.height / 2; + character.eventMode = 'static'; + character.cursor = 'pointer'; + + app.stage.addChild(character); + + character.on('pointertap', async () => + { + isEggHead = !isEggHead; + // These promise are already resolved in the cache. + character.texture = await PIXI.Assets.load(isEggHead ? 'eggHead' : 'flowerTop'); + }); +}); diff --git a/src/examples/v8.0.0-rc/assets/bundle.js b/src/examples/v8.0.0-rc/assets/bundle.js new file mode 100644 index 000000000..e60ea4b95 --- /dev/null +++ b/src/examples/v8.0.0-rc/assets/bundle.js @@ -0,0 +1,91 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +async function init() +{ + // manifest example + const manifestExample = { + bundles: [ + { + name: 'load-screen', + assets: [ + { + name: 'flowerTop', + srcs: 'https://pixijs.com/assets/flowerTop.png', + }, + ], + }, + { + name: 'game-screen', + assets: [ + { + name: 'eggHead', + srcs: 'https://pixijs.com/assets/eggHead.png', + }, + ], + }, + ], + }; + + await PIXI.Assets.init({ manifest: manifestExample }); + + // bundles can be loaded in the background too! + PIXI.Assets.backgroundLoadBundle(['load-screen', 'game-screen']); + + makeLoadScreen(); +} + +async function makeLoadScreen() +{ + // get the assets from the load screen bundle. + // If the bundle was already downloaded the promise resolves instantly! + const loadScreenAssets = await PIXI.Assets.loadBundle('load-screen'); + + // create a new Sprite from the resolved loaded texture + const goNext = new PIXI.Sprite(loadScreenAssets.flowerTop); + + goNext.anchor.set(0.5); + goNext.x = app.screen.width / 2; + goNext.y = app.screen.height / 2; + app.stage.addChild(goNext); + + goNext.eventMode = 'static'; + goNext.cursor = 'pointer'; + + goNext.on('pointertap', async () => + { + goNext.destroy(); + makeGameScreen(); + }); +} + +async function makeGameScreen() +{ + // Wait here until you get the assets + // If the user spends enough time in the load screen by the time they reach the game screen + // the assets are completely loaded and the promise resolves instantly! + const loadScreenAssets = await PIXI.Assets.loadBundle('game-screen'); + + // create a new Sprite from the resolved loaded texture + const goBack = new PIXI.Sprite(loadScreenAssets.eggHead); + + goBack.anchor.set(0.5); + goBack.x = app.screen.width / 2; + goBack.y = app.screen.height / 2; + app.stage.addChild(goBack); + + goBack.eventMode = 'static'; + goBack.cursor = 'pointer'; + + goBack.on('pointertap', async () => + { + goBack.destroy(); + // The user can go back and the files are already downloaded + makeLoadScreen(); + }); +} + +init(); diff --git a/src/examples/v8.0.0-rc/assets/multiple.js b/src/examples/v8.0.0-rc/assets/multiple.js new file mode 100644 index 000000000..119dc312e --- /dev/null +++ b/src/examples/v8.0.0-rc/assets/multiple.js @@ -0,0 +1,32 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +// Add the assets to load +PIXI.Assets.add('flowerTop', 'https://pixijs.com/assets/flowerTop.png'); +PIXI.Assets.add('eggHead', 'https://pixijs.com/assets/eggHead.png'); + +// Load the assets and get a resolved promise once both are loaded +const texturesPromise = PIXI.Assets.load(['flowerTop', 'eggHead']); // => Promise<{flowerTop: Texture, eggHead: Texture}> + +// When the promise resolves, we have the texture! +texturesPromise.then((textures) => +{ + // create a new Sprite from the resolved loaded Textures + + const flower = PIXI.Sprite.from(textures.flowerTop); + + flower.anchor.set(0.5); + flower.x = app.screen.width * 0.25; + flower.y = app.screen.height / 2; + app.stage.addChild(flower); + + const egg = PIXI.Sprite.from(textures.eggHead); + + egg.anchor.set(0.5); + egg.x = app.screen.width * 0.75; + egg.y = app.screen.height / 2; + app.stage.addChild(egg); +}); diff --git a/src/examples/v8.0.0-rc/assets/promise.js b/src/examples/v8.0.0-rc/assets/promise.js new file mode 100644 index 000000000..631bc5dcd --- /dev/null +++ b/src/examples/v8.0.0-rc/assets/promise.js @@ -0,0 +1,24 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +// Start loading right away and create a promise +const texturePromise = PIXI.Assets.load('https://pixijs.com/assets/bunny.png'); + +// When the promise resolves, we have the texture! +texturePromise.then((resolvedTexture) => +{ + // create a new Sprite from the resolved loaded Texture + const bunny = PIXI.Sprite.from(resolvedTexture); + + // center the sprite's anchor point + bunny.anchor.set(0.5); + + // move the sprite to the center of the screen + bunny.x = app.screen.width / 2; + bunny.y = app.screen.height / 2; + + app.stage.addChild(bunny); +}); diff --git a/src/examples/v8.0.0-rc/basic/blendModes.js b/src/examples/v8.0.0-rc/basic/blendModes.js new file mode 100644 index 000000000..d4e2c8a79 --- /dev/null +++ b/src/examples/v8.0.0-rc/basic/blendModes.js @@ -0,0 +1,92 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +// create a new background sprite +const background = PIXI.Sprite.from('https://pixijs.com/assets/bg_rotate.jpg'); + +background.width = app.screen.width; +background.height = app.screen.height; +app.stage.addChild(background); + +// create an array to store a reference to the dudes +const dudeArray = []; + +const totaldudes = 20; + +for (let i = 0; i < totaldudes; i++) +{ + // create a new Sprite that uses the image name that we just generated as its source + const dude = PIXI.Sprite.from('https://pixijs.com/assets/flowerTop.png'); + + dude.anchor.set(0.5); + + // set a random scale for the dude + dude.scale.set(0.8 + Math.random() * 0.3); + + // finally let's set the dude to be at a random position... + dude.x = Math.floor(Math.random() * app.screen.width); + dude.y = Math.floor(Math.random() * app.screen.height); + + // The important bit of this example, this is how you change the default blend mode of the sprite + dude.blendMode = PIXI.BLEND_MODES.ADD; + + // create some extra properties that will control movement + dude.direction = Math.random() * Math.PI * 2; + + // this number will be used to modify the direction of the dude over time + dude.turningSpeed = Math.random() - 0.8; + + // create a random speed for the dude between 0 - 2 + dude.speed = 2 + Math.random() * 2; + + // finally we push the dude into the dudeArray so it it can be easily accessed later + dudeArray.push(dude); + + app.stage.addChild(dude); +} + +// create a bounding box for the little dudes +const dudeBoundsPadding = 100; + +const dudeBounds = new PIXI.Rectangle( + -dudeBoundsPadding, + -dudeBoundsPadding, + app.screen.width + dudeBoundsPadding * 2, + app.screen.height + dudeBoundsPadding * 2, +); + +app.ticker.add(() => +{ + // iterate through the dudes and update the positions + for (let i = 0; i < dudeArray.length; i++) + { + const dude = dudeArray[i]; + + dude.direction += dude.turningSpeed * 0.01; + dude.x += Math.sin(dude.direction) * dude.speed; + dude.y += Math.cos(dude.direction) * dude.speed; + dude.rotation = -dude.direction - Math.PI / 2; + + // wrap the dudes by testing their bounds... + if (dude.x < dudeBounds.x) + { + dude.x += dudeBounds.width; + } + else if (dude.x > dudeBounds.x + dudeBounds.width) + { + dude.x -= dudeBounds.width; + } + + if (dude.y < dudeBounds.y) + { + dude.y += dudeBounds.height; + } + else if (dude.y > dudeBounds.y + dudeBounds.height) + { + dude.y -= dudeBounds.height; + } + } +}); diff --git a/src/examples/v8.0.0-rc/basic/cacheAsBitmap.js b/src/examples/v8.0.0-rc/basic/cacheAsBitmap.js new file mode 100644 index 000000000..d5942007d --- /dev/null +++ b/src/examples/v8.0.0-rc/basic/cacheAsBitmap.js @@ -0,0 +1,73 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +app.stop(); + +// load resources +PIXI.Assets.load('https://pixijs.com/assets/spritesheet/monsters.json').then(onAssetsLoaded); + +// holder to store aliens +const aliens = []; +const alienFrames = ['eggHead.png', 'flowerTop.png', 'helmlok.png', 'skully.png']; + +let count = 0; + +// create an empty container +const alienContainer = new PIXI.Container(); + +alienContainer.x = 400; +alienContainer.y = 300; + +// make the stage interactive +app.stage.eventMode = 'static'; +app.stage.addChild(alienContainer); + +function onAssetsLoaded() +{ + // add a bunch of aliens with textures from image paths + for (let i = 0; i < 100; i++) + { + const frameName = alienFrames[i % 4]; + + // create an alien using the frame name.. + const alien = PIXI.Sprite.from(frameName); + + alien.tint = Math.random() * 0xffffff; + + alien.x = Math.random() * 800 - 400; + alien.y = Math.random() * 600 - 300; + alien.anchor.x = 0.5; + alien.anchor.y = 0.5; + aliens.push(alien); + alienContainer.addChild(alien); + } + app.start(); +} + +// Combines both mouse click + touch tap +app.stage.on('pointertap', onClick); + +function onClick() +{ + alienContainer.cacheAsBitmap = !alienContainer.cacheAsBitmap; +} + +app.ticker.add(() => +{ + // let's rotate the aliens a little bit + for (let i = 0; i < 100; i++) + { + const alien = aliens[i]; + + alien.rotation += 0.1; + } + + count += 0.01; + + alienContainer.scale.x = Math.sin(count); + alienContainer.scale.y = Math.sin(count); + alienContainer.rotation += 0.01; +}); diff --git a/src/examples/v8.0.0-rc/basic/container.js b/src/examples/v8.0.0-rc/basic/container.js new file mode 100644 index 000000000..9d23157ca --- /dev/null +++ b/src/examples/v8.0.0-rc/basic/container.js @@ -0,0 +1,39 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +const container = new PIXI.Container(); + +app.stage.addChild(container); + +// Create a new texture +const texture = PIXI.Texture.from('https://pixijs.com/assets/bunny.png'); + +// Create a 5x5 grid of bunnies +for (let i = 0; i < 25; i++) +{ + const bunny = new PIXI.Sprite(texture); + + bunny.anchor.set(0.5); + bunny.x = (i % 5) * 40; + bunny.y = Math.floor(i / 5) * 40; + container.addChild(bunny); +} + +// Move container to the center +container.x = app.screen.width / 2; +container.y = app.screen.height / 2; + +// Center bunny sprite in local container coordinates +container.pivot.x = container.width / 2; +container.pivot.y = container.height / 2; + +// Listen for animate update +app.ticker.add((delta) => +{ + // rotate the container! + // use delta to create frame-independent transform + container.rotation -= 0.01 * delta; +}); diff --git a/src/examples/v8.0.0-rc/basic/particleContainer.js b/src/examples/v8.0.0-rc/basic/particleContainer.js new file mode 100644 index 000000000..4dc6d56b2 --- /dev/null +++ b/src/examples/v8.0.0-rc/basic/particleContainer.js @@ -0,0 +1,102 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +const sprites = new PIXI.ParticleContainer(10000, { + scale: true, + position: true, + rotation: true, + uvs: true, + alpha: true, +}); + +app.stage.addChild(sprites); + +// create an array to store all the sprites +const maggots = []; + +const totalSprites = app.renderer instanceof PIXI.Renderer ? 10000 : 100; + +for (let i = 0; i < totalSprites; i++) +{ + // create a new Sprite + const dude = PIXI.Sprite.from('https://pixijs.com/assets/maggot_tiny.png'); + + // set the anchor point so the texture is centerd on the sprite + dude.anchor.set(0.5); + + // different maggots, different sizes + dude.scale.set(0.8 + Math.random() * 0.3); + + // scatter them all + dude.x = Math.random() * app.screen.width; + dude.y = Math.random() * app.screen.height; + + dude.tint = Math.random() * 0x808080; + + // create a random direction in radians + dude.direction = Math.random() * Math.PI * 2; + + // this number will be used to modify the direction of the sprite over time + dude.turningSpeed = Math.random() - 0.8; + + // create a random speed between 0 - 2, and these maggots are slooww + dude.speed = (2 + Math.random() * 2) * 0.2; + + dude.offset = Math.random() * 100; + + // finally we push the dude into the maggots array so it it can be easily accessed later + maggots.push(dude); + + sprites.addChild(dude); +} + +// create a bounding box box for the little maggots +const dudeBoundsPadding = 100; +const dudeBounds = new PIXI.Rectangle( + -dudeBoundsPadding, + -dudeBoundsPadding, + app.screen.width + dudeBoundsPadding * 2, + app.screen.height + dudeBoundsPadding * 2, +); + +let tick = 0; + +app.ticker.add(() => +{ + // iterate through the sprites and update their position + for (let i = 0; i < maggots.length; i++) + { + const dude = maggots[i]; + + dude.scale.y = 0.95 + Math.sin(tick + dude.offset) * 0.05; + dude.direction += dude.turningSpeed * 0.01; + dude.x += Math.sin(dude.direction) * (dude.speed * dude.scale.y); + dude.y += Math.cos(dude.direction) * (dude.speed * dude.scale.y); + dude.rotation = -dude.direction + Math.PI; + + // wrap the maggots + if (dude.x < dudeBounds.x) + { + dude.x += dudeBounds.width; + } + else if (dude.x > dudeBounds.x + dudeBounds.width) + { + dude.x -= dudeBounds.width; + } + + if (dude.y < dudeBounds.y) + { + dude.y += dudeBounds.height; + } + else if (dude.y > dudeBounds.y + dudeBounds.height) + { + dude.y -= dudeBounds.height; + } + } + + // increment the ticker + tick += 0.1; +}); diff --git a/src/examples/v8.0.0-rc/basic/simplePlane.js b/src/examples/v8.0.0-rc/basic/simplePlane.js new file mode 100644 index 000000000..72faba2c5 --- /dev/null +++ b/src/examples/v8.0.0-rc/basic/simplePlane.js @@ -0,0 +1,32 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +PIXI.Assets.load('https://pixijs.com/assets/bg_grass.jpg').then((texture) => +{ + const plane = new PIXI.SimplePlane(texture, 10, 10); + + plane.x = 100; + plane.y = 100; + + app.stage.addChild(plane); + + // Get the buffer for vertice positions. + const buffer = plane.geometry.getBuffer('aVertexPosition'); + + // Listen for animate update + let timer = 0; + + app.ticker.add(() => + { + // Randomize the vertice positions a bit to create movement. + for (let i = 0; i < buffer.data.length; i++) + { + buffer.data[i] += Math.sin(timer / 10 + i) * 0.5; + } + buffer.update(); + timer++; + }); +}); diff --git a/src/examples/v8.0.0-rc/basic/tinting.js b/src/examples/v8.0.0-rc/basic/tinting.js new file mode 100644 index 000000000..e52ddc6f8 --- /dev/null +++ b/src/examples/v8.0.0-rc/basic/tinting.js @@ -0,0 +1,85 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +// holder to store the aliens +const aliens = []; + +const totalDudes = 20; + +for (let i = 0; i < totalDudes; i++) +{ + // create a new Sprite that uses the image name that we just generated as its source + const dude = PIXI.Sprite.from('https://pixijs.com/assets/eggHead.png'); + + // set the anchor point so the texture is centered on the sprite + dude.anchor.set(0.5); + + // set a random scale for the dude - no point them all being the same size! + dude.scale.set(0.8 + Math.random() * 0.3); + + // finally lets set the dude to be at a random position.. + dude.x = Math.random() * app.screen.width; + dude.y = Math.random() * app.screen.height; + + dude.tint = Math.random() * 0xffffff; + + // create some extra properties that will control movement : + // create a random direction in radians. This is a number between 0 and PI*2 which is the equivalent of 0 - 360 degrees + dude.direction = Math.random() * Math.PI * 2; + + // this number will be used to modify the direction of the dude over time + dude.turningSpeed = Math.random() - 0.8; + + // create a random speed for the dude between 2 - 4 + dude.speed = 2 + Math.random() * 2; + + // finally we push the dude into the aliens array so it it can be easily accessed later + aliens.push(dude); + + app.stage.addChild(dude); +} + +// create a bounding box for the little dudes +const dudeBoundsPadding = 100; +const dudeBounds = new PIXI.Rectangle( + -dudeBoundsPadding, + -dudeBoundsPadding, + app.screen.width + dudeBoundsPadding * 2, + app.screen.height + dudeBoundsPadding * 2, +); + +app.ticker.add(() => +{ + // iterate through the dudes and update their position + for (let i = 0; i < aliens.length; i++) + { + const dude = aliens[i]; + + dude.direction += dude.turningSpeed * 0.01; + dude.x += Math.sin(dude.direction) * dude.speed; + dude.y += Math.cos(dude.direction) * dude.speed; + dude.rotation = -dude.direction - Math.PI / 2; + + // wrap the dudes by testing their bounds... + if (dude.x < dudeBounds.x) + { + dude.x += dudeBounds.width; + } + else if (dude.x > dudeBounds.x + dudeBounds.width) + { + dude.x -= dudeBounds.width; + } + + if (dude.y < dudeBounds.y) + { + dude.y += dudeBounds.height; + } + else if (dude.y > dudeBounds.y + dudeBounds.height) + { + dude.y -= dudeBounds.height; + } + } +}); diff --git a/src/examples/v8.0.0-rc/basic/transparentBackground.js b/src/examples/v8.0.0-rc/basic/transparentBackground.js new file mode 100644 index 000000000..f31e19be8 --- /dev/null +++ b/src/examples/v8.0.0-rc/basic/transparentBackground.js @@ -0,0 +1,23 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ backgroundAlpha: 0, resizeTo: window }); + +document.body.appendChild(app.view); + +// create a new Sprite from an image path. +const bunny = PIXI.Sprite.from('https://pixijs.com/assets/bunny.png'); + +// center the sprite's anchor point +bunny.anchor.set(0.5); + +// move the sprite to the center of the screen +bunny.x = app.screen.width / 2; +bunny.y = app.screen.height / 2; + +app.stage.addChild(bunny); + +app.ticker.add(() => +{ + // just for fun, let's rotate mr rabbit a little + bunny.rotation += 0.1; +}); diff --git a/src/examples/v8.0.0-rc/events/click.js b/src/examples/v8.0.0-rc/events/click.js new file mode 100644 index 000000000..24ab92686 --- /dev/null +++ b/src/examples/v8.0.0-rc/events/click.js @@ -0,0 +1,36 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +// Scale mode for all textures, will retain pixelation +PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; + +const sprite = PIXI.Sprite.from('https://pixijs.com/assets/bunny.png'); + +// Set the initial position +sprite.anchor.set(0.5); +sprite.x = app.screen.width / 2; +sprite.y = app.screen.height / 2; + +// Opt-in to interactivity +sprite.eventMode = 'static'; + +// Shows hand cursor +sprite.cursor = 'pointer'; + +// Pointers normalize touch and mouse (good for mobile and desktop) +sprite.on('pointerdown', onClick); + +// Alternatively, use the mouse & touch events: +// sprite.on('click', onClick); // mouse-only +// sprite.on('tap', onClick); // touch-only + +app.stage.addChild(sprite); + +function onClick() +{ + sprite.scale.x *= 1.25; + sprite.scale.y *= 1.25; +} diff --git a/src/examples/v8.0.0-rc/events/customHitarea.js b/src/examples/v8.0.0-rc/events/customHitarea.js new file mode 100644 index 000000000..852b95e1c --- /dev/null +++ b/src/examples/v8.0.0-rc/events/customHitarea.js @@ -0,0 +1,116 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application(800, 600, { background: '#1099bb' }); + +document.body.appendChild(app.view); + +const yellowStar = PIXI.Texture.from('https://pixijs.com/assets/yellowstar.png'); + +// Standard Sprite Button +const starButton1 = new PIXI.Sprite(yellowStar); + +starButton1.position.set(50, 200); +starButton1.cursor = 'pointer'; +starButton1.eventMode = 'static'; + +starButton1 + .on('pointerdown', onClick, starButton1) + .on('pointerover', onPointerOver, starButton1) + .on('pointerout', onPointerOut, starButton1); + +// Custom Hitarea Button +const starButton2 = new PIXI.Sprite(yellowStar); + +starButton2.position.set(250, 200); + +// Create a hitarea that matches the sprite, which will be used for point +// intersection +starButton2.hitArea = new PIXI.Polygon([ + 80, 0, 100, 50, 160, 55, 115, 95, 130, 150, 80, 120, 30, 150, 45, 95, 0, 55, 60, 50, +]); +starButton2.cursor = 'pointer'; +starButton2.eventMode = 'static'; + +starButton2 + .on('pointerdown', onClick, starButton2) + .on('pointerover', onPointerOver, starButton2) + .on('pointerout', onPointerOut, starButton2); + +// With Mask, No Hit Area +const starButton3 = new PIXI.Sprite(yellowStar); + +starButton3.position.set(450, 200); +starButton3.cursor = 'pointer'; +starButton3.eventMode = 'static'; + +const squareMask = new PIXI.Graphics().beginFill(0xffffff).drawRect(starButton3.x, starButton3.y, 75, 200).endFill(); + +starButton3.mask = squareMask; + +starButton3 + .on('pointerdown', onClick, starButton3) + .on('pointerover', onPointerOver, starButton3) + .on('pointerout', onPointerOut, starButton3); + +// With a Mask and Hit Area +// Hitareas ignore masks. You can still click on a button made in this way, +// even from areas covered by a mask +const starButton4 = new PIXI.Sprite(yellowStar); + +starButton4.position.set(600, 200); + +const squareMask2 = new PIXI.Graphics().beginFill(0xffffff).drawRect(starButton4.x, starButton4.y, 75, 200).endFill(); + +starButton4.mask = squareMask2; + +// Again, hitarea for intersection checks +starButton4.hitArea = new PIXI.Polygon([ + 80, 0, 100, 50, 160, 55, 115, 95, 130, 150, 80, 120, 30, 150, 45, 95, 0, 55, 60, 50, +]); +starButton4.cursor = 'pointer'; +starButton4.eventMode = 'static'; + +starButton4 + .on('pointerdown', onClick, starButton4) + .on('pointerover', onPointerOver, starButton4) + .on('pointerout', onPointerOut, starButton4); + +const style = new PIXI.TextStyle({ fill: '#ffffff' }); + +const text1 = new PIXI.Text('Standard', style); + +text1.x = starButton1.x + 25; +text1.y = starButton1.y + 170; + +const text2 = new PIXI.Text('Hit Area', style); + +text2.x = starButton2.x + 35; +text2.y = starButton2.y + 170; + +const text3 = new PIXI.Text('Mask', style); + +text3.x = starButton3.x + 10; +text3.y = starButton3.y + 170; + +const text4 = new PIXI.Text('Mask + Hit Area', style); + +text4.x = starButton4.x - 10; +text4.y = starButton4.y + 170; + +// Add to stage +app.stage.addChild(starButton2, starButton1, starButton3, starButton4, squareMask, squareMask2, text1, text2, text3, text4); + +function onClick() +{ + this.tint = 0x333333; +} + +function onPointerOver() +{ + this.tint = 0x666666; +} + +function onPointerOut() +{ + this.tint = 0xffffff; +} diff --git a/src/examples/v8.0.0-rc/events/customMouseIcon.js b/src/examples/v8.0.0-rc/events/customMouseIcon.js new file mode 100644 index 000000000..4e479cece --- /dev/null +++ b/src/examples/v8.0.0-rc/events/customMouseIcon.js @@ -0,0 +1,104 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +// Css style for icons +const defaultIcon = 'url(\'https://pixijs.com/assets/bunny.png\'),auto'; +const hoverIcon = 'url(\'https://pixijs.com/assets/bunny_saturated.png\'),auto'; + +// Add custom cursor styles +app.renderer.events.cursorStyles.default = defaultIcon; +app.renderer.events.cursorStyles.hover = hoverIcon; + +// create a background... +const background = PIXI.Sprite.from('https://pixijs.com/assets/bg_button.jpg'); + +background.width = app.screen.width; +background.height = app.screen.height; +// add background to stage... +app.stage.addChild(background); + +// create some textures from an image path +const textureButton = PIXI.Texture.from('https://pixijs.com/assets/button.png'); +const textureButtonDown = PIXI.Texture.from('https://pixijs.com/assets/button_down.png'); +const textureButtonOver = PIXI.Texture.from('https://pixijs.com/assets/button_over.png'); + +const buttons = []; + +const buttonPositions = [175, 75, 655, 75, 410, 325, 150, 465, 685, 445]; + +for (let i = 0; i < 5; i++) +{ + const button = new PIXI.Sprite(textureButton); + + button.cursor = 'hover'; + + button.anchor.set(0.5); + button.x = buttonPositions[i * 2]; + button.y = buttonPositions[i * 2 + 1]; + + // make the button interactive... + button.eventMode = 'static'; + + button + .on('pointerdown', onButtonDown) + .on('pointerup', onButtonUp) + .on('pointerupoutside', onButtonUp) + .on('pointerover', onButtonOver) + .on('pointerout', onButtonOut); + + // add it to the stage + app.stage.addChild(button); + + // add button to array + buttons.push(button); +} + +// set some silly values... +buttons[0].scale.set(1.2); +buttons[2].rotation = Math.PI / 10; +buttons[3].scale.set(0.8); +buttons[4].scale.set(0.8, 1.2); +buttons[4].rotation = Math.PI; + +function onButtonDown() +{ + this.isdown = true; + this.texture = textureButtonDown; + this.alpha = 1; +} + +function onButtonUp() +{ + this.isdown = false; + if (this.isOver) + { + this.texture = textureButtonOver; + } + else + { + this.texture = textureButton; + } +} + +function onButtonOver() +{ + this.isOver = true; + if (this.isdown) + { + return; + } + this.texture = textureButtonOver; +} + +function onButtonOut() +{ + this.isOver = false; + if (this.isdown) + { + return; + } + this.texture = textureButton; +} diff --git a/src/examples/v8.0.0-rc/events/dragging.js b/src/examples/v8.0.0-rc/events/dragging.js new file mode 100644 index 000000000..010260eec --- /dev/null +++ b/src/examples/v8.0.0-rc/events/dragging.js @@ -0,0 +1,81 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +// create a texture from an image path +const texture = PIXI.Texture.from('https://pixijs.com/assets/bunny.png'); + +// Scale mode for pixelation +texture.baseTexture.scaleMode = PIXI.SCALE_MODES.NEAREST; + +for (let i = 0; i < 10; i++) +{ + createBunny(Math.floor(Math.random() * app.screen.width), Math.floor(Math.random() * app.screen.height)); +} + +function createBunny(x, y) +{ + // create our little bunny friend.. + const bunny = new PIXI.Sprite(texture); + + // enable the bunny to be interactive... this will allow it to respond to mouse and touch events + bunny.eventMode = 'static'; + + // this button mode will mean the hand cursor appears when you roll over the bunny with your mouse + bunny.cursor = 'pointer'; + + // center the bunny's anchor point + bunny.anchor.set(0.5); + + // make it a bit bigger, so it's easier to grab + bunny.scale.set(3); + + // setup events for mouse + touch using + // the pointer events + bunny.on('pointerdown', onDragStart, bunny); + + // move the sprite to its designated position + bunny.x = x; + bunny.y = y; + + // add it to the stage + app.stage.addChild(bunny); +} + +let dragTarget = null; + +app.stage.eventMode = 'static'; +app.stage.hitArea = app.screen; +app.stage.on('pointerup', onDragEnd); +app.stage.on('pointerupoutside', onDragEnd); + +function onDragMove(event) +{ + if (dragTarget) + { + dragTarget.parent.toLocal(event.global, null, dragTarget.position); + } +} + +function onDragStart() +{ + // store a reference to the data + // the reason for this is because of multitouch + // we want to track the movement of this particular touch + // this.data = event.data; + this.alpha = 0.5; + dragTarget = this; + app.stage.on('pointermove', onDragMove); +} + +function onDragEnd() +{ + if (dragTarget) + { + app.stage.off('pointermove', onDragMove); + dragTarget.alpha = 1; + dragTarget = null; + } +} diff --git a/src/examples/v8.0.0-rc/events/hitTestingWithSpatialHash.js b/src/examples/v8.0.0-rc/events/hitTestingWithSpatialHash.js new file mode 100644 index 000000000..54ac85f1d --- /dev/null +++ b/src/examples/v8.0.0-rc/events/hitTestingWithSpatialHash.js @@ -0,0 +1,219 @@ +import * as PIXI from 'pixi.js'; + +// This example shows how you can create your own EventBoundary to accelerate +// hit-testing using spatial hashes. This can be used to optimize relatively +// "flat" scene graphs, where a container contains so many objects that it +// covers the whole scene. + +// This special event boundary overrides the hit-testing implementation to use +// HashingContainer's own childHash to find children near the pointer +// location. +class HashingEventBoundary extends PIXI.EventBoundary +{ + constructor(...args) + { + super(...args); + // Create reusable temp rectangle for hit-testing! + this.tempRect = new PIXI.Rectangle(); + } + + hitTestRecursive(currentTarget, interactive, location, testFn, pruneFn) + { + // If currentTarget isn't a HashingContainer, then default to the + // regular hit-testing implementation provided by PixiJS. + if (!currentTarget || !currentTarget.visible || !currentTarget.childHash) + { + return super.hitTestRecursive(currentTarget, interactive, location, testFn, pruneFn); + } + + // Check if the location is outside of the entire container + if (pruneFn(currentTarget, location)) return null; + + // Time to get recursive and find the next child in the propagation + // path of the event, accelerated using the childHash. + if (currentTarget.interactiveChildren) + { + /* This is where the magic happens! */ + const tempRect = this.tempRect; + + // Store the location as a 0x0 rectangle. SpatialHash requires a + // rectangle for searching. + tempRect.x = location.x; + tempRect.y = location.y; + + // Find all the children overlapping with tempRect a.k.a location, + // and then sort them by their index in the HashingContainer's + // children array. + const children = Array.from(currentTarget.childHash.search(tempRect)).sort((a, b) => a.refIndex - b.refIndex); + + /* The following is copied from EventBoundary's code. */ + for (let i = children.length - 1; i >= 0; i--) + { + const child = children[i]; + const nestedHit = this.hitTestRecursive(child, interactive || child.interactive, location, testFn, pruneFn); + + if (nestedHit) + { + // Its a good idea to check if a child has lost its + // parent. this means it has been removed whilst looping + // so its best + if (nestedHit.length > 0 && !nestedHit[nestedHit.length - 1].parent) + { + // eslint-disable-next-line no-continue + continue; + } + + // Only add the current hit-test target to the hit-test + // chain if the chain has already started (i.e. the event + // target has been found) or if the current target is + // interactive (i.e. it becomes the event target). + if (nestedHit.length > 0 || currentTarget.interactive) + { + nestedHit.push(currentTarget); + } + + return nestedHit; + } + } + } + + /* The following is copied from EventBoundary's own implementation. */ + + // Finally, hit test this DisplayObject itself. + if (interactive && testFn(currentTarget, location)) + { + // The current hit-test target is the event's target only if it + // is interactive. Otherwise, the first interactive ancestor will + // be the event's target. + return currentTarget.interactive ? [currentTarget] : []; + } + + return null; + } +} + +// HashingContainer is a special kind of container that organizes its children +// in a spatial hash. It also sets each child's refIndex property to its index +// in the hashing container's children array. +class HashingContainer extends PIXI.Container +{ + constructor() + { + super(); + this.childHash = new PIXI.SpatialHash(); + } + + // Override updateTransform to update this.childHash! + updateTransform() + { + super.updateTransform(); + + // Reset childHash & re-add all the children. This will + // make the spatial hash re-evaluate the coverage of each child. + this.childHash.reset(); + for (let i = 0; i < this.children.length; i++) + { + const child = this.children[i]; + + this.childHash.put(child); + child.refIndex = i; + } + } +} + +// This is the actual program using HashingEventBoundary, HashingContainer. +function main() +{ + // Create app. autoStart = false so that the app doesn't render until + // something changes - this prevents redundant spatial-hash updates. + const app = new PIXI.Application({ + antialias: true, + autoStart: false, + background: '#1099bb', + }); + + document.body.appendChild(app.view); + + // Install our own EventBoundary! + app.renderer.events.rootBoundary = new HashingEventBoundary(app.stage); + + // Make the hashing container + const container = app.stage.addChild(new HashingContainer()); + // Textures to choose from for each random character + const textures = [ + PIXI.Texture.from('https://pixijs.com/assets/skully.png'), + PIXI.Texture.from('https://pixijs.com/assets/eggHead.png'), + PIXI.Texture.from('https://pixijs.com/assets/flowerTop.png'), + PIXI.Texture.from('https://pixijs.com/assets/helmlok.png'), + ]; + // Rerender scene when each texture loads + + textures.forEach((tex) => tex.baseTexture.once('loaded', () => app.render())); + + // Populate the hashing container! + function makeMonster(x, y) + { + const texture = textures[Math.floor(Math.random() * textures.length)]; + const sprite = new PIXI.Sprite(texture); + + // Randomly place the character + sprite.position.set( + x || Math.random() * (app.screen.width - 64), + y || 64 + Math.random() * (app.screen.height - 128), + ); + + // Make character smaller so we can have a bunch of 'em + sprite.scale.set(0.34); + + // Make the character interactive! + sprite.eventMode = 'static'; + + // Explode on clicks! + sprite.addEventListener('click', onMonsterClicked); + + container.addChild(sprite); + + return sprite; + } + function onMonsterClicked(e) + { + const monster = this; + const pos = monster.position; + const radius = Math.max(monster.width, monster.height) * 2; + + // Remove monster from scene once the event finishes propagating. + e.manager.dispatch.once('click', () => + { + // TODO: Fix PixiJS throwing errors since the monster is removed + // from scene graph while was under hover. + + monster.parent.removeChild(monster); + PIXI.Ticker.shared.addOnce(() => app.render()); + }); + + for (let i = 0; i < 8; i++) + { + const x = pos.x + radius * Math.cos((i * Math.PI) / 4); + const y = pos.y + radius * Math.sin((i * Math.PI) / 4); + + makeMonster(x, y); + } + } + // Make initial set of monsters + for (let i = 0; i < 100; i++) makeMonster(); + + // Add a descriptive title + const title = app.stage.addChild( + new PIXI.Text('Click on a monster and see it explode into more!', { + fontSize: 12, + }), + ); + + title.position.set(12, 12); + + // Render the stage once + app.render(); +} + +// Run our program! +main(); diff --git a/src/examples/v8.0.0-rc/events/interactivity.js b/src/examples/v8.0.0-rc/events/interactivity.js new file mode 100644 index 000000000..665e0f752 --- /dev/null +++ b/src/examples/v8.0.0-rc/events/interactivity.js @@ -0,0 +1,111 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +// create a background... +const background = PIXI.Sprite.from('https://pixijs.com/assets/bg_button.jpg'); + +background.width = app.screen.width; +background.height = app.screen.height; + +// add background to stage... +app.stage.addChild(background); + +// create some textures from an image path +const textureButton = PIXI.Texture.from('https://pixijs.com/assets/button.png'); +const textureButtonDown = PIXI.Texture.from('https://pixijs.com/assets/button_down.png'); +const textureButtonOver = PIXI.Texture.from('https://pixijs.com/assets/button_over.png'); + +const buttons = []; + +const buttonPositions = [175, 75, 655, 75, 410, 325, 150, 465, 685, 445]; + +for (let i = 0; i < 5; i++) +{ + const button = new PIXI.Sprite(textureButton); + + button.anchor.set(0.5); + button.x = buttonPositions[i * 2]; + button.y = buttonPositions[i * 2 + 1]; + + // make the button interactive... + button.eventMode = 'static'; + button.cursor = 'pointer'; + + button + // Mouse & touch events are normalized into + // the pointer* events for handling different + // button events. + .on('pointerdown', onButtonDown) + .on('pointerup', onButtonUp) + .on('pointerupoutside', onButtonUp) + .on('pointerover', onButtonOver) + .on('pointerout', onButtonOut); + + // Use mouse-only events + // .on('mousedown', onButtonDown) + // .on('mouseup', onButtonUp) + // .on('mouseupoutside', onButtonUp) + // .on('mouseover', onButtonOver) + // .on('mouseout', onButtonOut) + + // Use touch-only events + // .on('touchstart', onButtonDown) + // .on('touchend', onButtonUp) + // .on('touchendoutside', onButtonUp) + + // add it to the stage + app.stage.addChild(button); + + // add button to array + buttons.push(button); +} + +// set some silly values... +buttons[0].scale.set(1.2); +buttons[2].rotation = Math.PI / 10; +buttons[3].scale.set(0.8); +buttons[4].scale.set(0.8, 1.2); +buttons[4].rotation = Math.PI; + +function onButtonDown() +{ + this.isdown = true; + this.texture = textureButtonDown; + this.alpha = 1; +} + +function onButtonUp() +{ + this.isdown = false; + if (this.isOver) + { + this.texture = textureButtonOver; + } + else + { + this.texture = textureButton; + } +} + +function onButtonOver() +{ + this.isOver = true; + if (this.isdown) + { + return; + } + this.texture = textureButtonOver; +} + +function onButtonOut() +{ + this.isOver = false; + if (this.isdown) + { + return; + } + this.texture = textureButton; +} diff --git a/src/examples/v8.0.0-rc/events/logger.js b/src/examples/v8.0.0-rc/events/logger.js new file mode 100644 index 000000000..a76c32f0c --- /dev/null +++ b/src/examples/v8.0.0-rc/events/logger.js @@ -0,0 +1,86 @@ +import * as PIXI from 'pixi.js'; + +// This example logs the order of events hover-related events in the scene. +const app = new PIXI.Application({ + antialias: true, + background: '#1099bb', +}); + +document.body.appendChild(app.view); + +const title = app.stage.addChild( + new PIXI.Text( + `Move your mouse slowly over the boxes to + see the order of pointerenter, pointerleave, + pointerover, pointerout events on each target!`, + { + fontSize: 16, + }, + ), +); + +title.x = 2; + +const logs = []; +const logText = app.stage.addChild( + new PIXI.Text('', { + fontSize: 14, + }), +); + +logText.y = 80; +logText.x = 2; + +app.stage.name = 'stage'; + +// Mount outer black box +const blackBox = app.stage.addChild(new PIXI.Graphics().beginFill(0).drawRect(0, 0, 400, 400).endFill()); + +blackBox.name = 'black box'; +blackBox.x = 400; + +// Mount white box inside the white one +const whiteBox = blackBox.addChild(new PIXI.Graphics().beginFill(0xffffff).drawRect(100, 100, 200, 200).endFill()); + +whiteBox.name = 'white box'; + +// Enable interactivity everywhere! +app.stage.eventMode = 'static'; +app.stage.hitArea = app.screen; +whiteBox.eventMode = 'static'; +blackBox.eventMode = 'static'; + +function onEvent(e) +{ + const type = e.type; + const targetName = e.target.name; + const currentTargetName = e.currentTarget.name; + + // Add event to top of logs + logs.push(`${currentTargetName} received ${type} event (target is ${targetName})`); + + if (currentTargetName === 'stage' || type === 'pointerenter' || type === 'pointerleave') + { + logs.push('-----------------------------------------', ''); + } + + // Prevent logs from growing too long + if (logs.length > 30) + { + while (logs.length > 30) + { + logs.shift(); + } + } + + // Update logText + logText.text = logs.join('\n'); +} + +[app.stage, whiteBox, blackBox].forEach((object) => +{ + object.addEventListener('pointerenter', onEvent); + object.addEventListener('pointerleave', onEvent); + object.addEventListener('pointerover', onEvent); + object.addEventListener('pointerout', onEvent); +}); diff --git a/src/examples/v8.0.0-rc/events/nestedBoundaryWithProjection.js b/src/examples/v8.0.0-rc/events/nestedBoundaryWithProjection.js new file mode 100644 index 000000000..430a192ca --- /dev/null +++ b/src/examples/v8.0.0-rc/events/nestedBoundaryWithProjection.js @@ -0,0 +1,231 @@ +import * as PIXI from 'pixi.js'; +import '@pixi/graphics-extras'; + +// This example shows how you can setup a nested boundary to propagate events +// into a disjoint scene graph. Here, a camera is used to project an different +// world onto the canvas. + +const app = new PIXI.Application({ + antialias: true, + background: '#1099bb', +}); + +document.body.appendChild(app.view); + +// A projector renders it's content using projection. The transforms in +// the contents scene graph don't change if you move the camera. To achieve +// this, the content is not added as a "child" to the projector; however, this +// means events won't propagate into the content by default. +// +// To solve this, we nest our own EventBoundary, and connect it using +// addEventListener! +class Projector extends PIXI.DisplayObject +{ + constructor() + { + super(); + + // The content root to be rendered by this camera. + this.content = new PIXI.Container(); + + // Temporary matrix to store the original projection transform. + this.originalTransform = new PIXI.Matrix(); + + // The event boundary that'll map events downstream into the content + // scene. + this.boundary = new PIXI.EventBoundary(this.content); + + // Override copyMouseData to apply inverse worldTransform on + // global coords + this.boundary.copyMouseData = (from, to) => + { + // Apply default implementation first + PIXI.EventBoundary.prototype.copyMouseData.call(this.boundary, from, to); + + // Then bring global coords into content's world + this.worldTransform.applyInverse(to.global, to.global); + // TODO: Remove after https://github.com/pixijs/pixi.js/pull/7381 + // is merged! + to.target = this.boundary.hitTest(to.global.x, to.global.y); + }; + + // Propagate these events down into the content's scene graph! + ['pointerdown', 'pointerup', 'pointermove', 'pointerover', 'pointerout', 'wheel'].forEach((event) => + { + this.addEventListener(event, (e) => this.boundary.mapEvent(e)); + }); + + this.eventMode = 'static'; + } + + // Pass through cursor + get cursor() + { + return this.boundary.cursor; + } + + // eslint-disable-next-line class-methods-use-this + set cursor(value) + { + throw new Error('The camera\'s cursor is derived from its content!'); + } + + // Pass through calculateBounds + calculateBounds() + { + const contentBounds = this.content.getBounds(); + + this._bounds.addFrameMatrix( + this.worldTransform, + contentBounds.x, + contentBounds.y, + contentBounds.width, + contentBounds.height, + ); + } + + // Pass through containsPoint + containsPoint(point) + { + return !!this.boundary.hitTest(point.x, point.y); + } + + // Render content with projection + render(renderer) + { + renderer.batch.flush(); + + const projectionSystem = renderer.projection; + const renderTextureSystem = renderer.renderTexture; + + projectionSystem.transform = projectionSystem.transform || new PIXI.Matrix(); + projectionSystem.transform.copyTo(this.originalTransform); + projectionSystem.transform.append(this.worldTransform); + projectionSystem.update(null, null, 1, !renderTextureSystem.current); + + this.content.render(renderer); + + renderer.batch.flush(); + + projectionSystem.transform.copyFrom(this.originalTransform); + projectionSystem.update(null, null, 1, !renderTextureSystem.current); + } + + // updateTransform also updates content's transform + updateTransform() + { + super.updateTransform(); + + this.content.enableTempParent(); + this.content.updateTransform(); + this.content.disableTempParent(null); + } +} + +// The projector +const projector = app.stage.addChild(new Projector()); + +// Add coordinate axes! +projector.content.addChild( + new PIXI.Graphics() + .lineStyle({ color: 0, alpha: 0.2, width: 2 }) + .moveTo(0, -300) + .lineTo(0, 600) + .moveTo(-100, 0) + .lineTo(700, 0), +); + +// Construct the star Graphics +const stars = [1, 2, 3].map((i) => new PIXI.Graphics().beginFill(0xffffff, 0.75).drawStar(0, 0, 18 / i, (100 * i) / 2)); + +// Place the stars +stars[0].x = 0; +stars[1].x = 200; +stars[2].x = 500; + +// Add stars to the projector +projector.content.addChild(...stars); + +// Make projection x+100, y+300 +projector.x = 100; +projector.y = 300; +projector.content.hitArea = new PIXI.Rectangle(-100, -300, app.screen.width, app.screen.height); +// Make hit-area cover the whole screen so we can capture +// pointermove everywhere! +projector.hitArea = projector.content.hitArea; +projector.content.eventMode = 'static'; + +// Make stars interactive & add wheel handlers +stars.forEach((star) => +{ + // Make star interactive + star.eventMode = 'static'; + + // Set initial cursor + star.cursor = 'zoom-in'; + + // Add wheel rotation feedback + star.addEventListener('wheel', (e) => + { + const scroll = Math.sign(e.deltaY) * Math.min(15, Math.abs(e.deltaY)); + + star.rotation += scroll / 100; + }); + + // Add click zoom-in/zoom-out handler + star.addEventListener('click', (e) => + { + if (star.scale.x === 1) + { + star.scale.set(1.33); + star.cursor = 'zoom-out'; + } + else + { + star.scale.set(1); + star.cursor = 'zoom-in'; + } + }); +}); + +PIXI.BitmapFont.from( + 'coordinates', + { + fontFamily: 'Roboto', + fontSize: 16, + fill: '#272d37', + }, + { chars: ['Global:() Screen-.,', ['0', '9']] }, +); + +const coordinates = new PIXI.BitmapText('Global: (0, 0)\nScreen: (0, 0)', { + fontName: 'coordinates', +}); + +coordinates.x = 110; +coordinates.y = 550; + +app.stage.addChild(coordinates); + +projector.content.addEventListener('pointermove', (e) => +{ + const global = `(${e.global.x | 0}, ${e.global.y | 0})`; + const screen = `(${e.screen.x | 0}, ${e.screen.y | 0})`; + + coordinates.text = `Global: ${global}\nScreen: ${screen}`; +}); + +const description = new PIXI.Text( + 'The (0, 0) world coordinates for the content is located at the center of the first star!' + + '\n * Mouse wheel over stars to rotate them' + + '\n * Click to zoom in or out', + { + fontSize: 16, + fontFamily: 'Roboto', + fill: '#272d37', + }, +); + +description.position.set(110, 12); + +app.stage.addChild(description); diff --git a/src/examples/v8.0.0-rc/events/pointerTracker.js b/src/examples/v8.0.0-rc/events/pointerTracker.js new file mode 100644 index 000000000..97c805c8b --- /dev/null +++ b/src/examples/v8.0.0-rc/events/pointerTracker.js @@ -0,0 +1,34 @@ +import * as PIXI from 'pixi.js'; + +// In this a example, a circle will follow the pointer wherever it +// moves over the canvas. + +const app = new PIXI.Application({ + antialias: true, + background: '#1099bb', +}); + +document.body.appendChild(app.view); + +// Create the circle +const circle = app.stage.addChild( + new PIXI.Graphics() + .beginFill(0xffffff) + .lineStyle({ color: 0x111111, alpha: 0.87, width: 1 }) + .drawCircle(0, 0, 8) + .endFill(), +); + +circle.position.set(app.screen.width / 2, app.screen.height / 2); + +// Enable interactivity! +app.stage.eventMode = 'static'; + +// Make sure the whole canvas area is interactive, not just the circle. +app.stage.hitArea = app.screen; + +// Follow the pointer +app.stage.addEventListener('pointermove', (e) => +{ + circle.position.copyFrom(e.global); +}); diff --git a/src/examples/v8.0.0-rc/events/slider.js b/src/examples/v8.0.0-rc/events/slider.js new file mode 100644 index 000000000..1d1848d24 --- /dev/null +++ b/src/examples/v8.0.0-rc/events/slider.js @@ -0,0 +1,84 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ + antialias: true, + background: '#1099bb', +}); + +document.body.appendChild(app.view); + +const stageHeight = app.screen.height; +const stageWidth = app.screen.width; + +// Make sure stage covers the whole scene +app.stage.hitArea = app.screen; + +// Make the slider +const sliderWidth = 320; +const slider = new PIXI.Graphics().beginFill(0x272d37).drawRect(0, 0, sliderWidth, 4); + +slider.x = (stageWidth - sliderWidth) / 2; +slider.y = stageHeight * 0.75; + +// Draw the handle +const handle = new PIXI.Graphics().beginFill(0xffffff).drawCircle(0, 0, 8); + +handle.y = slider.height / 2; +handle.x = sliderWidth / 2; +handle.eventMode = 'static'; +handle.cursor = 'pointer'; + +handle.on('pointerdown', onDragStart).on('pointerup', onDragEnd).on('pointerupoutside', onDragEnd); + +app.stage.addChild(slider); +slider.addChild(handle); + +// Add bunny whose scale can be changed by user using slider +const bunny = app.stage.addChild(PIXI.Sprite.from('https://pixijs.com/assets/bunny.png')); + +bunny.texture.baseTexture.scaleMode = PIXI.SCALE_MODES.NEAREST; +bunny.scale.set(3); +bunny.anchor.set(0.5); +bunny.x = stageWidth / 2; +bunny.y = stageHeight / 2; + +// Add title +const title = new PIXI.Text('Drag the handle to change the scale of bunny.', { + fill: '#272d37', + fontFamily: 'Roboto', + fontSize: 20, + align: 'center', +}); + +title.roundPixels = true; +title.x = stageWidth / 2; +title.y = 40; +title.anchor.set(0.5, 0); +app.stage.addChild(title); + +// Listen to pointermove on stage once handle is pressed. +function onDragStart() +{ + app.stage.eventMode = 'static'; + app.stage.addEventListener('pointermove', onDrag); +} + +// Stop dragging feedback once the handle is released. +function onDragEnd(e) +{ + app.stage.eventMode = 'auto'; + app.stage.removeEventListener('pointermove', onDrag); +} + +// Update the handle's position & bunny's scale when the handle is moved. +function onDrag(e) +{ + const halfHandleWidth = handle.width / 2; + // Set handle y-position to match pointer, clamped to (4, screen.height - 4). + + handle.x = Math.max(halfHandleWidth, Math.min(slider.toLocal(e.global).x, sliderWidth - halfHandleWidth)); + // Normalize handle position between -1 and 1. + const t = 2 * (handle.x / sliderWidth - 0.5); + + bunny.scale.set(3 * (1.1 + t)); +} diff --git a/src/examples/v8.0.0-rc/examplesData.json b/src/examples/v8.0.0-rc/examplesData.json new file mode 100644 index 000000000..50a3f3d4d --- /dev/null +++ b/src/examples/v8.0.0-rc/examplesData.json @@ -0,0 +1,108 @@ +{ + "basic": [ + "container", + "transparentBackground", + "tinting", + "cacheAsBitmap", + "particleContainer", + "blendModes", + "simplePlane" + ], + "advanced": [ + "slots", + "scratchCard", + "starWarp", + "mouseTrail", + "screenShot", + "collisionDetection", + "spinners" + ], + "sprite": [ + "basic", + "textureSwap", + "animatedSpriteExplosion", + "animatedSpriteJet", + "animatedSpriteAnimationSpeed", + "tilingSprite", + "video" + ], + "text": [ + "pixiText", + "bitmapText", + "fromFont", + "webFont" + ], + "graphics": [ + "simple", + "advanced", + "dynamic" + ], + "events": [ + "click", + "interactivity", + "dragging", + "customMouseIcon", + "customHitarea", + { + "name": "hitTestingWithSpatialHash", + "hide": true + }, + "logger", + "nestedBoundaryWithProjection", + "pointerTracker", + "slider" + ], + "masks": [ + "graphics", + "sprite", + "filter" + ], + "filtersBasic": [ + "blur", + "colorMatrix", + "displacementMapCrawlies", + "displacementMapFlag" + ], + "filtersAdvanced": [ + "mouseBlending", + "custom", + "shaderToyFilterRenderTexture" + ], + "meshAndShaders": [ + "texturedMeshBasic", + "texturedMeshAdvanced", + "triangle", + "triangleColor", + "triangleTextured", + "uniforms", + "sharingGeometry", + "sharedShader", + "mergingGeometry", + "interleavingGeometry", + "instancedGeometry", + "shaderToyMesh", + "multiPassShaderGeneratedMesh" + ], + "textures": [ + "textureRotate", + "renderTextureBasic", + "renderTextureAdvanced", + "gradientBasic", + "gradientResource" + ], + "assets": [ + "promise", + "async", + "multiple", + "background", + "bundle" + ], + "offscreenCanvas": [ + "basic", + { + "name": "webWorker", + "hide": true, + "usesWebWorkerLibrary": true + } + ] +} diff --git a/src/examples/v8.0.0-rc/filtersAdvanced/custom.js b/src/examples/v8.0.0-rc/filtersAdvanced/custom.js new file mode 100644 index 000000000..ba3733dc8 --- /dev/null +++ b/src/examples/v8.0.0-rc/filtersAdvanced/custom.js @@ -0,0 +1,47 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +// Create background image +const background = PIXI.Sprite.from('https://pixijs.com/assets/bg_grass.jpg'); + +background.width = app.screen.width; +background.height = app.screen.height; +app.stage.addChild(background); + +// Stop application wait for load to finish +app.stop(); + +fetch('https://pixijs.com/assets/pixi-filters/shader.frag') + .then((res) => res.text()) + .then(onLoaded); + +let filter; + +// Handle the load completed +function onLoaded(data) +{ + // Create the new filter, arguments: (vertexShader, framentSource) + filter = new PIXI.Filter(null, data, { + customUniform: 0.0, + }); + + // === WARNING === + // specify uniforms in filter constructor + // or set them BEFORE first use + // filter.uniforms.customUniform = 0.0 + + // Add the filter + background.filters = [filter]; + + // Resume application update + app.start(); +} + +// Animate the filter +app.ticker.add((delta) => +{ + filter.uniforms.customUniform += 0.04 * delta; +}); diff --git a/src/examples/v8.0.0-rc/filtersAdvanced/mouseBlending.js b/src/examples/v8.0.0-rc/filtersAdvanced/mouseBlending.js new file mode 100644 index 000000000..34b2239d9 --- /dev/null +++ b/src/examples/v8.0.0-rc/filtersAdvanced/mouseBlending.js @@ -0,0 +1,58 @@ +import * as PIXI from 'pixi.js'; + +/** + * https://github.com/pixijs/pixi.js/wiki/v5-Creating-Filters + */ + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +// Create background image +const background = PIXI.Sprite.from('https://pixijs.com/assets/bg_grass.jpg'); + +background.width = app.screen.width; +background.height = app.screen.height; +app.stage.addChild(background); + +// NOTE: this shader wont work on old devices where mediump precision is forced in fragment shader +// because v5 default vertex shader uses `inputSize` in it. Same uniform in fragment and vertex shader +// cant have different precision :( + +const shaderFrag = ` +precision highp float; + +varying vec2 vTextureCoord; + +uniform vec2 mouse; +uniform vec4 inputSize; +uniform vec4 outputFrame; +uniform float time; + +void main() { + vec2 screenPos = vTextureCoord * inputSize.xy + outputFrame.xy; + if (length(mouse - screenPos) < 25.0) { + gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0) * 0.7; //yellow circle, alpha=0.7 + } else { + // blend with underlying image, alpha=0.5 + gl_FragColor = vec4( sin(time), (mouse.xy - outputFrame.xy) / outputFrame.zw, 1.0) * 0.5; + } +} +`; + +const container = new PIXI.Container(); + +container.filterArea = new PIXI.Rectangle(100, 100, app.screen.width - 200, app.screen.height - 200); +app.stage.addChild(container); +const filter = new PIXI.Filter(null, shaderFrag, { + mouse: new PIXI.Point(), +}); + +container.filters = [filter]; + +app.stage.hitArea = app.screen; +app.stage.eventMode = 'static'; +app.stage.on('pointermove', (event) => +{ + filter.uniforms.mouse.copyFrom(event.global); +}); diff --git a/src/examples/v8.0.0-rc/filtersAdvanced/shaderToyFilterRenderTexture.js b/src/examples/v8.0.0-rc/filtersAdvanced/shaderToyFilterRenderTexture.js new file mode 100644 index 000000000..2e26310a9 --- /dev/null +++ b/src/examples/v8.0.0-rc/filtersAdvanced/shaderToyFilterRenderTexture.js @@ -0,0 +1,116 @@ +import * as PIXI from 'pixi.js'; + +/** + * Please note that this is not the most optimal way of doing pure shader generated rendering and should be used when the + * scene is wanted as input texture. Check the mesh version of example for more performant version if you need only shader + * generated content. + **/ +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +PIXI.Assets.load('https://pixijs.com/assets/perlin.jpg').then(onAssetsLoaded); + +let filter = null; + +const text = new PIXI.Text('PixiJS', { fill: 0xffffff, fontSize: 80 }); + +text.anchor.set(0.5, 0.5); +text.position.set(app.renderer.screen.width / 2, app.renderer.screen.height / 2); + +app.stage.addChild(text); + +let totalTime = 0; + +// Fragment shader, in real use this would be much cleaner when loaded from a file +// or embedded into the application as data resource. +const fragment = `//Based on this: https://www.shadertoy.com/view/wtlSWX + +varying vec2 vTextureCoord; +uniform sampler2D uSampler; +uniform sampler2D noise; +uniform float time; +// Distance function. Just calculates the height (z) from x,y plane with really simple length check. +// Its not exact as there could be shorter distances. +vec2 dist(vec3 p) +{ + float id = floor(p.x)+floor(p.y); + id = mod(id, 2.); + float h = texture2D(noise, vec2(p.x, p.y)*0.04).r*5.1; + float h2 = texture2D(uSampler, vTextureCoord).r; + return vec2(h+h2-p.z,id); +} +//Light calculation. +vec3 calclight(vec3 p, vec3 rd) +{ + vec2 eps = vec2( 0., 0.001); + vec3 n = normalize( vec3( + dist(p+eps.yxx).x - dist(p-eps.yxx).x, + dist(p+eps.xyx).x - dist(p-eps.xyx).x, + dist(p+eps.xxy).x - dist(p-eps.xxy).x + )); + + vec3 d = vec3( max( 0., dot( -rd ,n))); + + return d; +} + +void main() +{ + vec2 uv = vec2(vTextureCoord.x, 1.-vTextureCoord.y); + uv *=2.; + uv-=1.; + + vec3 cam = vec3(0.,time -2., -3.); + vec3 target = vec3(sin(time)*0.1, time+cos(time)+2., 0. ); + float fov = 2.2; + vec3 forward = normalize( target - cam); + vec3 up = normalize(cross( forward, vec3(0., 1.,0.))); + vec3 right = normalize( cross( up, forward)); + vec3 raydir = normalize(vec3( uv.x *up + uv.y * right + fov*forward)); + + //Do the raymarch + vec3 col = vec3(0.); + float t = 0.; + for( int i = 0; i < 100; i++) + { + vec3 p = t * raydir + cam; + vec2 d = dist(p); + t+=d.x*0.5;//Jump only half of the distance as height function used is not really the best for heightmaps. + if(d.x < 0.001) + { + vec3 bc = d.y < 0.5 ? vec3(1.0, .8, 0.) : + vec3(0.8,0.0, 1.0); + col = vec3( 1.) * calclight(p, raydir) * (1. - t/150.) *bc; + break; + } + if(t > 1000.) + { + break; + } + } + gl_FragColor = vec4(col, 1.); +} +`; + +function onAssetsLoaded(perlin) +{ + // Add perlin noise for filter, make sure it's wrapping and does not have mipmap. + perlin.baseTexture.wrapMode = PIXI.WRAP_MODES.REPEAT; + perlin.baseTexture.mipmap = false; + + // Build the filter + filter = new PIXI.Filter(null, fragment, { + time: 0.0, + noise: perlin, + }); + app.stage.filterArea = app.renderer.screen; + app.stage.filters = [filter]; + + // Listen for animate update. + app.ticker.add((delta) => + { + filter.uniforms.time = totalTime; + totalTime += delta / 60; + }); +} diff --git a/src/examples/v8.0.0-rc/filtersBasic/blur.js b/src/examples/v8.0.0-rc/filtersBasic/blur.js new file mode 100644 index 000000000..9557f45bf --- /dev/null +++ b/src/examples/v8.0.0-rc/filtersBasic/blur.js @@ -0,0 +1,42 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +const bg = PIXI.Sprite.from('https://pixijs.com/assets/pixi-filters/bg_depth_blur.jpg'); + +bg.width = app.screen.width; +bg.height = app.screen.height; +app.stage.addChild(bg); + +const littleDudes = PIXI.Sprite.from('https://pixijs.com/assets/pixi-filters/depth_blur_dudes.jpg'); + +littleDudes.x = app.screen.width / 2 - 315; +littleDudes.y = 200; +app.stage.addChild(littleDudes); + +const littleRobot = PIXI.Sprite.from('https://pixijs.com/assets/pixi-filters/depth_blur_moby.jpg'); + +littleRobot.x = app.screen.width / 2 - 200; +littleRobot.y = 100; +app.stage.addChild(littleRobot); + +const blurFilter1 = new PIXI.filters.BlurFilter(); +const blurFilter2 = new PIXI.filters.BlurFilter(); + +littleDudes.filters = [blurFilter1]; +littleRobot.filters = [blurFilter2]; + +let count = 0; + +app.ticker.add(() => +{ + count += 0.005; + + const blurAmount = Math.cos(count); + const blurAmount2 = Math.sin(count); + + blurFilter1.blur = 20 * blurAmount; + blurFilter2.blur = 20 * blurAmount2; +}); diff --git a/src/examples/v8.0.0-rc/filtersBasic/colorMatrix.js b/src/examples/v8.0.0-rc/filtersBasic/colorMatrix.js new file mode 100644 index 000000000..1ef11e814 --- /dev/null +++ b/src/examples/v8.0.0-rc/filtersBasic/colorMatrix.js @@ -0,0 +1,90 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +app.stage.eventMode = 'static'; + +const bg = PIXI.Sprite.from('https://pixijs.com/assets/bg_rotate.jpg'); + +bg.anchor.set(0.5); + +bg.x = app.screen.width / 2; +bg.y = app.screen.height / 2; + +const filter = new PIXI.filters.ColorMatrixFilter(); + +const container = new PIXI.Container(); + +container.x = app.screen.width / 2; +container.y = app.screen.height / 2; + +const bgFront = PIXI.Sprite.from('https://pixijs.com/assets/bg_scene_rotate.jpg'); + +bgFront.anchor.set(0.5); + +container.addChild(bgFront); + +const light2 = PIXI.Sprite.from('https://pixijs.com/assets/light_rotate_2.png'); + +light2.anchor.set(0.5); +container.addChild(light2); + +const light1 = PIXI.Sprite.from('https://pixijs.com/assets/light_rotate_1.png'); + +light1.anchor.set(0.5); +container.addChild(light1); + +const panda = PIXI.Sprite.from('https://pixijs.com/assets/panda.png'); + +panda.anchor.set(0.5); + +container.addChild(panda); + +app.stage.addChild(container); + +app.stage.filters = [filter]; + +let count = 0; +let enabled = true; + +app.stage.on('pointertap', () => +{ + enabled = !enabled; + app.stage.filters = enabled ? [filter] : null; +}); + +const help = new PIXI.Text('Click or tap to turn filters on / off.', { + fontFamily: 'Arial', + fontSize: 12, + fontWeight: 'bold', + fill: 'white', +}); + +help.y = app.screen.height - 25; +help.x = 10; + +app.stage.addChild(help); + +app.ticker.add((delta) => +{ + bg.rotation += 0.01; + bgFront.rotation -= 0.01; + light1.rotation += 0.02; + light2.rotation += 0.01; + + panda.scale.x = 1 + Math.sin(count) * 0.04; + panda.scale.y = 1 + Math.cos(count) * 0.04; + + count += 0.1; + + const { matrix } = filter; + + matrix[1] = Math.sin(count) * 3; + matrix[2] = Math.cos(count); + matrix[3] = Math.cos(count) * 1.5; + matrix[4] = Math.sin(count / 3) * 2; + matrix[5] = Math.sin(count / 2); + matrix[6] = Math.sin(count / 4); +}); diff --git a/src/examples/v8.0.0-rc/filtersBasic/displacementMapCrawlies.js b/src/examples/v8.0.0-rc/filtersBasic/displacementMapCrawlies.js new file mode 100644 index 000000000..21b823678 --- /dev/null +++ b/src/examples/v8.0.0-rc/filtersBasic/displacementMapCrawlies.js @@ -0,0 +1,111 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +app.stage.eventMode = 'static'; + +const container = new PIXI.Container(); + +app.stage.addChild(container); + +const padding = 100; +const bounds = new PIXI.Rectangle(-padding, -padding, app.screen.width + padding * 2, app.screen.height + padding * 2); +const maggots = []; + +for (let i = 0; i < 20; i++) +{ + const maggot = PIXI.Sprite.from('https://pixijs.com/assets/maggot.png'); + + maggot.anchor.set(0.5); + container.addChild(maggot); + + maggot.direction = Math.random() * Math.PI * 2; + maggot.speed = 1; + maggot.turnSpeed = Math.random() - 0.8; + + maggot.x = Math.random() * bounds.width; + maggot.y = Math.random() * bounds.height; + + maggot.scale.set(1 + Math.random() * 0.3); + maggot.original = new PIXI.Point(); + maggot.original.copyFrom(maggot.scale); + maggots.push(maggot); +} + +const displacementSprite = PIXI.Sprite.from('https://pixijs.com/assets/pixi-filters/displace.png'); +const displacementFilter = new PIXI.filters.DisplacementFilter(displacementSprite); + +app.stage.addChild(displacementSprite); + +container.filters = [displacementFilter]; + +displacementFilter.scale.x = 110; +displacementFilter.scale.y = 110; +displacementSprite.anchor.set(0.5); + +const ring = PIXI.Sprite.from('https://pixijs.com/assets/pixi-filters/ring.png'); + +ring.anchor.set(0.5); + +ring.visible = false; + +app.stage.addChild(ring); + +const bg = PIXI.Sprite.from('https://pixijs.com/assets/bg_grass.jpg'); + +bg.width = app.screen.width; +bg.height = app.screen.height; + +bg.alpha = 0.4; + +container.addChild(bg); + +app.stage.on('mousemove', onPointerMove).on('touchmove', onPointerMove); + +function onPointerMove(eventData) +{ + ring.visible = true; + + displacementSprite.position.set(eventData.data.global.x - 25, eventData.data.global.y); + ring.position.copyFrom(displacementSprite.position); +} + +let count = 0; + +app.ticker.add(() => +{ + count += 0.05; + + for (let i = 0; i < maggots.length; i++) + { + const maggot = maggots[i]; + + maggot.direction += maggot.turnSpeed * 0.01; + maggot.x += Math.sin(maggot.direction) * maggot.speed; + maggot.y += Math.cos(maggot.direction) * maggot.speed; + + maggot.rotation = -maggot.direction - Math.PI / 2; + maggot.scale.x = maggot.original.x + Math.sin(count) * 0.2; + + // wrap the maggots around as the crawl + if (maggot.x < bounds.x) + { + maggot.x += bounds.width; + } + else if (maggot.x > bounds.x + bounds.width) + { + maggot.x -= bounds.width; + } + + if (maggot.y < bounds.y) + { + maggot.y += bounds.height; + } + else if (maggot.y > bounds.y + bounds.height) + { + maggot.y -= bounds.height; + } + } +}); diff --git a/src/examples/v8.0.0-rc/filtersBasic/displacementMapFlag.js b/src/examples/v8.0.0-rc/filtersBasic/displacementMapFlag.js new file mode 100644 index 000000000..0c09bc815 --- /dev/null +++ b/src/examples/v8.0.0-rc/filtersBasic/displacementMapFlag.js @@ -0,0 +1,46 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +app.stage.eventMode = 'static'; + +const container = new PIXI.Container(); + +app.stage.addChild(container); + +const flag = PIXI.Sprite.from('https://pixijs.com/assets/pixi-filters/flag.png'); + +container.addChild(flag); +flag.x = 100; +flag.y = 100; + +const displacementSprite = PIXI.Sprite.from('https://pixijs.com/assets/pixi-filters/displacement_map_repeat.jpg'); +// Make sure the sprite is wrapping. + +displacementSprite.texture.baseTexture.wrapMode = PIXI.WRAP_MODES.REPEAT; +const displacementFilter = new PIXI.filters.DisplacementFilter(displacementSprite); + +displacementFilter.padding = 10; + +displacementSprite.position = flag.position; + +app.stage.addChild(displacementSprite); + +flag.filters = [displacementFilter]; + +displacementFilter.scale.x = 30; +displacementFilter.scale.y = 60; + +app.ticker.add(() => +{ + // Offset the sprite position to make vFilterCoord update to larger value. + // Repeat wrapping makes sure there's still pixels on the coordinates. + displacementSprite.x++; + // Reset x to 0 when it's over width to keep values from going to very huge numbers. + if (displacementSprite.x > displacementSprite.width) + { + displacementSprite.x = 0; + } +}); diff --git a/src/examples/v8.0.0-rc/graphics/advanced.js b/src/examples/v8.0.0-rc/graphics/advanced.js new file mode 100644 index 000000000..bce095b7f --- /dev/null +++ b/src/examples/v8.0.0-rc/graphics/advanced.js @@ -0,0 +1,105 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ antialias: true, resizeTo: window }); + +document.body.appendChild(app.view); + +const sprite = PIXI.Sprite.from('https://pixijs.com/assets/bg_rotate.jpg'); + +// // BEZIER CURVE //// +// information: https://en.wikipedia.org/wiki/Bézier_curve + +const realPath = new PIXI.Graphics(); + +realPath.lineStyle(2, 0xffffff, 1); +realPath.moveTo(0, 0); +realPath.lineTo(100, 200); +realPath.lineTo(200, 200); +realPath.lineTo(240, 100); + +realPath.position.x = 50; +realPath.position.y = 50; + +app.stage.addChild(realPath); + +const bezier = new PIXI.Graphics(); + +bezier.lineStyle(5, 0xaa0000, 1); +bezier.bezierCurveTo(100, 200, 200, 200, 240, 100); + +bezier.position.x = 50; +bezier.position.y = 50; + +app.stage.addChild(bezier); + +// // BEZIER CURVE 2 //// +const realPath2 = new PIXI.Graphics(); + +realPath2.lineStyle(2, 0xffffff, 1); +realPath2.moveTo(0, 0); +realPath2.lineTo(0, -100); +realPath2.lineTo(150, 150); +realPath2.lineTo(240, 100); + +realPath2.position.x = 320; +realPath2.position.y = 150; + +app.stage.addChild(realPath2); + +const bezier2 = new PIXI.Graphics(); + +bezier2.lineTextureStyle({ width: 10, texture: sprite.texture }); +bezier2.bezierCurveTo(0, -100, 150, 150, 240, 100); + +bezier2.position.x = 320; +bezier2.position.y = 150; + +app.stage.addChild(bezier2); + +// // ARC //// +const arc = new PIXI.Graphics(); + +arc.lineStyle(5, 0xaa00bb, 1); +arc.arc(600, 100, 50, Math.PI, 2 * Math.PI); + +app.stage.addChild(arc); + +// // ARC 2 //// +const arc2 = new PIXI.Graphics(); + +arc2.lineStyle(6, 0x3333dd, 1); +arc2.arc(650, 270, 60, 2 * Math.PI, (3 * Math.PI) / 2); + +app.stage.addChild(arc2); + +// // ARC 3 //// +const arc3 = new PIXI.Graphics(); + +arc3.lineTextureStyle({ width: 20, texture: sprite.texture }); +arc3.arc(650, 420, 60, 2 * Math.PI, (2.5 * Math.PI) / 2); + +app.stage.addChild(arc3); + +// / Hole //// +const rectAndHole = new PIXI.Graphics(); + +rectAndHole.beginFill(0x00ff00); +rectAndHole.drawRect(350, 350, 150, 150); +rectAndHole.beginHole(); +rectAndHole.drawCircle(375, 375, 25); +rectAndHole.drawCircle(425, 425, 25); +rectAndHole.drawCircle(475, 475, 25); +rectAndHole.endHole(); +rectAndHole.endFill(); + +app.stage.addChild(rectAndHole); + +// // Line Texture Style //// +const beatifulRect = new PIXI.Graphics(); + +beatifulRect.lineTextureStyle({ width: 20, texture: sprite.texture }); +beatifulRect.beginFill(0xff0000); +beatifulRect.drawRect(80, 350, 150, 150); +beatifulRect.endFill(); + +app.stage.addChild(beatifulRect); diff --git a/src/examples/v8.0.0-rc/graphics/dynamic.js b/src/examples/v8.0.0-rc/graphics/dynamic.js new file mode 100644 index 000000000..5db56f8d8 --- /dev/null +++ b/src/examples/v8.0.0-rc/graphics/dynamic.js @@ -0,0 +1,98 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ antialias: true, resizeTo: window }); + +document.body.appendChild(app.view); + +app.stage.eventMode = 'static'; +app.stage.hitArea = app.screen; + +const graphics = new PIXI.Graphics(); + +// set a fill and line style +graphics.beginFill(0xff3300); +graphics.lineStyle(10, 0xffd900, 1); + +// draw a shape +graphics.moveTo(50, 50); +graphics.lineTo(250, 50); +graphics.lineTo(100, 100); +graphics.lineTo(250, 220); +graphics.lineTo(50, 220); +graphics.lineTo(50, 50); +graphics.closePath(); +graphics.endFill(); + +// set a fill and line style again +graphics.lineStyle(10, 0xff0000, 0.8); +graphics.beginFill(0xff700b, 1); + +// draw a second shape +graphics.moveTo(210, 300); +graphics.lineTo(450, 320); +graphics.lineTo(570, 350); +graphics.quadraticCurveTo(600, 0, 480, 100); +graphics.lineTo(330, 120); +graphics.lineTo(410, 200); +graphics.lineTo(210, 300); +graphics.closePath(); +graphics.endFill(); + +// draw a rectangle +graphics.lineStyle(2, 0x0000ff, 1); +graphics.drawRect(50, 250, 100, 100); + +// draw a circle +graphics.lineStyle(0); +graphics.beginFill(0xffff0b, 0.5); +graphics.drawCircle(470, 200, 100); +graphics.endFill(); + +graphics.lineStyle(20, 0x33ff00); +graphics.moveTo(30, 30); +graphics.lineTo(600, 300); + +app.stage.addChild(graphics); + +// let's create a moving shape +const thing = new PIXI.Graphics(); + +app.stage.addChild(thing); +thing.x = 800 / 2; +thing.y = 600 / 2; + +let count = 0; + +// Just click on the stage to draw random lines +window.app = app; +app.stage.on('pointerdown', () => +{ + graphics.lineStyle(Math.random() * 30, Math.random() * 0xffffff, 1); + graphics.moveTo(Math.random() * 800, Math.random() * 600); + graphics.bezierCurveTo( + Math.random() * 800, + Math.random() * 600, + Math.random() * 800, + Math.random() * 600, + Math.random() * 800, + Math.random() * 600, + ); +}); + +app.ticker.add(() => +{ + count += 0.1; + + thing.clear(); + thing.lineStyle(10, 0xff0000, 1); + thing.beginFill(0xffff00, 0.5); + + thing.moveTo(-120 + Math.sin(count) * 20, -100 + Math.cos(count) * 20); + thing.lineTo(120 + Math.cos(count) * 20, -100 + Math.sin(count) * 20); + thing.lineTo(120 + Math.sin(count) * 20, 100 + Math.cos(count) * 20); + thing.lineTo(-120 + Math.cos(count) * 20, 100 + Math.sin(count) * 20); + thing.lineTo(-120 + Math.sin(count) * 20, -100 + Math.cos(count) * 20); + thing.closePath(); + + thing.rotation = count * 0.1; +}); diff --git a/src/examples/v8.0.0-rc/graphics/simple.js b/src/examples/v8.0.0-rc/graphics/simple.js new file mode 100644 index 000000000..735e40f20 --- /dev/null +++ b/src/examples/v8.0.0-rc/graphics/simple.js @@ -0,0 +1,99 @@ +import * as PIXI from 'pixi.js'; +import '@pixi/graphics-extras'; + +const app = new PIXI.Application({ antialias: true, resizeTo: window }); + +document.body.appendChild(app.view); + +const graphics = new PIXI.Graphics(); + +// Rectangle +graphics.beginFill(0xde3249); +graphics.drawRect(50, 50, 100, 100); +graphics.endFill(); + +// Rectangle + line style 1 +graphics.lineStyle(2, 0xfeeb77, 1); +graphics.beginFill(0x650a5a); +graphics.drawRect(200, 50, 100, 100); +graphics.endFill(); + +// Rectangle + line style 2 +graphics.lineStyle(10, 0xffbd01, 1); +graphics.beginFill(0xc34288); +graphics.drawRect(350, 50, 100, 100); +graphics.endFill(); + +// Rectangle 2 +graphics.lineStyle(2, 0xffffff, 1); +graphics.beginFill(0xaa4f08); +graphics.drawRect(530, 50, 140, 100); +graphics.endFill(); + +// Circle +graphics.lineStyle(0); // draw a circle, set the lineStyle to zero so the circle doesn't have an outline +graphics.beginFill(0xde3249, 1); +graphics.drawCircle(100, 250, 50); +graphics.endFill(); + +// Circle + line style 1 +graphics.lineStyle(2, 0xfeeb77, 1); +graphics.beginFill(0x650a5a, 1); +graphics.drawCircle(250, 250, 50); +graphics.endFill(); + +// Circle + line style 2 +graphics.lineStyle(10, 0xffbd01, 1); +graphics.beginFill(0xc34288, 1); +graphics.drawCircle(400, 250, 50); +graphics.endFill(); + +// Ellipse + line style 2 +graphics.lineStyle(2, 0xffffff, 1); +graphics.beginFill(0xaa4f08, 1); +graphics.drawEllipse(600, 250, 80, 50); +graphics.endFill(); + +// draw a shape +graphics.beginFill(0xff3300); +graphics.lineStyle(4, 0xffd900, 1); +graphics.moveTo(50, 350); +graphics.lineTo(250, 350); +graphics.lineTo(100, 400); +graphics.lineTo(50, 350); +graphics.closePath(); +graphics.endFill(); + +// draw a rounded rectangle +graphics.lineStyle(2, 0xff00ff, 1); +graphics.beginFill(0x650a5a, 0.25); +graphics.drawRoundedRect(50, 440, 100, 100, 16); +graphics.endFill(); + +// draw star +graphics.lineStyle(2, 0xffffff); +graphics.beginFill(0x35cc5a, 1); +graphics.drawStar(360, 370, 5, 50); +graphics.endFill(); + +// draw star 2 +graphics.lineStyle(2, 0xffffff); +graphics.beginFill(0xffcc5a, 1); +graphics.drawStar(280, 510, 7, 50); +graphics.endFill(); + +// draw star 3 +graphics.lineStyle(4, 0xffffff); +graphics.beginFill(0x55335a, 1); +graphics.drawStar(470, 450, 4, 50); +graphics.endFill(); + +// draw polygon +const path = [600, 370, 700, 460, 780, 420, 730, 570, 590, 520]; + +graphics.lineStyle(0); +graphics.beginFill(0x3500fa, 1); +graphics.drawPolygon(path); +graphics.endFill(); + +app.stage.addChild(graphics); diff --git a/src/examples/v8.0.0-rc/index.ts b/src/examples/v8.0.0-rc/index.ts new file mode 100644 index 000000000..7588e51dc --- /dev/null +++ b/src/examples/v8.0.0-rc/index.ts @@ -0,0 +1,286 @@ +import collisionDetection from '!!raw-loader!./advanced/collisionDetection.js'; +import mouseTrail from '!!raw-loader!./advanced/mouseTrail.js'; +import scratchCard from '!!raw-loader!./advanced/scratchCard.js'; +import screenShot from '!!raw-loader!./advanced/screenShot.js'; +import slots from '!!raw-loader!./advanced/slots.js'; +import spinners from '!!raw-loader!./advanced/spinners.js'; +import starWarp from '!!raw-loader!./advanced/starWarp.js'; + +import async from '!!raw-loader!./assets/async.js'; +import background from '!!raw-loader!./assets/background.js'; +import bundle from '!!raw-loader!./assets/bundle.js'; +import multiple from '!!raw-loader!./assets/multiple.js'; +import promise from '!!raw-loader!./assets/promise.js'; + +import blendModes from '!!raw-loader!./basic/blendModes.js'; +import cacheAsBitmap from '!!raw-loader!./basic/cacheAsBitmap.js'; +import container from '!!raw-loader!./basic/container.js'; +import particleContainer from '!!raw-loader!./basic/particleContainer.js'; +import simplePlane from '!!raw-loader!./basic/simplePlane.js'; +import tinting from '!!raw-loader!./basic/tinting.js'; +import transparentBackground from '!!raw-loader!./basic/transparentBackground.js'; + +import click from '!!raw-loader!./events/click.js'; +import customHitarea from '!!raw-loader!./events/customHitarea.js'; +import customMouseIcon from '!!raw-loader!./events/customMouseIcon.js'; +import dragging from '!!raw-loader!./events/dragging.js'; +import hitTestingWithSpatialHash from '!!raw-loader!./events/hitTestingWithSpatialHash.js'; +import interactivity from '!!raw-loader!./events/interactivity.js'; +import logger from '!!raw-loader!./events/logger.js'; +import nestedBoundaryWithProjection from '!!raw-loader!./events/nestedBoundaryWithProjection.js'; +import pointerTracker from '!!raw-loader!./events/pointerTracker.js'; +import slider from '!!raw-loader!./events/slider.js'; + +import custom from '!!raw-loader!./filtersAdvanced/custom.js'; +import mouseBlending from '!!raw-loader!./filtersAdvanced/mouseBlending.js'; +import shaderToyFilterRenderTexture from '!!raw-loader!./filtersAdvanced/shaderToyFilterRenderTexture.js'; + +import blur from '!!raw-loader!./filtersBasic/blur.js'; +import colorMatrix from '!!raw-loader!./filtersBasic/colorMatrix.js'; +import displacementMapCrawlies from '!!raw-loader!./filtersBasic/displacementMapCrawlies.js'; +import displacementMapFlag from '!!raw-loader!./filtersBasic/displacementMapFlag.js'; + +import advanced from '!!raw-loader!./graphics/advanced.js'; +import dynamic from '!!raw-loader!./graphics/dynamic.js'; +import simple from '!!raw-loader!./graphics/simple.js'; + +import filter from '!!raw-loader!./masks/filter.js'; +import graphics from '!!raw-loader!./masks/graphics.js'; +import sprite from '!!raw-loader!./masks/sprite.js'; + +import instancedGeometry from '!!raw-loader!./meshAndShaders/instancedGeometry.js'; +import interleavingGeometry from '!!raw-loader!./meshAndShaders/interleavingGeometry.js'; +import mergingGeometry from '!!raw-loader!./meshAndShaders/mergingGeometry.js'; +import multiPassShaderGeneratedMesh from '!!raw-loader!./meshAndShaders/multiPassShaderGeneratedMesh.js'; +import shaderToyMesh from '!!raw-loader!./meshAndShaders/shaderToyMesh.js'; +import sharedShader from '!!raw-loader!./meshAndShaders/sharedShader.js'; +import sharingGeometry from '!!raw-loader!./meshAndShaders/sharingGeometry.js'; +import texturedMeshAdvanced from '!!raw-loader!./meshAndShaders/texturedMeshAdvanced.js'; +import texturedMeshBasic from '!!raw-loader!./meshAndShaders/texturedMeshBasic.js'; +import triangleColor from '!!raw-loader!./meshAndShaders/triangleColor.js'; +import triangleTextured from '!!raw-loader!./meshAndShaders/triangleTextured.js'; +import triangle from '!!raw-loader!./meshAndShaders/triangle.js'; +import uniforms from '!!raw-loader!./meshAndShaders/uniforms.js'; + +import offscreenCanvasBasic from '!!raw-loader!./offscreenCanvas/basic.js'; +import webWorker from '!!raw-loader!./offscreenCanvas/webWorker.js'; + +import animatedSpriteAnimationSpeed from '!!raw-loader!./sprite/animatedSpriteAnimationSpeed.js'; +import animatedSpriteExplosion from '!!raw-loader!./sprite/animatedSpriteExplosion.js'; +import animatedSpriteJet from '!!raw-loader!./sprite/animatedSpriteJet.js'; +import spriteBasic from '!!raw-loader!./sprite/basic.js'; +import textureSwap from '!!raw-loader!./sprite/textureSwap.js'; +import tilingSprite from '!!raw-loader!./sprite/tilingSprite.js'; +import video from '!!raw-loader!./sprite/video.js'; + +import bitmapText from '!!raw-loader!./text/bitmapText.js'; +import fromFont from '!!raw-loader!./text/fromFont.js'; +import pixiText from '!!raw-loader!./text/pixiText.js'; +import webFont from '!!raw-loader!./text/webFont.js'; + +import gradientBasic from '!!raw-loader!./textures/gradientBasic.js'; +import gradientResource from '!!raw-loader!./textures/gradientResource.js'; +import renderTextureAdvanced from '!!raw-loader!./textures/renderTextureAdvanced.js'; +import renderTextureBasic from '!!raw-loader!./textures/renderTextureBasic.js'; +import textureRotate from '!!raw-loader!./textures/textureRotate.js'; +import type { Option, OptionGroup } from '@site/src/components/Select'; + +// Defines order of examples in documentation and playground dropdown, it's defined +// separately here so it can be used in runtime code and in the md generation script +import examplesData from './examplesData.json'; +import { camelCaseToSentenceCase } from '@site/src/utils/utils'; + +export type ExampleDataEntry = { + name: string; + hide?: boolean; + usesWebWorkerLibrary?: boolean; +}; +export type ExampleSourceEntry = { + source: string; + hide: boolean; + usesWebWorkerLibrary: boolean; +}; +// json data structure +export type ExamplesJsonType = Record; +// sourcecode dictionary structure for below +export type ExamplesSourceType = Record>; +// normalized combination of the above +export type CategoryDataType = Record; +export type ExamplesDataType = Record; + +const examplesSource: ExamplesSourceType = { + basic: { + blendModes, + cacheAsBitmap, + container, + particleContainer, + simplePlane, + tinting, + transparentBackground, + }, + sprite: { + animatedSpriteAnimationSpeed, + animatedSpriteExplosion, + animatedSpriteJet, + basic: spriteBasic, + textureSwap, + tilingSprite, + video, + }, + text: { + bitmapText, + fromFont, + pixiText, + webFont, + }, + graphics: { + advanced, + dynamic, + simple, + }, + events: { + click, + customHitarea, + customMouseIcon, + dragging, + hitTestingWithSpatialHash, + interactivity, + logger, + nestedBoundaryWithProjection, + pointerTracker, + slider, + }, + masks: { + filter, + graphics, + sprite, + }, + textures: { + gradientBasic, + gradientResource, + renderTextureAdvanced, + renderTextureBasic, + textureRotate, + }, + assets: { + async, + background, + bundle, + multiple, + promise, + }, + offscreenCanvas: { + basic: offscreenCanvasBasic, + webWorker, + }, + filtersBasic: { + blur, + colorMatrix, + displacementMapCrawlies, + displacementMapFlag, + }, + filtersAdvanced: { + custom, + mouseBlending, + shaderToyFilterRenderTexture, + }, + advanced: { + collisionDetection, + mouseTrail, + scratchCard, + screenShot, + slots, + spinners, + starWarp, + }, + meshAndShaders: { + instancedGeometry, + interleavingGeometry, + mergingGeometry, + multiPassShaderGeneratedMesh, + shaderToyMesh, + sharedShader, + sharingGeometry, + texturedMeshAdvanced, + texturedMeshBasic, + triangleColor, + triangleTextured, + triangle, + uniforms, + }, +}; + +const normalizeExampleDataEntry = (categoryExample: ExampleDataEntry | string): Required => +{ + const defaults = { + hide: false, + usesWebWorkerLibrary: false, + }; + + if (typeof categoryExample === 'string') + { + return { + ...defaults, + name: categoryExample, + }; + } + + return { + ...defaults, + ...categoryExample, + }; +}; + +const normalizedExamplesData = Object.entries(examplesData as ExamplesJsonType).reduce( + (directoryAcc, [categoryKey, categoryExamples]) => ({ + ...directoryAcc, + [categoryKey]: categoryExamples.reduce((categoryAcc, categoryExampleOrString) => + { + const categoryExample = normalizeExampleDataEntry(categoryExampleOrString); + const { name: categoryName, hide, usesWebWorkerLibrary } = categoryExample; + + return { + ...categoryAcc, + [categoryName]: { + source: examplesSource[categoryKey][categoryName], + hide, + usesWebWorkerLibrary, + }, + }; + }, {} as CategoryDataType), + }), + {} as ExamplesDataType, +); + +export function getExampleEntry(pathString: string): ExampleSourceEntry | undefined +{ + const [directory, example] = pathString.split('.'); + + return normalizedExamplesData[directory]?.[example]; +} + +export function getExampleOptions(): OptionGroup[] +{ + return Object.entries(examplesData as ExamplesJsonType).map(([folderKey, folderEntries]) => + { + const options = folderEntries.reduce((acc, exampleDataEntry) => + { + const { name: exampleKey, hide } = normalizeExampleDataEntry(exampleDataEntry); + + if (hide) + { + return acc; + } + + return acc.concat({ + value: `${folderKey}.${exampleKey}`, + label: camelCaseToSentenceCase(exampleKey), + }); + }, [] as Option[]); + + return { + label: camelCaseToSentenceCase(folderKey), + options, + }; + }); +} diff --git a/src/examples/v8.0.0-rc/masks/filter.js b/src/examples/v8.0.0-rc/masks/filter.js new file mode 100644 index 000000000..47a2cb7fd --- /dev/null +++ b/src/examples/v8.0.0-rc/masks/filter.js @@ -0,0 +1,42 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +// Inner radius of the circle +const radius = 100; + +// The blur amount +const blurSize = 32; + +PIXI.Assets.load('https://pixijs.com/assets/bg_grass.jpg').then((grassTexture) => +{ + const background = new PIXI.Sprite(grassTexture); + + app.stage.addChild(background); + background.width = app.screen.width; + background.height = app.screen.height; + + const circle = new PIXI.Graphics() + .beginFill(0xff0000) + .drawCircle(radius + blurSize, radius + blurSize, radius) + .endFill(); + + circle.filters = [new PIXI.filters.BlurFilter(blurSize)]; + + const bounds = new PIXI.Rectangle(0, 0, (radius + blurSize) * 2, (radius + blurSize) * 2); + const texture = app.renderer.generateTexture(circle, PIXI.SCALE_MODES.NEAREST, 1, bounds); + const focus = new PIXI.Sprite(texture); + + app.stage.addChild(focus); + background.mask = focus; + + app.stage.eventMode = 'static'; + app.stage.hitArea = app.screen; + app.stage.on('pointermove', (event) => + { + focus.position.x = event.global.x - focus.width / 2; + focus.position.y = event.global.y - focus.height / 2; + }); +}); diff --git a/src/examples/v8.0.0-rc/masks/graphics.js b/src/examples/v8.0.0-rc/masks/graphics.js new file mode 100644 index 000000000..976c3e385 --- /dev/null +++ b/src/examples/v8.0.0-rc/masks/graphics.js @@ -0,0 +1,100 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ antialias: true, resizeTo: window }); + +document.body.appendChild(app.view); + +app.stage.eventMode = 'static'; + +const bg = PIXI.Sprite.from('https://pixijs.com/assets/bg_rotate.jpg'); + +bg.anchor.set(0.5); + +bg.x = app.screen.width / 2; +bg.y = app.screen.height / 2; + +app.stage.addChild(bg); + +const container = new PIXI.Container(); + +container.x = app.screen.width / 2; +container.y = app.screen.height / 2; + +// add a bunch of sprites +const bgFront = PIXI.Sprite.from('https://pixijs.com/assets/bg_scene_rotate.jpg'); + +bgFront.anchor.set(0.5); + +const light2 = PIXI.Sprite.from('https://pixijs.com/assets/light_rotate_2.png'); + +light2.anchor.set(0.5); + +const light1 = PIXI.Sprite.from('https://pixijs.com/assets/light_rotate_1.png'); + +light1.anchor.set(0.5); + +const panda = PIXI.Sprite.from('https://pixijs.com/assets/panda.png'); + +panda.anchor.set(0.5); + +container.addChild(bgFront, light2, light1, panda); + +app.stage.addChild(container); + +// let's create a moving shape +const thing = new PIXI.Graphics(); + +app.stage.addChild(thing); +thing.x = app.screen.width / 2; +thing.y = app.screen.height / 2; +thing.lineStyle(0); + +container.mask = thing; + +let count = 0; + +app.stage.on('pointertap', () => +{ + if (!container.mask) + { + container.mask = thing; + } + else + { + container.mask = null; + } +}); + +const help = new PIXI.Text('Click or tap to turn masking on / off.', { + fontFamily: 'Arial', + fontSize: 12, + fontWeight: 'bold', + fill: 'white', +}); + +help.y = app.screen.height - 26; +help.x = 10; +app.stage.addChild(help); + +app.ticker.add(() => +{ + bg.rotation += 0.01; + bgFront.rotation -= 0.01; + + light1.rotation += 0.02; + light2.rotation += 0.01; + + panda.scale.x = 1 + Math.sin(count) * 0.04; + panda.scale.y = 1 + Math.cos(count) * 0.04; + + count += 0.1; + + thing.clear(); + + thing.beginFill(0x8bc5ff, 0.4); + thing.moveTo(-120 + Math.sin(count) * 20, -100 + Math.cos(count) * 20); + thing.lineTo(120 + Math.cos(count) * 20, -100 + Math.sin(count) * 20); + thing.lineTo(120 + Math.sin(count) * 20, 100 + Math.cos(count) * 20); + thing.lineTo(-120 + Math.cos(count) * 20, 100 + Math.sin(count) * 20); + thing.rotation = count * 0.1; +}); diff --git a/src/examples/v8.0.0-rc/masks/sprite.js b/src/examples/v8.0.0-rc/masks/sprite.js new file mode 100644 index 000000000..c30cfead2 --- /dev/null +++ b/src/examples/v8.0.0-rc/masks/sprite.js @@ -0,0 +1,46 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +app.stage.eventMode = 'static'; + +const bg = PIXI.Sprite.from('https://pixijs.com/assets/bg_plane.jpg'); + +app.stage.addChild(bg); + +const cells = PIXI.Sprite.from('https://pixijs.com/assets/cells.png'); + +cells.scale.set(1.5); + +const mask = PIXI.Sprite.from('https://pixijs.com/assets/flowerTop.png'); + +mask.anchor.set(0.5); +mask.x = 310; +mask.y = 190; + +cells.mask = mask; + +app.stage.addChild(mask, cells); + +const target = new PIXI.Point(); + +reset(); + +function reset() +{ + target.x = Math.floor(Math.random() * 550); + target.y = Math.floor(Math.random() * 300); +} + +app.ticker.add(() => +{ + mask.x += (target.x - mask.x) * 0.1; + mask.y += (target.y - mask.y) * 0.1; + + if (Math.abs(mask.x - target.x) < 1) + { + reset(); + } +}); diff --git a/src/examples/v8.0.0-rc/meshAndShaders/instancedGeometry.js b/src/examples/v8.0.0-rc/meshAndShaders/instancedGeometry.js new file mode 100644 index 000000000..31b929ddf --- /dev/null +++ b/src/examples/v8.0.0-rc/meshAndShaders/instancedGeometry.js @@ -0,0 +1,76 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +const geometry = new PIXI.Geometry().addAttribute('aVPos', [-100, 0, 100, 0, 0, -150]); + +geometry.instanced = true; +geometry.instanceCount = 5; + +const positionSize = 2; +const colorSize = 3; +const buffer = new PIXI.Buffer(new Float32Array(geometry.instanceCount * (positionSize + colorSize))); + +geometry.addAttribute('aIPos', buffer, positionSize, false, PIXI.TYPES.FLOAT, 4 * (positionSize + colorSize), 0, true); +geometry.addAttribute( + 'aICol', + buffer, + colorSize, + false, + PIXI.TYPES.FLOAT, + 4 * (positionSize + colorSize), + 4 * positionSize, + true, +); + +for (let i = 0; i < geometry.instanceCount; i++) +{ + const instanceOffset = i * (positionSize + colorSize); + + buffer.data[instanceOffset + 0] = i * 80; + buffer.data[instanceOffset + 2] = Math.random(); + buffer.data[instanceOffset + 3] = Math.random(); + buffer.data[instanceOffset + 4] = Math.random(); +} + +const shader = PIXI.Shader.from( + ` + precision mediump float; + attribute vec2 aVPos; + attribute vec2 aIPos; + attribute vec3 aICol; + + uniform mat3 translationMatrix; + uniform mat3 projectionMatrix; + + varying vec3 vCol; + + void main() { + vCol = aICol; + + gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVPos + aIPos, 1.0)).xy, 0.0, 1.0); + }`, + + `precision mediump float; + + varying vec3 vCol; + + void main() { + gl_FragColor = vec4(vCol, 1.0); + } + +`, +); + +const triangles = new PIXI.Mesh(geometry, shader); + +triangles.position.set(400, 300); + +app.stage.addChild(triangles); + +app.ticker.add((delta) => +{ + triangles.rotation += 0.01; +}); diff --git a/src/examples/v8.0.0-rc/meshAndShaders/interleavingGeometry.js b/src/examples/v8.0.0-rc/meshAndShaders/interleavingGeometry.js new file mode 100644 index 000000000..a8538c756 --- /dev/null +++ b/src/examples/v8.0.0-rc/meshAndShaders/interleavingGeometry.js @@ -0,0 +1,86 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +const geometry = new PIXI.Geometry() + .addAttribute( + 'aVertexPosition', // the attribute name + [ + -100, + -100, // x, y + 100, + -100, // x, y + 100, + 100, + -100, + 100, + ], // x, y + 2, + ) // the size of the attribute + .addAttribute( + 'aUvs', // the attribute name + [ + 0, + 0, // u, v + 1, + 0, // u, v + 1, + 1, + 0, + 1, + ], // u, v + 2, + ) // the size of the attribute + .addIndex([0, 1, 2, 0, 2, 3]) + .interleave(); + +const shader = PIXI.Shader.from( + ` + + precision mediump float; + + attribute vec2 aVertexPosition; + attribute vec2 aUvs; + + uniform mat3 translationMatrix; + uniform mat3 projectionMatrix; + + varying vec2 vUvs; + + void main() { + + vUvs = aUvs; + gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0); + + }`, + + `precision mediump float; + + varying vec2 vUvs; + + uniform sampler2D uSampler2; + + void main() { + + gl_FragColor = texture2D(uSampler2, vUvs ); + } + +`, + { + uSampler2: PIXI.Texture.from('https://pixijs.com/assets/bg_scene_rotate.jpg'), + }, +); + +const quad = new PIXI.Mesh(geometry, shader); + +quad.position.set(400, 300); +quad.scale.set(2); + +app.stage.addChild(quad); + +app.ticker.add((delta) => +{ + quad.rotation += 0.01; +}); diff --git a/src/examples/v8.0.0-rc/meshAndShaders/mergingGeometry.js b/src/examples/v8.0.0-rc/meshAndShaders/mergingGeometry.js new file mode 100644 index 000000000..31e78cdf6 --- /dev/null +++ b/src/examples/v8.0.0-rc/meshAndShaders/mergingGeometry.js @@ -0,0 +1,114 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +const geometry = new PIXI.Geometry() + .addAttribute( + 'aVertexPosition', // the attribute name + [ + -100, + -100, // x, y + 100, + -100, // x, y + 100, + 100, + -100, + 100, + ], // x, y + 2, + ) // the size of the attribute + .addAttribute( + 'aUvs', // the attribute name + [ + 0, + 0, // u, v + 1, + 0, // u, v + 1, + 1, + 0, + 1, + ], // u, v + 2, + ) // the size of the attribute + .addIndex([0, 1, 2, 0, 2, 3]); + +const geometry2 = new PIXI.Geometry() + .addAttribute( + 'aVertexPosition', // the attribute name + [ + -100 + 100, + -100, // x, y + 100 + 100, + -100, // x, y + 100 + 100, + 100, + ], // x, y + 2, + ) // the size of the attribute + .addAttribute( + 'aUvs', // the attribute name + [ + 0, + 0, // u, v + 1, + 0, // u, v + 1, + 1, + ], // u, v + 2, + ) // the size of the attribute + .addIndex([0, 1, 2]); + +const geometry3 = PIXI.Geometry.merge([geometry, geometry2]); + +const shader = PIXI.Shader.from( + ` + + precision mediump float; + + attribute vec2 aVertexPosition; + attribute vec2 aUvs; + + uniform mat3 translationMatrix; + uniform mat3 projectionMatrix; + + varying vec2 vUvs; + + void main() { + + vUvs = aUvs; + gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0); + + }`, + + `precision mediump float; + + varying vec2 vUvs; + + uniform sampler2D uSampler2; + + void main() { + + gl_FragColor = texture2D(uSampler2, vUvs ); + } + +`, + { + uSampler2: PIXI.Texture.from('https://pixijs.com/assets/bg_scene_rotate.jpg'), + }, +); + +const quad = new PIXI.Mesh(geometry3, shader); + +quad.position.set(400, 300); +quad.scale.set(2); + +app.stage.addChild(quad); + +app.ticker.add((delta) => +{ + quad.rotation += 0.01; +}); diff --git a/src/examples/v8.0.0-rc/meshAndShaders/multiPassShaderGeneratedMesh.js b/src/examples/v8.0.0-rc/meshAndShaders/multiPassShaderGeneratedMesh.js new file mode 100644 index 000000000..1375ca5cb --- /dev/null +++ b/src/examples/v8.0.0-rc/meshAndShaders/multiPassShaderGeneratedMesh.js @@ -0,0 +1,235 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ height: 640, resizeTo: window }); + +document.body.appendChild(app.view); + +// Build geometry. +const geometry = new PIXI.Geometry() + .addAttribute( + 'aVertexPosition', // the attribute name + [ + 0, + 0, // x, y + 200, + 0, // x, y + 200, + 200, + 0, + 200, + ], // x, y + 2, + ) // the size of the attribute + .addAttribute( + 'aUvs', // the attribute name + [ + 0, + 0, // u, v + 1, + 0, // u, v + 1, + 1, + 0, + 1, + ], // u, v + 2, + ) // the size of the attribute + .addIndex([0, 1, 2, 0, 2, 3]); + +// Vertex shader. Use same shader for all passes. +const vertexSrc = ` + + precision mediump float; + + attribute vec2 aVertexPosition; + attribute vec2 aUvs; + + uniform mat3 translationMatrix; + uniform mat3 projectionMatrix; + + varying vec2 vUvs; + + void main() { + + vUvs = aUvs; + gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0); + + }`; + +// Load a perlinnoise texture for one of the shaders. +const perlinTexture = PIXI.Texture.from('https://pixijs.com/assets/perlin.jpg'); + +// First pass, generates a grid. +const fragmentGridSrc = ` +precision mediump float; +varying vec2 vUvs; +uniform float zoom; + +void main() +{ + //Generate a simple grid. + //Offset uv so that center is 0,0 and edges are -1,1 + vec2 uv = (vUvs-vec2(0.5))*2.0; + vec2 gUv = floor(uv*zoom); + vec4 color1 = vec4(0.8, 0.8, 0.8, 1.0); + vec4 color2 = vec4(0.4, 0.4, 0.4, 1.0); + vec4 outColor = mod(gUv.x + gUv.y, 2.) < 0.5 ? color1 : color2; + gl_FragColor = outColor; + +}`; + +const gridUniforms = { + zoom: 10, +}; +const gridShader = PIXI.Shader.from(vertexSrc, fragmentGridSrc, gridUniforms); +// Sharing textures and meshes is possible. +// But for simplicity each pass has its own output texture and mesh in this example. +const gridTexture = PIXI.RenderTexture.create({ width: 200, height: 200 }); +const gridQuad = new PIXI.Mesh(geometry, gridShader); +const gridContainer = new PIXI.Container(); + +gridContainer.addChild(gridQuad); + +// Second pass. Takes grid as input and makes it ripple. +const fragmentRippleSrc = ` +precision mediump float; +varying vec2 vUvs; +uniform float amount; +uniform float phase; +uniform sampler2D texIn; + +void main() +{ + //Generate a simple grid. + vec2 uv = vUvs; + //Calculate distance from center + float distance = length( uv - vec2(0.5)); + vec4 color = texture2D(texIn, uv); + color.rgb *= sin(distance*25.0+phase) * amount+1.; + gl_FragColor = color; +}`; +const rippleUniforms = { + amount: 0.5, + phase: 0, + texIn: gridTexture, +}; +const rippleShader = PIXI.Shader.from(vertexSrc, fragmentRippleSrc, rippleUniforms); +const rippleTexture = PIXI.RenderTexture.create({ width: 200, height: 200 }); +const rippleQuad = new PIXI.Mesh(geometry, rippleShader); +const rippleContainer = new PIXI.Container(); + +rippleContainer.addChild(rippleQuad); + +// Second effect. Generates a filtered noise. +const fragmentNoiseSrc = ` +precision mediump float; +varying vec2 vUvs; +uniform float limit; +uniform sampler2D noise; + +void main() +{ + float color = texture2D(noise, vUvs).r; + color = step(limit, color); + gl_FragColor = vec4(color); +}`; +const noiseUniforms = { + limit: 0.5, + noise: perlinTexture, +}; +const noiseShader = PIXI.Shader.from(vertexSrc, fragmentNoiseSrc, noiseUniforms); +const noiseTexture = PIXI.RenderTexture.create({ width: 200, height: 200 }); +const noiseQuad = new PIXI.Mesh(geometry, noiseShader); +const noiseContainer = new PIXI.Container(); + +noiseContainer.addChild(noiseQuad); + +// Third effect +const fragmentWaveSrc = ` +precision mediump float; +varying vec2 vUvs; +uniform float amplitude; +uniform float time; + +void main() +{ + //Offset uv so that center is 0,0 and edges are -1,1 + vec2 uv = (vUvs-vec2(0.5))*2.0; + + vec3 outColor = vec3(0.); + + //Simple wavefunctions inversed and with small offsets. + outColor += 5./length(uv.y*200. - 50.0*sin( uv.x*0.25+ time*0.25)*amplitude); + outColor += 4./length(uv.y*300. - 100.0*sin(uv.x*0.5+time*0.5)*amplitude*1.2); + outColor += 3./length(uv.y*400. - 150.0*sin(uv.x*0.75+time*0.75)*amplitude*1.4); + outColor += 2./length(uv.y*500. - 200.0*sin(uv.x+time)*amplitude*1.6); + + gl_FragColor = vec4(outColor,1.0); +}`; +const waveUniforms = { + amplitude: 0.75, + time: 0, +}; +const waveShader = PIXI.Shader.from(vertexSrc, fragmentWaveSrc, waveUniforms); +const waveTexture = PIXI.RenderTexture.create({ width: 200, height: 200 }); +const waveQuad = new PIXI.Mesh(geometry, waveShader); +const waveContainer = new PIXI.Container(); + +waveContainer.addChild(waveQuad); + +// Final combination pass +const fragmentCombineSrc = ` +precision mediump float; +varying vec2 vUvs; + +uniform sampler2D texRipple; +uniform sampler2D texNoise; +uniform sampler2D texWave; + +void main() +{ + //Read color from all + vec4 ripple = texture2D(texRipple, vUvs); + vec4 noise = texture2D(texNoise, vUvs); + vec4 wave = texture2D(texWave, vUvs); + + gl_FragColor = mix(ripple, wave,noise.r); +}`; +const combineUniforms = { + texRipple: rippleTexture, + texNoise: noiseTexture, + texWave: waveTexture, +}; +const combineShader = PIXI.Shader.from(vertexSrc, fragmentCombineSrc, combineUniforms); +const combineQuad = new PIXI.Mesh(geometry, combineShader); + +gridContainer.position.set(10, 10); +rippleContainer.position.set(220, 10); +noiseContainer.position.set(10, 220); +waveContainer.position.set(10, 430); +combineQuad.position.set(430, 220); + +// Add all phases to stage so all the phases can be seen separately. +app.stage.addChild(gridContainer); +app.stage.addChild(rippleContainer); +app.stage.addChild(noiseContainer); +app.stage.addChild(waveContainer); +app.stage.addChild(combineQuad); + +// start the animation.. +let time = 0; + +app.ticker.add((delta) => +{ + time += 1 / 60; + // gridQuad.shader.uniforms.zoom = Math.sin(time)*5+10; + rippleQuad.shader.uniforms.phase = -time; + waveQuad.shader.uniforms.time = time; + noiseQuad.shader.uniforms.limit = Math.sin(time * 0.5) * 0.35 + 0.5; + + // Render the passes to get textures. + app.renderer.render(gridQuad, { renderTexture: gridTexture }); + app.renderer.render(rippleQuad, { renderTexture: rippleTexture }); + app.renderer.render(noiseQuad, { renderTexture: noiseTexture }); + app.renderer.render(waveQuad, { renderTexture: waveTexture }); +}); diff --git a/src/examples/v8.0.0-rc/meshAndShaders/shaderToyMesh.js b/src/examples/v8.0.0-rc/meshAndShaders/shaderToyMesh.js new file mode 100644 index 000000000..cc078d525 --- /dev/null +++ b/src/examples/v8.0.0-rc/meshAndShaders/shaderToyMesh.js @@ -0,0 +1,155 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +// Build geometry. +const geometry = new PIXI.Geometry() + .addAttribute( + 'aVertexPosition', // the attribute name + [ + -100, + -100, // x, y + 100, + -100, // x, y + 100, + 100, + -100, + 100, + ], // x, y + 2, + ) // the size of the attribute + .addAttribute( + 'aUvs', // the attribute name + [ + 0, + 0, // u, v + 1, + 0, // u, v + 1, + 1, + 0, + 1, + ], // u, v + 2, + ) // the size of the attribute + .addIndex([0, 1, 2, 0, 2, 3]); + +const vertexSrc = ` + + precision mediump float; + + attribute vec2 aVertexPosition; + attribute vec2 aUvs; + + uniform mat3 translationMatrix; + uniform mat3 projectionMatrix; + + varying vec2 vUvs; + + void main() { + + vUvs = aUvs; + gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0); + + }`; + +const fragmentSrc = ` +//Based on this: https://www.shadertoy.com/view/wtlSWX +precision mediump float; + +varying vec2 vUvs; + +uniform sampler2D noise; +uniform float time; + +// Distance function. Just calculates the height (z) from x,y plane with really simple length check. +// Its not exact as there could be shorter distances. +vec2 dist(vec3 p) +{ + float id = floor(p.x)+floor(p.y); + id = mod(id, 2.); + float h = texture2D(noise, vec2(p.x, p.y)*0.04).r*5.1; + return vec2(h-p.z,id); +} + +//Light calculation. +vec3 calclight(vec3 p, vec3 rd) +{ + vec2 eps = vec2( 0., 0.001); + vec3 n = normalize( vec3( + dist(p+eps.yxx).x - dist(p-eps.yxx).x, + dist(p+eps.xyx).x - dist(p-eps.xyx).x, + dist(p+eps.xxy).x - dist(p-eps.xxy).x + )); + + vec3 d = vec3( max( 0., dot( -rd ,n))); + + return d; +} + +void main() +{ + vec2 uv = vec2(vUvs.x,1.-vUvs.y); + uv *=2.; + uv-=1.; + + vec3 cam = vec3(0.,time -2., -3.); + vec3 target = vec3(sin(time)*0.1, time+cos(time)+2., 0. ); + float fov = 2.2; + vec3 forward = normalize( target - cam); + vec3 up = normalize(cross( forward, vec3(0., 1.,0.))); + vec3 right = normalize( cross( up, forward)); + vec3 raydir = normalize(vec3( uv.x *up + uv.y * right + fov*forward)); + + //Do the raymarch + vec3 col = vec3(0.); + float t = 0.; + for( int i = 0; i < 100; i++) + { + vec3 p = t * raydir + cam; + vec2 d = dist(p); + t+=d.x*0.5;//Jump only half of the distance as height function used is not really the best for heightmaps. + if(d.x < 0.001) + { + vec3 bc = d.y < 0.5 ? vec3(1.0, .8, 0.) : + vec3(0.8,0.0, 1.0); + col = vec3( 1.) * calclight(p, raydir) * (1. - t/150.) *bc; + break; + } + if(t > 1000.) + { + break; + } + } + gl_FragColor = vec4(col, 1.); +}`; + +const uniforms = { + noise: PIXI.Texture.from('https://pixijs.com/assets/perlin.jpg'), + time: 0, +}; +// Make sure repeat wrap is used and no mipmapping. + +uniforms.noise.baseTexture.wrapMode = PIXI.WRAP_MODES.REPEAT; +uniforms.noise.baseTexture.mipmap = false; + +// Build the shader and the quad. +const shader = PIXI.Shader.from(vertexSrc, fragmentSrc, uniforms); +const quad = new PIXI.Mesh(geometry, shader); + +quad.position.set(400, 300); +quad.scale.set(2); + +app.stage.addChild(quad); + +// start the animation.. +let time = 0; + +app.ticker.add((delta) => +{ + time += 1 / 60; + quad.shader.uniforms.time = time; + quad.scale.set(Number(Math.cos(time)) + 2, Number(Math.sin(time * 0.7)) + 2); +}); diff --git a/src/examples/v8.0.0-rc/meshAndShaders/sharedShader.js b/src/examples/v8.0.0-rc/meshAndShaders/sharedShader.js new file mode 100644 index 000000000..66a18fa55 --- /dev/null +++ b/src/examples/v8.0.0-rc/meshAndShaders/sharedShader.js @@ -0,0 +1,124 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +const geometry = new PIXI.Geometry() + .addAttribute( + 'aVertexPosition', // the attribute name + [ + -100, + -100, // x, y + 100, + -100, // x, y + 100, + 100, + ], + ) // x, y + + .addAttribute( + 'aUvs', // the attribute name + [ + 0, + 0, // u, v + 1, + 0, // u, v + 1, + 1, + ], + ); // u, v + +const shader = PIXI.Shader.from( + ` + + precision mediump float; + + attribute vec2 aVertexPosition; + attribute vec2 aUvs; + + uniform mat3 translationMatrix; + uniform mat3 projectionMatrix; + + varying vec2 vUvs; + + void main() { + + vUvs = aUvs; + gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0); + + }`, + + `precision mediump float; + + varying vec2 vUvs; + + uniform sampler2D uSampler2; + + void main() { + + gl_FragColor = texture2D(uSampler2, vUvs); + } + +`, + { + uSampler2: PIXI.Texture.from('https://pixijs.com/assets/bg_scene_rotate.jpg'), + }, +); + +const shader2 = PIXI.Shader.from( + ` + + precision mediump float; + + attribute vec2 aVertexPosition; + attribute vec2 aUvs; + + uniform mat3 translationMatrix; + uniform mat3 projectionMatrix; + + varying vec2 vUvs; + + void main() { + + vUvs = aUvs; + gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0); + + }`, + + `precision mediump float; + + varying vec2 vUvs; + + uniform sampler2D uSampler2; + + void main() { + + gl_FragColor = texture2D(uSampler2, vUvs); + gl_FragColor.r += (abs(sin(gl_FragCoord.x * 0.06)) * 0.5) * 2.; + gl_FragColor.g += (abs(cos(gl_FragCoord.y * 0.06)) * 0.5) * 2.; + } + +`, + { + uSampler2: PIXI.Texture.from('https://pixijs.com/assets/bg_scene_rotate.jpg'), + }, +); + +const triangle = new PIXI.Mesh(geometry, shader); + +const triangle2 = new PIXI.Mesh(geometry, shader2); + +triangle.position.set(400, 300); +triangle.scale.set(2); + +triangle2.position.set(500, 400); +triangle2.scale.set(3); + +app.stage.addChild(triangle2, triangle); + +app.ticker.add((delta) => +{ + triangle.rotation += 0.01; + triangle2.rotation -= 0.005; +}); diff --git a/src/examples/v8.0.0-rc/meshAndShaders/sharingGeometry.js b/src/examples/v8.0.0-rc/meshAndShaders/sharingGeometry.js new file mode 100644 index 000000000..b53923573 --- /dev/null +++ b/src/examples/v8.0.0-rc/meshAndShaders/sharingGeometry.js @@ -0,0 +1,104 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +const geometry = new PIXI.Geometry() + .addAttribute( + 'aVertexPosition', // the attribute name + [ + -100, + -100, // x, y + 100, + -100, // x, y + 100, + 100, + ], // x, y + 2, + ) // the size of the attribute + + .addAttribute( + 'aUvs', // the attribute name + [ + 0, + 0, // u, v + 1, + 0, // u, v + 1, + 1, + ], // u, v + 2, + ); // the size of the attribute + +const program = PIXI.Program.from( + ` + + precision mediump float; + + attribute vec2 aVertexPosition; + attribute vec2 aUvs; + + uniform mat3 translationMatrix; + uniform mat3 projectionMatrix; + + varying vec2 vUvs; + + void main() { + + vUvs = aUvs; + gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0); + + }`, + + `precision mediump float; + + varying vec2 vUvs; + + uniform sampler2D uSamplerTexture; + + void main() { + + gl_FragColor = texture2D(uSamplerTexture, vUvs); + } + +`, +); + +const triangle = new PIXI.Mesh( + geometry, + new PIXI.Shader(program, { + uSamplerTexture: PIXI.Texture.from('https://pixijs.com/assets/bg_scene_rotate.jpg'), + }), +); + +const triangle2 = new PIXI.Mesh( + geometry, + new PIXI.Shader(program, { + uSamplerTexture: PIXI.Texture.from('https://pixijs.com/assets/bg_rotate.jpg'), + }), +); + +const triangle3 = new PIXI.Mesh( + geometry, + new PIXI.Shader(program, { + uSamplerTexture: PIXI.Texture.from('https://pixijs.com/assets/bg_displacement.jpg'), + }), +); + +triangle.position.set(400, 300); +triangle.scale.set(2); + +triangle2.position.set(200, 100); + +triangle3.position.set(500, 400); +triangle3.scale.set(3); + +app.stage.addChild(triangle3, triangle2, triangle); + +app.ticker.add((delta) => +{ + triangle.rotation += 0.01; + triangle2.rotation -= 0.01; + triangle3.rotation -= 0.005; +}); diff --git a/src/examples/v8.0.0-rc/meshAndShaders/texturedMeshAdvanced.js b/src/examples/v8.0.0-rc/meshAndShaders/texturedMeshAdvanced.js new file mode 100644 index 000000000..9b4c60c08 --- /dev/null +++ b/src/examples/v8.0.0-rc/meshAndShaders/texturedMeshAdvanced.js @@ -0,0 +1,64 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +let count = 0; + +// build a rope! +const ropeLength = 45; + +const points = []; + +for (let i = 0; i < 25; i++) +{ + points.push(new PIXI.Point(i * ropeLength, 0)); +} + +const strip = new PIXI.SimpleRope(PIXI.Texture.from('https://pixijs.com/assets/snake.png'), points); + +strip.x = -40; +strip.y = 300; + +app.stage.addChild(strip); + +const g = new PIXI.Graphics(); + +g.x = strip.x; +g.y = strip.y; +app.stage.addChild(g); + +// start animating +app.ticker.add(() => +{ + count += 0.1; + + // make the snake + for (let i = 0; i < points.length; i++) + { + points[i].y = Math.sin(i * 0.5 + count) * 30; + points[i].x = i * ropeLength + Math.cos(i * 0.3 + count) * 20; + } + renderPoints(); +}); + +function renderPoints() +{ + g.clear(); + + g.lineStyle(2, 0xffc2c2); + g.moveTo(points[0].x, points[0].y); + + for (let i = 1; i < points.length; i++) + { + g.lineTo(points[i].x, points[i].y); + } + + for (let i = 1; i < points.length; i++) + { + g.beginFill(0xff0022); + g.drawCircle(points[i].x, points[i].y, 10); + g.endFill(); + } +} diff --git a/src/examples/v8.0.0-rc/meshAndShaders/texturedMeshBasic.js b/src/examples/v8.0.0-rc/meshAndShaders/texturedMeshBasic.js new file mode 100644 index 000000000..c8f01a788 --- /dev/null +++ b/src/examples/v8.0.0-rc/meshAndShaders/texturedMeshBasic.js @@ -0,0 +1,43 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +let count = 0; + +// build a rope! +const ropeLength = 918 / 20; + +const points = []; + +for (let i = 0; i < 20; i++) +{ + points.push(new PIXI.Point(i * ropeLength, 0)); +} + +const strip = new PIXI.SimpleRope(PIXI.Texture.from('https://pixijs.com/assets/snake.png'), points); + +strip.x = -459; + +const snakeContainer = new PIXI.Container(); + +snakeContainer.x = 400; +snakeContainer.y = 300; + +snakeContainer.scale.set(800 / 1100); +app.stage.addChild(snakeContainer); + +snakeContainer.addChild(strip); + +app.ticker.add(() => +{ + count += 0.1; + + // make the snake + for (let i = 0; i < points.length; i++) + { + points[i].y = Math.sin(i * 0.5 + count) * 30; + points[i].x = i * ropeLength + Math.cos(i * 0.3 + count) * 20; + } +}); diff --git a/src/examples/v8.0.0-rc/meshAndShaders/triangle.js b/src/examples/v8.0.0-rc/meshAndShaders/triangle.js new file mode 100644 index 000000000..67a43059f --- /dev/null +++ b/src/examples/v8.0.0-rc/meshAndShaders/triangle.js @@ -0,0 +1,40 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +const geometry = new PIXI.Geometry().addAttribute('aVertexPosition', [-100, -50, 100, -50, 0, 100]); + +const shader = PIXI.Shader.from( + ` + + precision mediump float; + attribute vec2 aVertexPosition; + + uniform mat3 translationMatrix; + uniform mat3 projectionMatrix; + + void main() { + gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0); + }`, + + `precision mediump float; + + void main() { + gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); + } + +`, +); + +const triangle = new PIXI.Mesh(geometry, shader); + +triangle.position.set(400, 300); + +app.stage.addChild(triangle); + +app.ticker.add((delta) => +{ + triangle.rotation += 0.01; +}); diff --git a/src/examples/v8.0.0-rc/meshAndShaders/triangleColor.js b/src/examples/v8.0.0-rc/meshAndShaders/triangleColor.js new file mode 100644 index 000000000..92ca929db --- /dev/null +++ b/src/examples/v8.0.0-rc/meshAndShaders/triangleColor.js @@ -0,0 +1,77 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +const geometry = new PIXI.Geometry() + .addAttribute( + 'aVertexPosition', // the attribute name + [ + -100, + -50, // x, y + 100, + -50, // x, y + 0.0, + 100.0, + ], // x, y + 2, + ) // the size of the attribute + + .addAttribute( + 'aColor', // the attribute name + [ + 1, + 0, + 0, // r, g, b + 0, + 1, + 0, // r, g, b + 0, + 0, + 1, + ], // r, g, b + 3, + ); // the size of the attribute + +const shader = PIXI.Shader.from( + ` + + precision mediump float; + attribute vec2 aVertexPosition; + attribute vec3 aColor; + + uniform mat3 translationMatrix; + uniform mat3 projectionMatrix; + + varying vec3 vColor; + + void main() { + + vColor = aColor; + gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0); + + }`, + + `precision mediump float; + + varying vec3 vColor; + + void main() { + gl_FragColor = vec4(vColor, 1.0); + } + +`, +); + +const triangle = new PIXI.Mesh(geometry, shader); + +triangle.position.set(400, 300); +triangle.scale.set(2); + +app.stage.addChild(triangle); + +app.ticker.add((delta) => +{ + triangle.rotation += 0.01; +}); diff --git a/src/examples/v8.0.0-rc/meshAndShaders/triangleTextured.js b/src/examples/v8.0.0-rc/meshAndShaders/triangleTextured.js new file mode 100644 index 000000000..91c7c31ec --- /dev/null +++ b/src/examples/v8.0.0-rc/meshAndShaders/triangleTextured.js @@ -0,0 +1,100 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +const geometry = new PIXI.Geometry() + .addAttribute( + 'aVertexPosition', // the attribute name + [ + -100, + -100, // x, y + 100, + -100, // x, y + 100, + 100, + ], // x, y + 2, + ) // the size of the attribute + + .addAttribute( + 'aColor', // the attribute name + [ + 1, + 0, + 0, // r, g, b + 0, + 1, + 0, // r, g, b + 0, + 0, + 1, + ], // r, g, b + 3, + ) // the size of the attribute + + .addAttribute( + 'aUvs', // the attribute name + [ + 0, + 0, // u, v + 1, + 0, // u, v + 1, + 1, + ], // u, v + 2, + ); // the size of the attribute + +const vertexSrc = ` + + precision mediump float; + + attribute vec2 aVertexPosition; + attribute vec3 aColor; + attribute vec2 aUvs; + + uniform mat3 translationMatrix; + uniform mat3 projectionMatrix; + + varying vec2 vUvs; + varying vec3 vColor; + + void main() { + + vUvs = aUvs; + vColor = aColor; + gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0); + + }`; + +const fragmentSrc = ` + + precision mediump float; + + varying vec3 vColor; + varying vec2 vUvs; + + uniform sampler2D uSampler2; + + void main() { + + gl_FragColor = texture2D(uSampler2, vUvs) * vec4(vColor, 1.0); + }`; + +const uniforms = { uSampler2: PIXI.Texture.from('https://pixijs.com/assets/bg_scene_rotate.jpg') }; + +const shader = PIXI.Shader.from(vertexSrc, fragmentSrc, uniforms); + +const triangle = new PIXI.Mesh(geometry, shader); + +triangle.position.set(400, 300); +triangle.scale.set(2); + +app.stage.addChild(triangle); + +app.ticker.add((delta) => +{ + triangle.rotation += 0.01; +}); diff --git a/src/examples/v8.0.0-rc/meshAndShaders/uniforms.js b/src/examples/v8.0.0-rc/meshAndShaders/uniforms.js new file mode 100644 index 000000000..b057916c3 --- /dev/null +++ b/src/examples/v8.0.0-rc/meshAndShaders/uniforms.js @@ -0,0 +1,92 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +const geometry = new PIXI.Geometry() + .addAttribute( + 'aVertexPosition', // the attribute name + [ + -100, + -100, // x, y + 100, + -100, // x, y + 100, + 100, + -100, + 100, + ], // x, y + 2, + ) // the size of the attribute + .addAttribute( + 'aUvs', // the attribute name + [ + 0, + 0, // u, v + 1, + 0, // u, v + 1, + 1, + 0, + 1, + ], // u, v + 2, + ) // the size of the attribute + .addIndex([0, 1, 2, 0, 2, 3]); + +const vertexSrc = ` + + precision mediump float; + + attribute vec2 aVertexPosition; + attribute vec2 aUvs; + + uniform mat3 translationMatrix; + uniform mat3 projectionMatrix; + + varying vec2 vUvs; + + void main() { + + vUvs = aUvs; + gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0); + + }`; + +const fragmentSrc = ` + + precision mediump float; + + varying vec2 vUvs; + + uniform sampler2D uSampler2; + uniform float time; + + void main() { + + gl_FragColor = texture2D(uSampler2, vUvs + sin( (time + (vUvs.x) * 14.) ) * 0.1 ); + }`; + +const uniforms = { + uSampler2: PIXI.Texture.from('https://pixijs.com/assets/bg_scene_rotate.jpg'), + time: 0, +}; + +const shader = PIXI.Shader.from(vertexSrc, fragmentSrc, uniforms); + +const quad = new PIXI.Mesh(geometry, shader); + +quad.position.set(400, 300); +quad.scale.set(2); + +app.stage.addChild(quad); + +// start the animation.. +// requestAnimationFrame(animate); + +app.ticker.add((delta) => +{ + quad.rotation += 0.01; + quad.shader.uniforms.time += 0.1; +}); diff --git a/src/examples/v8.0.0-rc/offscreenCanvas/basic.js b/src/examples/v8.0.0-rc/offscreenCanvas/basic.js new file mode 100644 index 000000000..7f7ad943b --- /dev/null +++ b/src/examples/v8.0.0-rc/offscreenCanvas/basic.js @@ -0,0 +1,44 @@ +import * as PIXI from 'pixi.js'; + +// This example is the based on basic/container, but using OffscreenCanvas. + +const canvas = document.createElement('canvas'); +const view = canvas.transferControlToOffscreen(); + +const app = new PIXI.Application({ view, background: 0x1099bb, resizeTo: window }); + +document.body.appendChild(canvas); + +const container = new PIXI.Container(); + +app.stage.addChild(container); + +// Create a new texture +const texture = PIXI.Texture.from('https://pixijs.com/assets/bunny.png'); + +// Create a 5x5 grid of bunnies +for (let i = 0; i < 25; i++) +{ + const bunny = new PIXI.Sprite(texture); + + bunny.anchor.set(0.5); + bunny.x = (i % 5) * 40; + bunny.y = Math.floor(i / 5) * 40; + container.addChild(bunny); +} + +// Move container to the center +container.x = app.screen.width / 2; +container.y = app.screen.height / 2; + +// Center bunny sprite in local container coordinates +container.pivot.x = container.width / 2; +container.pivot.y = container.height / 2; + +// Listen for animate update +app.ticker.add((delta) => +{ + // rotate the container! + // use delta to create frame-independent transform + container.rotation -= 0.01 * delta; +}); diff --git a/src/examples/v8.0.0-rc/offscreenCanvas/webWorker.js b/src/examples/v8.0.0-rc/offscreenCanvas/webWorker.js new file mode 100644 index 000000000..44f0b99e6 --- /dev/null +++ b/src/examples/v8.0.0-rc/offscreenCanvas/webWorker.js @@ -0,0 +1,84 @@ +import * as PIXI from '@pixi/webworker'; + +// This example is the based on basic/container, but running in Web Worker. + +function workerSource(self) +{ + self.onmessage = async ({ data: { baseUrl, pixiWebWorkerUrl, options } }) => + { + self.importScripts(new URL(pixiWebWorkerUrl, baseUrl)); + + const app = new PIXI.Application(options); + + document.body.appendChild(app.view); + + const container = new PIXI.Container(); + + app.stage.addChild(container); + + // Create a new texture + const textureUrl = new URL('https://pixijs.com/assets/bunny.png', baseUrl).toString(); + const texture = PIXI.Texture.from(textureUrl); + + // Create a 5x5 grid of bunnies + for (let i = 0; i < 25; i++) + { + const bunny = new PIXI.Sprite(texture); + + bunny.anchor.set(0.5); + bunny.x = (i % 5) * 40; + bunny.y = Math.floor(i / 5) * 40; + container.addChild(bunny); + } + + // Move container to the center + container.x = app.screen.width / 2; + container.y = app.screen.height / 2; + + // Center bunny sprite in local container coordinates + container.pivot.x = container.width / 2; + container.pivot.y = container.height / 2; + + // Listen for animate update + app.ticker.add((delta) => + { + // rotate the container! + // use delta to create frame-independent transform + container.rotation -= 0.01 * delta; + }); + }; +} + +const blob = new Blob(['(', workerSource, ')(self);'], { type: 'application/javascript' }); + +const url = URL.createObjectURL(blob); +const worker = new Worker(url); + +URL.revokeObjectURL(url); + +const width = 800; +const height = 600; +const resolution = window.devicePixelRatio; +const canvas = document.createElement('canvas'); + +canvas.style.width = `${width}px`; +canvas.style.height = `${height}px`; +const view = canvas.transferControlToOffscreen(); + +const baseUrl = window.location.href; +const pixiWebWorkerUrl = window.PIXI_WEBWORKER_URL; + +worker.postMessage( + { + baseUrl, + pixiWebWorkerUrl, + options: { + width, + height, + resolution, + view, + background: 0x1099bb, + }, + }, + [view], +); diff --git a/src/examples/v8.0.0-rc/sprite/animatedSpriteAnimationSpeed.js b/src/examples/v8.0.0-rc/sprite/animatedSpriteAnimationSpeed.js new file mode 100644 index 000000000..6f7ac5118 --- /dev/null +++ b/src/examples/v8.0.0-rc/sprite/animatedSpriteAnimationSpeed.js @@ -0,0 +1,47 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ autoStart: false, resizeTo: window }); + +document.body.appendChild(app.view); + +PIXI.Assets.load('https://pixijs.com/assets/spritesheet/0123456789.json').then((spritesheet) => +{ + // create an array to store the textures + const textures = []; + let i; + + for (i = 0; i < 10; i++) + { + const framekey = `0123456789 ${i}.ase`; + const texture = PIXI.Texture.from(framekey); + const time = spritesheet.data.frames[framekey].duration; + + textures.push({ texture, time }); + } + + const scaling = 4; + + // create a slow AnimatedSprite + const slow = new PIXI.AnimatedSprite(textures); + + slow.anchor.set(0.5); + slow.scale.set(scaling); + slow.animationSpeed = 0.5; + slow.x = (app.screen.width - slow.width) / 2; + slow.y = app.screen.height / 2; + slow.play(); + app.stage.addChild(slow); + + // create a fast AnimatedSprite + const fast = new PIXI.AnimatedSprite(textures); + + fast.anchor.set(0.5); + fast.scale.set(scaling); + fast.x = (app.screen.width + fast.width) / 2; + fast.y = app.screen.height / 2; + fast.play(); + app.stage.addChild(fast); + + // start animating + app.start(); +}); diff --git a/src/examples/v8.0.0-rc/sprite/animatedSpriteExplosion.js b/src/examples/v8.0.0-rc/sprite/animatedSpriteExplosion.js new file mode 100644 index 000000000..2a1ac9554 --- /dev/null +++ b/src/examples/v8.0.0-rc/sprite/animatedSpriteExplosion.js @@ -0,0 +1,36 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ autoStart: false, resizeTo: window }); + +document.body.appendChild(app.view); + +PIXI.Assets.load('https://pixijs.com/assets/spritesheet/mc.json').then(() => +{ + // create an array to store the textures + const explosionTextures = []; + let i; + + for (i = 0; i < 26; i++) + { + const texture = PIXI.Texture.from(`Explosion_Sequence_A ${i + 1}.png`); + + explosionTextures.push(texture); + } + + for (i = 0; i < 50; i++) + { + // create an explosion AnimatedSprite + const explosion = new PIXI.AnimatedSprite(explosionTextures); + + explosion.x = Math.random() * app.screen.width; + explosion.y = Math.random() * app.screen.height; + explosion.anchor.set(0.5); + explosion.rotation = Math.random() * Math.PI; + explosion.scale.set(0.75 + Math.random() * 0.5); + explosion.gotoAndPlay((Math.random() * 26) | 0); + app.stage.addChild(explosion); + } + + // start animating + app.start(); +}); diff --git a/src/examples/v8.0.0-rc/sprite/animatedSpriteJet.js b/src/examples/v8.0.0-rc/sprite/animatedSpriteJet.js new file mode 100644 index 000000000..98111eb14 --- /dev/null +++ b/src/examples/v8.0.0-rc/sprite/animatedSpriteJet.js @@ -0,0 +1,40 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +PIXI.Assets.load('https://pixijs.com/assets/spritesheet/fighter.json').then(() => +{ + // create an array of textures from an image path + const frames = []; + + for (let i = 0; i < 30; i++) + { + const val = i < 10 ? `0${i}` : i; + + // magically works since the spritesheet was loaded with the pixi loader + frames.push(PIXI.Texture.from(`rollSequence00${val}.png`)); + } + + // create an AnimatedSprite (brings back memories from the days of Flash, right ?) + const anim = new PIXI.AnimatedSprite(frames); + + /* + * An AnimatedSprite inherits all the properties of a PIXI sprite + * so you can change its position, its anchor, mask it, etc + */ + anim.x = app.screen.width / 2; + anim.y = app.screen.height / 2; + anim.anchor.set(0.5); + anim.animationSpeed = 0.5; + anim.play(); + + app.stage.addChild(anim); + + // Animate the rotation + app.ticker.add(() => + { + anim.rotation += 0.01; + }); +}); diff --git a/src/examples/v8.0.0-rc/sprite/basic.js b/src/examples/v8.0.0-rc/sprite/basic.js new file mode 100644 index 000000000..2fe2a02ad --- /dev/null +++ b/src/examples/v8.0.0-rc/sprite/basic.js @@ -0,0 +1,26 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +// create a new Sprite from an image path +const bunny = PIXI.Sprite.from('https://pixijs.com/assets/bunny.png'); + +// center the sprite's anchor point +bunny.anchor.set(0.5); + +// move the sprite to the center of the screen +bunny.x = app.screen.width / 2; +bunny.y = app.screen.height / 2; + +app.stage.addChild(bunny); + +// Listen for animate update +app.ticker.add((delta) => +{ + // just for fun, let's rotate mr rabbit a little + // delta is 1 if running at 100% performance + // creates frame-independent transformation + bunny.rotation += 0.1 * delta; +}); diff --git a/src/examples/v8.0.0-rc/sprite/textureSwap.js b/src/examples/v8.0.0-rc/sprite/textureSwap.js new file mode 100644 index 000000000..bc9137bd5 --- /dev/null +++ b/src/examples/v8.0.0-rc/sprite/textureSwap.js @@ -0,0 +1,38 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +let isFlower = true; + +const texture = PIXI.Texture.from('https://pixijs.com/assets/flowerTop.png'); +const secondTexture = PIXI.Texture.from('https://pixijs.com/assets/eggHead.png'); + +// create a new Sprite using the texture +const character = new PIXI.Sprite(texture); + +// center the sprites anchor point +character.anchor.set(0.5); + +// move the sprite to the center of the screen +character.x = app.screen.width / 2; +character.y = app.screen.height / 2; + +app.stage.addChild(character); + +// make the sprite interactive +character.eventMode = 'static'; +character.cursor = 'pointer'; + +character.on('pointertap', () => +{ + isFlower = !isFlower; + // Dynamically swap the texture + character.texture = isFlower ? texture : secondTexture; +}); + +app.ticker.add(() => +{ + character.rotation += 0.02; +}); diff --git a/src/examples/v8.0.0-rc/sprite/tilingSprite.js b/src/examples/v8.0.0-rc/sprite/tilingSprite.js new file mode 100644 index 000000000..3e68c2f42 --- /dev/null +++ b/src/examples/v8.0.0-rc/sprite/tilingSprite.js @@ -0,0 +1,29 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +// create a texture from an image path +const texture = PIXI.Texture.from('https://pixijs.com/assets/p2.jpeg'); + +/* create a tiling sprite ... + * requires a texture, a width and a height + * in WebGL the image size should preferably be a power of two + */ +const tilingSprite = new PIXI.TilingSprite(texture, app.screen.width, app.screen.height); + +app.stage.addChild(tilingSprite); + +let count = 0; + +app.ticker.add(() => +{ + count += 0.005; + + tilingSprite.tileScale.x = 2 + Math.sin(count); + tilingSprite.tileScale.y = 2 + Math.cos(count); + + tilingSprite.tilePosition.x += 1; + tilingSprite.tilePosition.y += 1; +}); diff --git a/src/examples/v8.0.0-rc/sprite/video.js b/src/examples/v8.0.0-rc/sprite/video.js new file mode 100644 index 000000000..30ed43ec0 --- /dev/null +++ b/src/examples/v8.0.0-rc/sprite/video.js @@ -0,0 +1,53 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ backgroundAlpha: 0, resizeTo: window }); + +document.body.appendChild(app.view); + +// Create play button that can be used to trigger the video +const button = new PIXI.Graphics() + .beginFill(0x0, 0.5) + .drawRoundedRect(0, 0, 100, 100, 10) + .endFill() + .beginFill(0xffffff) + .moveTo(36, 30) + .lineTo(36, 70) + .lineTo(70, 50); + +// Position the button +button.x = (app.screen.width - button.width) / 2; +button.y = (app.screen.height - button.height) / 2; + +// Enable interactivity on the button +button.eventMode = 'static'; +button.cursor = 'pointer'; + +// Add to the stage +app.stage.addChild(button); + +// Listen for a click/tap event to start playing the video +// this is useful for some mobile platforms. For example: +// ios9 and under cannot render videos in PIXI without a +// polyfill - https://github.com/bfred-it/iphone-inline-video +// ios10 and above require a click/tap event to render videos +// that contain audio in PIXI. Videos with no audio track do +// not have this requirement +button.on('pointertap', onPlayVideo); + +function onPlayVideo() +{ + // Don't need the button anymore + button.destroy(); + + // create a video texture from a path + const texture = PIXI.Texture.from('https://pixijs.com/assets/video.mp4'); + + // create a new Sprite using the video texture (yes it's that easy) + const videoSprite = new PIXI.Sprite(texture); + + // Stetch the fullscreen + videoSprite.width = app.screen.width; + videoSprite.height = app.screen.height; + + app.stage.addChild(videoSprite); +} diff --git a/src/examples/v8.0.0-rc/text/bitmapText.js b/src/examples/v8.0.0-rc/text/bitmapText.js new file mode 100644 index 000000000..88ab17415 --- /dev/null +++ b/src/examples/v8.0.0-rc/text/bitmapText.js @@ -0,0 +1,19 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +PIXI.Assets.load('https://pixijs.com/assets/bitmap-font/desyrel.xml').then(() => +{ + const bitmapFontText = new PIXI.BitmapText('bitmap fonts are supported!\nWoo yay!', { + fontName: 'Desyrel', + fontSize: 55, + align: 'left', + }); + + bitmapFontText.x = 50; + bitmapFontText.y = 200; + + app.stage.addChild(bitmapFontText); +}); diff --git a/src/examples/v8.0.0-rc/text/fromFont.js b/src/examples/v8.0.0-rc/text/fromFont.js new file mode 100644 index 000000000..067e62051 --- /dev/null +++ b/src/examples/v8.0.0-rc/text/fromFont.js @@ -0,0 +1,29 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +// Load from any font file! +PIXI.Assets.addBundle('fonts', { + ChaChicle: 'https://pixijs.com/assets/webfont-loader/ChaChicle.ttf', + Lineal: 'https://pixijs.com/assets/webfont-loader/Lineal.otf', + 'Dotrice Regular': 'https://pixijs.com/assets/webfont-loader/Dotrice-Regular.woff', + Crosterian: 'https://pixijs.com/assets/webfont-loader/Crosterian.woff2', +}); +PIXI.Assets.loadBundle('fonts').then(() => +{ + const text1 = new PIXI.Text('ChaChicle.ttf', new PIXI.TextStyle({ fontFamily: 'ChaChicle', fontSize: 50 })); + const text2 = new PIXI.Text('Lineal.otf', new PIXI.TextStyle({ fontFamily: 'Lineal', fontSize: 50 })); + const text3 = new PIXI.Text('Dotrice Regular.woff', new PIXI.TextStyle({ fontFamily: 'Dotrice Regular', fontSize: 50 })); + const text4 = new PIXI.Text('Crosterian.woff2', new PIXI.TextStyle({ fontFamily: 'Crosterian', fontSize: 50 })); + + text2.y = 150; + text3.y = 300; + text4.y = 450; + + app.stage.addChild(text1); + app.stage.addChild(text2); + app.stage.addChild(text3); + app.stage.addChild(text4); +}); diff --git a/src/examples/v8.0.0-rc/text/pixiText.js b/src/examples/v8.0.0-rc/text/pixiText.js new file mode 100644 index 000000000..d28f6b4a9 --- /dev/null +++ b/src/examples/v8.0.0-rc/text/pixiText.js @@ -0,0 +1,62 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +const basicText = new PIXI.Text('Basic text in pixi'); + +basicText.x = 50; +basicText.y = 100; + +app.stage.addChild(basicText); + +const style = new PIXI.TextStyle({ + fontFamily: 'Arial', + fontSize: 36, + fontStyle: 'italic', + fontWeight: 'bold', + fill: ['#ffffff', '#00ff99'], // gradient + stroke: '#4a1850', + strokeThickness: 5, + dropShadow: true, + dropShadowColor: '#000000', + dropShadowBlur: 4, + dropShadowAngle: Math.PI / 6, + dropShadowDistance: 6, + wordWrap: true, + wordWrapWidth: 440, + lineJoin: 'round', +}); + +const richText = new PIXI.Text('Rich text with a lot of options and across multiple lines', style); + +richText.x = 50; +richText.y = 220; + +app.stage.addChild(richText); + +const skewStyle = new PIXI.TextStyle({ + fontFamily: 'Arial', + dropShadow: true, + dropShadowAlpha: 0.8, + dropShadowAngle: 2.1, + dropShadowBlur: 4, + dropShadowColor: '0x111111', + dropShadowDistance: 10, + fill: ['#ffffff'], + stroke: '#004620', + fontSize: 60, + fontWeight: 'lighter', + lineJoin: 'round', + strokeThickness: 12, +}); + +const skewText = new PIXI.Text('SKEW IS COOL', skewStyle); + +skewText.skew.set(0.65, -0.3); +skewText.anchor.set(0.5, 0.5); +skewText.x = 300; +skewText.y = 480; + +app.stage.addChild(skewText); diff --git a/src/examples/v8.0.0-rc/text/webFont.js b/src/examples/v8.0.0-rc/text/webFont.js new file mode 100644 index 000000000..be529a431 --- /dev/null +++ b/src/examples/v8.0.0-rc/text/webFont.js @@ -0,0 +1,42 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +// Load them google fonts before starting... +window.WebFontConfig = { + google: { + families: ['Snippet'], + }, + active() + { + init(); + }, +}; + +/* eslint-disable */ +// include the web-font loader script +(function () { + const wf = document.createElement('script'); + wf.src = `${ + document.location.protocol === 'https:' ? 'https' : 'http' + }://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js`; + wf.type = 'text/javascript'; + wf.async = 'true'; + const s = document.getElementsByTagName('script')[0]; + s.parentNode.insertBefore(wf, s); +})(); +/* eslint-enabled */ + +function init() { + // create some white text using the Snippet webfont + const textSample = new PIXI.Text('PixiJS text using the\ncustom "Snippet" Webfont', { + fontFamily: 'Snippet', + fontSize: 50, + fill: 'white', + align: 'left', + }); + textSample.position.set(50, 200); + app.stage.addChild(textSample); +} diff --git a/src/examples/v8.0.0-rc/textures/gradientBasic.js b/src/examples/v8.0.0-rc/textures/gradientBasic.js new file mode 100644 index 000000000..251cab554 --- /dev/null +++ b/src/examples/v8.0.0-rc/textures/gradientBasic.js @@ -0,0 +1,43 @@ +import * as PIXI from 'pixi.js'; + +// This demo uses canvas2d gradient API +// https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createLinearGradient + +const app = new PIXI.Application({ antialias: true, resizeTo: window }); + +document.body.appendChild(app.view); + +function createGradTexture() +{ + // adjust it if somehow you need better quality for very very big images + const quality = 256; + const canvas = document.createElement('canvas'); + + canvas.width = quality; + canvas.height = 1; + + const ctx = canvas.getContext('2d'); + + // use canvas2d API to create gradient + const grd = ctx.createLinearGradient(0, 0, quality, 0); + + grd.addColorStop(0, 'rgba(255, 255, 255, 0.0)'); + grd.addColorStop(0.3, 'cyan'); + grd.addColorStop(0.7, 'red'); + grd.addColorStop(1, 'green'); + + ctx.fillStyle = grd; + ctx.fillRect(0, 0, quality, 1); + + return PIXI.Texture.from(canvas); +} + +const gradTexture = createGradTexture(); + +const sprite = new PIXI.Sprite(gradTexture); + +sprite.position.set(100, 100); +sprite.rotation = Math.PI / 8; +sprite.width = 500; +sprite.height = 50; +app.stage.addChild(sprite); diff --git a/src/examples/v8.0.0-rc/textures/gradientResource.js b/src/examples/v8.0.0-rc/textures/gradientResource.js new file mode 100644 index 000000000..620e85617 --- /dev/null +++ b/src/examples/v8.0.0-rc/textures/gradientResource.js @@ -0,0 +1,72 @@ +import * as PIXI from 'pixi.js'; + +// PixiJS V5 Texture-Resource API + canvas2d gradient API + WebGL texImage2D +// Look here for advanced upload function: +// https://github.com/pixijs/pixi.js/blob/dev/packages/core/src/textures/resources/BaseImageResource.js#L54 + +class GradientResource extends PIXI.Resource +{ + constructor() + { + // pass width and height. (0,0) if we dont know yet + // gradient needs only 1 pixel height + super(256, 1); + } + + upload(renderer, baseTexture, glTexture) + { + const { width } = this; // default size or from baseTexture? + const { height } = this; // your choice. + + // temporary canvas, we dont need it after texture is uploaded to GPU + const canvas = document.createElement('canvas'); + + canvas.width = width; + canvas.height = height; + + const ctx = canvas.getContext('2d'); + + const grd = ctx.createLinearGradient(0, 0, width, 0); + + grd.addColorStop(0, 'rgba(255, 255, 255, 0.0)'); + grd.addColorStop(0.3, 'cyan'); + grd.addColorStop(0.7, 'red'); + grd.addColorStop(1, 'green'); + + ctx.fillStyle = grd; + ctx.fillRect(0, 0, width, height); + + // This info ios usseful if upload happens second time + // Some people use that to track used memory + glTexture.width = width; + glTexture.height = height; + + // PURE WEBGL CALLS - that's what its all about. + // PixiJS cant wrap all that API, we give you acceess to it! + const { gl } = renderer; + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.premultiplyAlpha); + gl.texImage2D(baseTexture.target, 0, baseTexture.format, baseTexture.format, baseTexture.type, canvas); + + return true; + } +} + +const app = new PIXI.Application({ antialias: true, resizeTo: window }); + +document.body.appendChild(app.view); + +const gradBaseTexture = new PIXI.BaseTexture(new GradientResource()); +// Here you can fake baseTexture size to avoid resizing all sprites +// There can be multiple baseTextures per gradient, but be careful: +// resource will spawn more glTextures! + +gradBaseTexture.setSize(500, 50); + +const gradTexture = new PIXI.Texture(gradBaseTexture); + +const sprite = new PIXI.Sprite(gradTexture); + +sprite.position.set(100, 100); +sprite.rotation = Math.PI / 8; +app.stage.addChild(sprite); diff --git a/src/examples/v8.0.0-rc/textures/renderTextureAdvanced.js b/src/examples/v8.0.0-rc/textures/renderTextureAdvanced.js new file mode 100644 index 000000000..e7cdfd4b8 --- /dev/null +++ b/src/examples/v8.0.0-rc/textures/renderTextureAdvanced.js @@ -0,0 +1,96 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +const stageSize = { + width: app.screen.width, + height: app.screen.height, +}; + +// create two render textures... these dynamic textures will be used to draw the scene into itself +let renderTexture = PIXI.RenderTexture.create(stageSize); +let renderTexture2 = PIXI.RenderTexture.create(stageSize); +const currentTexture = renderTexture; + +// create a new sprite that uses the render texture we created above +const outputSprite = new PIXI.Sprite(currentTexture); + +// align the sprite +outputSprite.x = 400; +outputSprite.y = 300; +outputSprite.anchor.set(0.5); + +// add to stage +app.stage.addChild(outputSprite); + +const stuffContainer = new PIXI.Container(); + +stuffContainer.x = 400; +stuffContainer.y = 300; + +app.stage.addChild(stuffContainer); + +// create an array of image ids.. +const fruits = [ + 'https://pixijs.com/assets/rt_object_01.png', + 'https://pixijs.com/assets/rt_object_02.png', + 'https://pixijs.com/assets/rt_object_03.png', + 'https://pixijs.com/assets/rt_object_04.png', + 'https://pixijs.com/assets/rt_object_05.png', + 'https://pixijs.com/assets/rt_object_06.png', + 'https://pixijs.com/assets/rt_object_07.png', + 'https://pixijs.com/assets/rt_object_08.png', +]; + +// create an array of items +const items = []; + +// now create some items and randomly position them in the stuff container +for (let i = 0; i < 20; i++) +{ + const item = PIXI.Sprite.from(fruits[i % fruits.length]); + + item.x = Math.random() * 400 - 200; + item.y = Math.random() * 400 - 200; + item.anchor.set(0.5); + stuffContainer.addChild(item); + items.push(item); +} + +// used for spinning! +let count = 0; + +app.ticker.add(() => +{ + for (let i = 0; i < items.length; i++) + { + // rotate each item + const item = items[i]; + + item.rotation += 0.1; + } + + count += 0.01; + + // swap the buffers ... + const temp = renderTexture; + + renderTexture = renderTexture2; + renderTexture2 = temp; + + // set the new texture + outputSprite.texture = renderTexture; + + // twist this up! + stuffContainer.rotation -= 0.01; + outputSprite.scale.set(1 + Math.sin(count) * 0.2); + + // render the stage to the texture + // the 'true' clears the texture before the content is rendered + app.renderer.render(app.stage, { + renderTexture: renderTexture2, + clear: false, + }); +}); diff --git a/src/examples/v8.0.0-rc/textures/renderTextureBasic.js b/src/examples/v8.0.0-rc/textures/renderTextureBasic.js new file mode 100644 index 000000000..dd55a1e81 --- /dev/null +++ b/src/examples/v8.0.0-rc/textures/renderTextureBasic.js @@ -0,0 +1,48 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ background: '#1099bb', resizeTo: window }); + +document.body.appendChild(app.view); + +const container = new PIXI.Container(); + +app.stage.addChild(container); + +const texture = PIXI.Texture.from('https://pixijs.com/assets/bunny.png'); + +for (let i = 0; i < 25; i++) +{ + const bunny = new PIXI.Sprite(texture); + + bunny.x = (i % 5) * 30; + bunny.y = Math.floor(i / 5) * 30; + bunny.rotation = Math.random() * (Math.PI * 2); + container.addChild(bunny); +} + +const rt = PIXI.RenderTexture.create({ + width: 300, + height: 300, + scaleMode: PIXI.SCALE_MODES.LINEAR, + resolution: 1, +}); + +const sprite = new PIXI.Sprite(rt); + +sprite.x = 450; +sprite.y = 60; +app.stage.addChild(sprite); + +/* + * All the bunnies are added to the container with the addChild method + * when you do this, all the bunnies become children of the container, and when a container moves, + * so do all its children. + * This gives you a lot of flexibility and makes it easier to position elements on the screen + */ +container.x = 100; +container.y = 60; + +app.ticker.add(() => +{ + app.renderer.render(container, { renderTexture: rt }); +}); diff --git a/src/examples/v8.0.0-rc/textures/textureRotate.js b/src/examples/v8.0.0-rc/textures/textureRotate.js new file mode 100644 index 000000000..0c1616906 --- /dev/null +++ b/src/examples/v8.0.0-rc/textures/textureRotate.js @@ -0,0 +1,65 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ resizeTo: window }); + +document.body.appendChild(app.view); + +PIXI.Assets.load('https://pixijs.com/assets/flowerTop.png').then((texture) => +{ + // create rotated textures + const textures = [texture]; + const D8 = PIXI.groupD8; + + for (let rotate = 1; rotate < 16; rotate++) + { + const h = D8.isVertical(rotate) ? texture.frame.width : texture.frame.height; + const w = D8.isVertical(rotate) ? texture.frame.height : texture.frame.width; + + const { frame } = texture; + const crop = new PIXI.Rectangle(texture.frame.x, texture.frame.y, w, h); + const trim = crop; + let rotatedTexture; + + if (rotate % 2 === 0) + { + rotatedTexture = new PIXI.Texture(texture.baseTexture, frame, crop, trim, rotate); + } + else + { + // HACK to avoid exception + // PIXI doesnt like diamond-shaped UVs, because they are different in canvas and webgl + rotatedTexture = new PIXI.Texture(texture.baseTexture, frame, crop, trim, rotate - 1); + rotatedTexture.rotate++; + } + textures.push(rotatedTexture); + } + + const offsetX = (app.screen.width / 16) | 0; + const offsetY = (app.screen.height / 8) | 0; + const gridW = (app.screen.width / 4) | 0; + const gridH = (app.screen.height / 5) | 0; + + // normal rotations and mirrors + for (let i = 0; i < 16; i++) + { + // create a new Sprite using rotated texture + const dude = new PIXI.Sprite(textures[i < 8 ? i * 2 : (i - 8) * 2 + 1]); + + dude.scale.x = 0.5; + dude.scale.y = 0.5; + // show it in grid + dude.x = offsetX + gridW * (i % 4); + dude.y = offsetY + gridH * ((i / 4) | 0); + app.stage.addChild(dude); + const text = new PIXI.Text(`rotate = ${dude.texture.rotate}`, { + fontFamily: 'Courier New', + fontSize: '12px', + fill: 'white', + align: 'left', + }); + + text.x = dude.x; + text.y = dude.y - 20; + app.stage.addChild(text); + } +}); diff --git a/src/tutorials/v8.0.0-rc/gettingStarted/index.ts b/src/tutorials/v8.0.0-rc/gettingStarted/index.ts new file mode 100644 index 000000000..79b2a054a --- /dev/null +++ b/src/tutorials/v8.0.0-rc/gettingStarted/index.ts @@ -0,0 +1,36 @@ +import code1 from '!!raw-loader!./step1-code'; +import code2 from '!!raw-loader!./step2-code'; +import completedCode2 from '!!raw-loader!./step2-completed-code'; +import code3 from '!!raw-loader!./step3-code'; +import completedCode3 from '!!raw-loader!./step3-completed-code'; +import code4 from '!!raw-loader!./step4-code'; +import type { TutorialStep } from '@site/src/tutorials/v7.3.2'; +import content1 from './step1-content.md'; +import content2 from './step2-content.md'; +import content3 from './step3-content.md'; +import content4 from './step4-content.md'; + +export const gettingStartedTutorialSteps: TutorialStep[] = [ + { + header: 'Getting Started', + Content: content1, + code: code1, + }, + { + header: 'Set up something', + Content: content2, + code: code2, + completedCode: completedCode2, + }, + { + header: 'Do something', + Content: content3, + code: code3, + completedCode: completedCode3, + }, + { + header: 'You did it!', + Content: content4, + code: code4, + }, +]; diff --git a/src/tutorials/v8.0.0-rc/gettingStarted/step1-code.js b/src/tutorials/v8.0.0-rc/gettingStarted/step1-code.js new file mode 100644 index 000000000..dce725b33 --- /dev/null +++ b/src/tutorials/v8.0.0-rc/gettingStarted/step1-code.js @@ -0,0 +1,8 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ + background: '#1099bb', + resizeTo: window, +}); + +document.body.appendChild(app.view); diff --git a/src/tutorials/v8.0.0-rc/gettingStarted/step1-content.md b/src/tutorials/v8.0.0-rc/gettingStarted/step1-content.md new file mode 100644 index 000000000..46168e89b --- /dev/null +++ b/src/tutorials/v8.0.0-rc/gettingStarted/step1-content.md @@ -0,0 +1,15 @@ +# Getting Started + +Welcome to the PixiJS tutorial! + +Please go through the tutorial steps at your own pace and challenge yourself using the editor on the right hand side. Here PixiJS has already been included as guided under the [Getting Started](/guides/basics/getting-started#loading-pixijs) section. Let's start with the creation of a PixiJS canvas application and add its view to the DOM. + +```javascript +// Create a PixiJS application of type canvas with specify background color and make it resize to the iframe window +const app = new PIXI.Application() < HTMLCanvasElement > { background: '#1099bb', resizeTo: window }; + +// Adding the application's view to the DOM +document.body.appendChild(app.view); +``` + +When you are ready, proceed to the next exercise using the _Next >_ button below, or feel free to skip to any exercise using the drop-down menu on the top right hand corner of the card. diff --git a/src/tutorials/v8.0.0-rc/gettingStarted/step2-code.js b/src/tutorials/v8.0.0-rc/gettingStarted/step2-code.js new file mode 100644 index 000000000..dce725b33 --- /dev/null +++ b/src/tutorials/v8.0.0-rc/gettingStarted/step2-code.js @@ -0,0 +1,8 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ + background: '#1099bb', + resizeTo: window, +}); + +document.body.appendChild(app.view); diff --git a/src/tutorials/v8.0.0-rc/gettingStarted/step2-completed-code.js b/src/tutorials/v8.0.0-rc/gettingStarted/step2-completed-code.js new file mode 100644 index 000000000..ef428c17d --- /dev/null +++ b/src/tutorials/v8.0.0-rc/gettingStarted/step2-completed-code.js @@ -0,0 +1,21 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ + background: '#1099bb', + resizeTo: window, +}); + +document.body.appendChild(app.view); + +// create a new Sprite from an image path +const bunny = PIXI.Sprite.from('https://pixijs.com/assets/bunny.png'); + +// add to stage +app.stage.addChild(bunny); + +// center the sprite's anchor point +bunny.anchor.set(0.5); + +// move the sprite to the center of the screen +bunny.x = app.screen.width / 2; +bunny.y = app.screen.height / 2; diff --git a/src/tutorials/v8.0.0-rc/gettingStarted/step2-content.md b/src/tutorials/v8.0.0-rc/gettingStarted/step2-content.md new file mode 100644 index 000000000..4e1e4a2cf --- /dev/null +++ b/src/tutorials/v8.0.0-rc/gettingStarted/step2-content.md @@ -0,0 +1,29 @@ +# Creating a Sprite + +So far all we've been doing is prep work. We haven't actually told PixiJS to draw anything. Let's fix that by adding an image to be displayed. + +There are a number of ways to draw images in PixiJS, but the simplest is by using a [Sprite](https://pixijs.download/release/docs/PIXI.Sprite.html). We'll get into the details of how the scene graph works in a later guide, but for now all you need to know is that PixiJS renders a hierarchy of [DisplayObjects](https://pixijs.download/release/docs/PIXI.DisplayObject.html). A Sprite is a type of DisplayObject that wraps a loaded image resource to allow drawing it, scaling it, rotating it, and so forth. + +Before PixiJS can render an image, it needs to be loaded. Just like in any web page, image loading happens asynchronously. We'll talk a lot more about resource loading in later guides. For now, we can use a helper method on the PIXI.Sprite class to handle the image loading for us: + +```JavaScript +// Magically load the PNG asynchronously +const bunny = PIXI.Sprite.from('https://pixijs.com/assets/bunny.png') +``` + +Then we need to add our new sprite to the stage. The stage is simply a [Container](https://pixijs.download/release/docs/PIXI.Container.html) that is the root of the scene graph. Every child of the stage container will be rendered every frame. By adding our sprite to the stage, we tell PixiJS's renderer we want to draw it. + +```JavaScript +app.stage.addChild(bunny) +``` + +Now let's set the Sprite's anchor and position it so that it's bang on at the center. + +```JavaScript +// center the sprite's anchor point +bunny.anchor.set(0.5) + +// move the sprite to the center of the screen +bunny.x = app.screen.width / 2 +bunny.y = app.screen.height / 2 +``` diff --git a/src/tutorials/v8.0.0-rc/gettingStarted/step3-code.js b/src/tutorials/v8.0.0-rc/gettingStarted/step3-code.js new file mode 100644 index 000000000..9be26c31d --- /dev/null +++ b/src/tutorials/v8.0.0-rc/gettingStarted/step3-code.js @@ -0,0 +1,20 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ + background: '#1099bb', + resizeTo: window, +}); + +document.body.appendChild(app.view); + +// create a new Sprite from an image path +const bunny = PIXI.Sprite.from('https://pixijs.com/assets/bunny.png'); + +// center the sprite's anchor point +bunny.anchor.set(0.5); + +// move the sprite to the center of the screen +bunny.x = app.screen.width / 2; +bunny.y = app.screen.height / 2; + +app.stage.addChild(bunny); diff --git a/src/tutorials/v8.0.0-rc/gettingStarted/step3-completed-code.js b/src/tutorials/v8.0.0-rc/gettingStarted/step3-completed-code.js new file mode 100644 index 000000000..945c6ab20 --- /dev/null +++ b/src/tutorials/v8.0.0-rc/gettingStarted/step3-completed-code.js @@ -0,0 +1,29 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ + background: '#1099bb', + resizeTo: window, +}); + +document.body.appendChild(app.view); + +// create a new Sprite from an image path +const bunny = PIXI.Sprite.from('https://pixijs.com/assets/bunny.png'); + +// center the sprite's anchor point +bunny.anchor.set(0.5); + +// move the sprite to the center of the screen +bunny.x = app.screen.width / 2; +bunny.y = app.screen.height / 2; + +app.stage.addChild(bunny); + +// Listen for animate update +app.ticker.add((delta) => +{ + // just for fun, let's rotate mr rabbit a little + // delta is 1 if running at 100% performance + // creates frame-independent transformation + bunny.rotation += 0.1 * delta; +}); diff --git a/src/tutorials/v8.0.0-rc/gettingStarted/step3-content.md b/src/tutorials/v8.0.0-rc/gettingStarted/step3-content.md new file mode 100644 index 000000000..09ae74098 --- /dev/null +++ b/src/tutorials/v8.0.0-rc/gettingStarted/step3-content.md @@ -0,0 +1,15 @@ +# Writing an Update Loop + +While you _can_ use PixiJS for static content, for most projects you'll want to add animation. Our sample app is actually cranking away, rendering the same sprite in the same place multiple times a second. All we have to do to make the image move is to update its attributes once per frame. To do this, we want to hook into the application's _ticker_. A ticker is a PixiJS object that runs one or more callbacks each frame. Doing so is surprisingly easy. Add the following to the end of your script block: + +```javascript +// Listen for animate update +app.ticker.add((delta) => { + // just for fun, let's rotate mr rabbit a little + // delta is 1 if running at 100% performance + // creates frame-independent transformation + bunny.rotation += 0.1 * delta; +}); +``` + +All you need to do is to call `app.ticker.add(...)`, pass it a callback function, and then update your scene in that function. It will get called every frame, and you can move, rotate etc. whatever you'd like to drive your project's animations. diff --git a/src/tutorials/v8.0.0-rc/gettingStarted/step4-code.js b/src/tutorials/v8.0.0-rc/gettingStarted/step4-code.js new file mode 100644 index 000000000..945c6ab20 --- /dev/null +++ b/src/tutorials/v8.0.0-rc/gettingStarted/step4-code.js @@ -0,0 +1,29 @@ +import * as PIXI from 'pixi.js'; + +const app = new PIXI.Application({ + background: '#1099bb', + resizeTo: window, +}); + +document.body.appendChild(app.view); + +// create a new Sprite from an image path +const bunny = PIXI.Sprite.from('https://pixijs.com/assets/bunny.png'); + +// center the sprite's anchor point +bunny.anchor.set(0.5); + +// move the sprite to the center of the screen +bunny.x = app.screen.width / 2; +bunny.y = app.screen.height / 2; + +app.stage.addChild(bunny); + +// Listen for animate update +app.ticker.add((delta) => +{ + // just for fun, let's rotate mr rabbit a little + // delta is 1 if running at 100% performance + // creates frame-independent transformation + bunny.rotation += 0.1 * delta; +}); diff --git a/src/tutorials/v8.0.0-rc/gettingStarted/step4-content.md b/src/tutorials/v8.0.0-rc/gettingStarted/step4-content.md new file mode 100644 index 000000000..f9901c218 --- /dev/null +++ b/src/tutorials/v8.0.0-rc/gettingStarted/step4-content.md @@ -0,0 +1,3 @@ +# You did it! + +Congratulations! Now you are ready for the real world ~ diff --git a/src/tutorials/v8.0.0-rc/index.ts b/src/tutorials/v8.0.0-rc/index.ts new file mode 100644 index 000000000..30959e667 --- /dev/null +++ b/src/tutorials/v8.0.0-rc/index.ts @@ -0,0 +1,26 @@ +import { gettingStartedTutorialSteps } from './gettingStarted'; + +export type TutorialStep = { + header: string; + Content: string; + code: string; + completedCode?: string; +}; + +export type TutorialEntry = { + description: string; + thumbnail?: string; + steps: TutorialStep[]; +}; + +const tutorialsData: Record = { + gettingStarted: { + description: 'Learn the basics of how to use PixiJS.', + steps: gettingStartedTutorialSteps, + }, +}; + +export function getTutorialEntry(key: string) +{ + return tutorialsData[key]; +} diff --git a/src/tutorials/v8.0.0-rc/tutorialsData.json b/src/tutorials/v8.0.0-rc/tutorialsData.json new file mode 100644 index 000000000..5edfac93a --- /dev/null +++ b/src/tutorials/v8.0.0-rc/tutorialsData.json @@ -0,0 +1 @@ +["gettingStarted"] diff --git a/versioned_docs/version-7.3.2/branding.md b/versioned_docs/version-7.3.2/branding.md new file mode 100644 index 000000000..99b8ab8e8 --- /dev/null +++ b/versioned_docs/version-7.3.2/branding.md @@ -0,0 +1,68 @@ +# Branding + +Below are links to assorted PixiJS branding assets usable for including on your site, game, or app. All assets here are free-to-use. If you have any questions or requests, please [file an issue](https://github.com/pixijs/pixijs.com/issues/new). + +## Banner + +This is the banner that is displayed at the top of our [README](https://github.com/pixijs/pixijs/blob/dev/README.md). + +![PixiJS Banner](https://files.pixijs.download/branding/pixijs-banner.png) + +## Logo + +We recommend using the Logo in places where the audience may not be familiar with PixiJS. + +### Logo (Dark) + +Download: [SVG](https://files.pixijs.download/branding/pixijs-logo-full-dark.svg) +[PNG](https://files.pixijs.download/branding/pixijs-logo-full-dark.png) + +![PixiJS Logo Full Dark](https://files.pixijs.download/branding/pixijs-logo-full-dark.png) + +### Logo (Dark, Transparent) + +Download: [SVG](https://files.pixijs.download/branding/pixijs-logo-transparent-dark.svg) +[PNG](https://files.pixijs.download/branding/pixijs-logo-transparent-dark.png) + +![PixiJS Logo Full Dark](https://files.pixijs.download/branding/pixijs-logo-transparent-dark.png) + +### Logo (Pink) + +Download: [SVG](https://files.pixijs.download/branding/pixijs-logo-full-light.svg) +[PNG](https://files.pixijs.download/branding/pixijs-logo-full-light.png) + +![PixiJS Logo Full Light](https://files.pixijs.download/branding/pixijs-logo-full-light.png) + +### Logo (Pink, Transparent) + +Download: [SVG](https://files.pixijs.download/branding/pixijs-logo-transparent-light.svg) +[PNG](https://files.pixijs.download/branding/pixijs-logo-transparent-light.png) + +![PixiJS Logo Full Light](https://files.pixijs.download/branding/pixijs-logo-transparent-light.png) + +## Mark + +We recommend using the Mark in places where the audience is someone familiar with the ecosystem, such as PixiJS Discord users, plugin authors, social media followers. + +### Mark (Pink, Large) + +512px x 512px + +Download: [SVG](https://files.pixijs.download/branding/pixijs-logo.svg) +[PNG](https://files.pixijs.download/branding/pixijs-logo.png) + +![PixiJS Logo Full Dark](https://files.pixijs.download/branding/pixijs-logo.png) + +### Mark (Pink) + +Download: [SVG](https://files.pixijs.download/branding/pixijs-logo-mark-dark.svg) +[PNG](https://files.pixijs.download/branding/pixijs-logo-mark-dark.png) + +![PixiJS Logo Mark Dark](https://files.pixijs.download/branding/pixijs-logo-mark-dark.png) + +### Mark (Light) + +Download: [SVG](https://files.pixijs.download/branding/pixijs-logo-mark-light.svg) +[PNG](https://files.pixijs.download/branding/pixijs-logo-mark-light.png) + +![PixiJS Logo Mark Light](https://files.pixijs.download/branding/pixijs-logo-mark-light.png) diff --git a/versioned_docs/version-7.3.2/examples/index.md b/versioned_docs/version-7.3.2/examples/index.md new file mode 100644 index 000000000..98e22ea4b --- /dev/null +++ b/versioned_docs/version-7.3.2/examples/index.md @@ -0,0 +1,17 @@ +--- +hide_table_of_contents: true +sidebar_position: 0 +--- + +# Examples + +Welcome to the PixiJS Examples page! Here you can find a variety of demos and code snippets to help you get started with PixiJS. + +Check out some of our featured examples below: + +- [Basic Container](./basic/container.md) +- [Blend Modes](./basic/blend-modes.md) +- [Tiling Sprite](./sprite/tiling-sprite.md) +- [Animated Sprite](./sprite/animated-sprite-jet.md) +- [Text](./text/pixi-text.md) +- [Graphics](./graphics/simple.md) diff --git a/versioned_docs/version-7.3.2/faq.md b/versioned_docs/version-7.3.2/faq.md new file mode 100644 index 000000000..01cd259d7 --- /dev/null +++ b/versioned_docs/version-7.3.2/faq.md @@ -0,0 +1,40 @@ +# FAQ + +## What is PixiJS for? + +Everything! Pixi.js is a rendering library that will allow you to create rich, +interactive graphic experiences, cross-platform applications, and games without +having to dive into the WebGL API or grapple with the intricacies of browser and +device compatibility. Killer performance with a clean API, means not only will +your content be better - but also faster to build! + +## Is PixiJS free? + +PixiJS is and always will be free and Open Source. That said, financial contributions +are what make it possible to push PixiJS further, faster. Contributions allow us to +commission the PixiJS developer community to accelerate feature development and create +more in-depth documentation. Support Us by making a contribution via Open Collective. Go on! It will be a massive help AND make you feel good about yourself, win win ;) + +## Where do I get it? + +Visit our GitHub page to download the very latest version of PixiJS. This is the most up-to-date resource for PixiJS and should always be your first port of call to make sure you are using the latest version. Just click the 'Download' link in the navigation. + +## How do I get started? + +Right here! Take a look through the Resources section for a wealth of information including documentation, forums, tutorials and the Goodboy blog. + +## Why should I use PixiJS? + +Because you care about speed. PixiJS' #1 mantra has always been speed. We really do feel the need! We do everything we can to make PixiJS as streamlined, efficient and fast as possible, whilst balancing it with offering as many crucial and valuable features as we can. + +## Is PixiJS a game engine? + +No. PixiJS is what we've come to think of as a "creation engine". Whilst it is extremely good for making games, the core essence of PixiJS is simply moving things around on screens as quickly and efficiently as possible. It does of course happen that it is absolutely brilliant for making games though! + +## Who makes PixiJS? + +Outside of the highly active PixiJS community, it is primarily maintained by Mat Groves, Technical Partner of our creative agency Goodboy Digital. One of the huge advantages of creating PixiJS within the framework of a working agency is that it means its features are always driven by genuine industry demands and critically are always trialled "in anger" in our cutting-edge games, sites and apps. + +## I found a bug. What should I do? + +Two things - lets us know via the PixiJS GitHub community and even better yet, if you know how, post a fix! Our Community is stronger in numbers so we're always keen to welcome new contributors into the team to help us shape what PixiJS becomes next. diff --git a/versioned_docs/version-7.3.2/guides/basics/architecture-overview.md b/versioned_docs/version-7.3.2/guides/basics/architecture-overview.md new file mode 100644 index 000000000..f74a2ceb7 --- /dev/null +++ b/versioned_docs/version-7.3.2/guides/basics/architecture-overview.md @@ -0,0 +1,25 @@ +# Architecture Overview + +OK, now that you've gotten a feel for how easy it is to build a PixiJS application, let's get into the specifics. For the rest of the Basics section, we're going to work from the high level down to the details. We'll start with an overview of how PixiJS is put together. + +## The Code + +Before we get into how the code is layed out, let's talk about where it lives. PixiJS is an open source product hosted on [GitHub](https://github.com/pixijs/pixijs). Like any GitHub repo, you can browse and download the raw source files for each PixiJS class, as well as search existing issues & bugs, and even submit your own. PixiJS is written in a JavaScript variant called [TypeScript](https://www.typescriptlang.org), which enables type-checking in JavaScript via a pre-compile step. + +## The Components + +PixiJS is a modular rendering engine. Each task required for generating, updating and displaying content is broken out into its own component. Not only does this make the code cleaner, it allows for greater extensibility. Additionally, with the use of the [PixiJS Customize tool](https://pixijs.io/customize/), it's possible to build a custom PixiJS file containing only the subset of features your project needs, saving download size. + +Here's a list of the major components that make up PixiJS. Note that this list isn't exhaustive. Additionally, don't worry too much about how each component works. The goal here is to give you a feel for what's under the hood as we start exploring the engine. + +### Major Components + +| Component | Description | +| --- | --- | +| **Renderer** `@pixi/core` | The core of the PixiJS system is the renderer, which displays the scene graph and draws it to the screen. The default renderer for PixiJS is based on WebGL under the hood. | +| **Container** `@pixi/display` | Main display object which creates a scene graph: the tree of renderable objects to be displayed, such as sprites, graphics and text. See [Scene Graph](scene-graph) for more details. | +| **Loader** `@pixi/loader` | The loader system provides tools for asynchronously loading resources such as images and audio files. | +| **Ticker** `@pixi/ticker` | Tickers provide periodic callbacks based on a clock. Your game update logic will generally be run in response to a tick once per frame. You can have multiple tickers in use at one time. | +| **Application** `@pixi/app` | The Application is a simple helper that wraps a Loader, Ticker and Renderer into a single, convenient easy-to-use object. Great for getting started quickly, prototyping and building simple projects. | +| **Interaction** `@pixi/interaction` | PixiJS supports both touch and mouse-based interaction - making objects clickable, firing hover events, etc. | +| **Accessibility** `@pixi/accessibility` | Woven through our display system is a rich set of tools for enabling keyboard and screen-reader accessibility. | diff --git a/versioned_docs/version-7.3.2/guides/basics/getting-started.md b/versioned_docs/version-7.3.2/guides/basics/getting-started.md new file mode 100644 index 000000000..8c84ec24d --- /dev/null +++ b/versioned_docs/version-7.3.2/guides/basics/getting-started.md @@ -0,0 +1,176 @@ +# Getting Started + +In this section we're going to build the simplest possible PixiJS application. In doing so, we'll walk through the basics of how to build and serve the code. + +### Advanced Users + +A quick note before we start: this guide is aimed at beginning PixiJS developers who have minimal +experience developing JavaScript-based applications. If you are a coding veteran, you may find that +the level of detail here is not helpful. If that's the case, you may want to skim this guide, then +jump into [how to work with PixiJS and packers](#TODO) like webpack and npm. + +### A Note About JavaScript + +One final note. The JavaScript universe is currently in transition from old-school JavaScript (ES5) to the newer ES6 flavor: + +```javascript +// ES5 +var x = 5; +setTimeout(function() { alert(x); }, 1000); +// ES6 +const x = 5; +setTimeout(() => alert(x), 1000); +``` + +ES6 brings a number of major advantages in terms of clearer syntax, better variable scoping, native class support, etc. By now, all major browsers support it. Given this, our examples in these guides will use ES6. This doesn't mean you can't use PixiJS with ES5 programs! Just mentally substitute "var" for "let/const", expand the shorter function-passing syntax, and everything will run just fine. + +### Components of a PixiJS Application + +OK! With those notes out of the way, let's get started. There are only a few steps required to write a PixiJS application: + +* Create an HTML file +* Serve the file with a web server +* Load the PixiJS library +* Create an [Application](https://pixijs.download/release/docs/PIXI.Application.html) +* Add the generated view to the DOM +* Add an image to the stage +* Write an update loop + +Let's walk through them together. + +### The HTML File + +PixiJS is a JavaScript library that runs in a web page. So the first thing we're going to need is some HTML in a file. In a real PixiJS application, you might want to embed your display within a complex existing page, or you might want your display area to fill the whole page. For this demo, we'll build an empty page to start: + +```html + + + + + +

Hello PixiJS

+ + +``` + +Create a new folder named `pixi-test`, then copy and paste this HTML into a new file in the `pixi-test` folder named `index.html`. + +### Serving the File + +You will need to run a web server to develop locally with PixiJS. Web browsers prevent loading local files (such as images and audio files) on locally loaded web pages. If you just double-click your new HTML file, you'll get an error when you try to add a sprite to the PixiJS stage. + +Running a web server sounds complex and difficult, but it turns out there are a number of simple web servers that will serve this purpose. For this guide, we're going to be working with [Mongoose](https://mongoose.ws), but you could just as easily use [XAMPP](https://www.apachefriends.org/download.html) or the [http-server Node.js package](https://www.npmjs.com/package/http-server) to serve your files. + +To start serving your page with Mongoose, go to [the Mongoose download page](https://mongoose.ws) and download the free server for your operating system. Mongoose defaults to serving the files in the folder it's run in, so copy the downloaded executable into the folder you created in the prior step (`pixi-test`). Double-click the executable, tell your operating system that you trust the file to run, and you'll have a running web server, serving your new folder. + +Test that everything is working by opening your browser of choice and entering `http://127.0.0.1:8080` in the location bar. (Mongoose by default serves files on port 8080.) You should see "Hello PixiJS" and nothing else. If you get an error at this step, it means you didn't name your file `index.html` or you mis-configured your web server. + +### Loading PixiJS + +OK, so we have a web page, and we're serving it. But it's empty. The next step is to actually load the PixiJS library. If we were building a real application, we'd want to download a target version of PixiJS from the [Pixi Github repo](https://github.com/pixijs/pixijs) so that our version wouldn't change on us. But for this sample application, we'll just use the CDN version of PixiJS. Add this line to the `` section of your `index.html` file: + +```html + +``` + +This will include a *non-minified* version of the latest version of PixiJS when your page loads, ready to be used. We use the non-minified version because we're in development. In production, you'd want to use `pixi.min.js` instead, which is compressed for faster download and excludes assertions and deprecation warnings that can help when building your project, but take longer to download and run. + +### Creating an Application + +Loading the library doesn't do much good if we don't *use* it, so the next step is to start up PixiJS. Start by replacing the line `

Hello PixiJS

` with a script tag like so: + +```html + +``` + +What we're doing here is adding a JavaScript code block, and in that block creating a new PIXI.Application instance. [Application](https://pixijs.download/release/docs/PIXI.Application.html) is a helper class that simplifies working with PixiJS. It creates the renderer, creates the stage, and starts a ticker for updating. In production, you'll almost certainly want to do these steps yourself for added customization and control - we'll cover doing so in a later guide. For now, the Application class is a perfect way to start playing with PixiJS without worrying about the details. + +### Adding the View to the DOM + +When the PIXI.Application class creates the renderer, it builds a Canvas element that it will render *to*. In order to see what we draw with PixiJS, we need to add this Canvas element to the web page's DOM. Append the following line to your page's script block: + +```JavaScript + document.body.appendChild(app.view); +``` + +This takes the view created by the application (the Canvas element) and adds it to the body of your page. + +### Creating a Sprite + +So far all we've been doing is prep work. We haven't actually told PixiJS to draw anything. Let's fix that by adding an image to be displayed. + +There are a number of ways to draw images in PixiJS, but the simplest is by using a [Sprite](https://pixijs.download/release/docs/PIXI.Sprite.html). We'll get into the details of how the scene graph works in a later guide, but for now all you need to know is that PixiJS renders a hierarchy of [DisplayObjects](https://pixijs.download/release/docs/PIXI.DisplayObject.html). A Sprite is a type of DisplayObject that wraps a loaded image resource to allow drawing it, scaling it, rotating it, and so forth. + +Before PixiJS can render an image, it needs to be loaded. Just like in any web page, image loading happens asynchronously. We'll talk a lot more about resource loading in later guides. For now, we can use a helper method on the PIXI.Sprite class to handle the image loading for us: + +```JavaScript + // Magically load the PNG asynchronously + let sprite = PIXI.Sprite.from('sample.png'); +``` + +[Download the sample PNG here](/images/sample.png), and save it into your `pixi-test` directory next to your `index.html`. + +### Adding the Sprite to the Stage + +Finally, we need to add our new sprite to the stage. The stage is simply a [Container](https://pixijs.download/release/docs/PIXI.Container.html) that is the root of the scene graph. Every child of the stage container will be rendered every frame. By adding our sprite to the stage, we tell PixiJS's renderer we want to draw it. + +```JavaScript + app.stage.addChild(sprite); +``` + +### Writing an Update Loop + +While you _can_ use PixiJS for static content, for most projects you'll want to add animation. Our sample app is actually cranking away, rendering the same sprite in the same place multiple times a second. All we have to do to make the image move is to update its attributes once per frame. To do this, we want to hook into the application's _ticker_. A ticker is a PixiJS object that runs one or more callbacks each frame. Doing so is surprisingly easy. Add the following to the end of your script block: + +```javascript + // Add a variable to count up the seconds our demo has been running + let elapsed = 0.0; + // Tell our application's ticker to run a new callback every frame, passing + // in the amount of time that has passed since the last tick + app.ticker.add((delta) => { + // Add the time to our total elapsed time + elapsed += delta; + // Update the sprite's X position based on the cosine of our elapsed time. We divide + // by 50 to slow the animation down a bit... + sprite.x = 100.0 + Math.cos(elapsed/50.0) * 100.0; + }); +``` + +All you need to do is to call `app.ticker.add(...)`, pass it a callback function, and then update your scene in that function. It will get called every frame, and you can move, rotate etc. whatever you'd like to drive your project's animations. + +### Putting It All Together + +That's it! The simplest PixiJS project! + +Here's the whole thing in one place. Check your file and make sure it matches if you're getting errors. + +```html + + + + + + + + + +``` + +Once you have things working, the next thing to do is to read through the rest of the Basics guides to dig into how all this works in much greater depth. diff --git a/versioned_docs/version-7.3.2/guides/basics/render-loop.md b/versioned_docs/version-7.3.2/guides/basics/render-loop.md new file mode 100644 index 000000000..938d4d0b1 --- /dev/null +++ b/versioned_docs/version-7.3.2/guides/basics/render-loop.md @@ -0,0 +1,35 @@ +# Render Loop + +Now that you understand the major parts of the system, let's look at how these parts work together to get your project onto the screen. Unlike a web page, PixiJS is constantly updating and re-drawing itself, over and over. You update your objects, then PixiJS renders them to the screen, then the process repeats. We call this cycle the render loop. + +The majority of any PixiJS project is contained in this update + render cycle. You code the updates, PixiJS handles the rendering. + +Let's walk through what happens each frame of the render loop. There are three main steps. + + + +## Running Ticker Callbacks + +The first step is to calculate how much time has elapsed since the last frame, and then call the Application object's ticker callbacks with that time delta. This allows your project's code to animate and update the sprites, etc. on the stage in preparation for rendering. + +## Updating the Scene Graph + +We'll talk a *lot* more about what a scene graph is and what it's made of in the next guide, but for now, all you need to know is that it contains the things you're drawing - sprites, text, etc. - and that these objects are in a tree-like hierarchy. After you've updated your game objects by moving, rotating and so forth, PixiJS needs to calculate the new positions and state of every object in the scene, before it can start drawing. + + + +## Rendering the Scene Graph + +Now that our game's state has been updated, it's time to draw it to the screen. The rendering system starts with the root of the scene graph (`app.stage`), and starts rendering each object and its children, until all objects have been drawn. No culling or other cleverness is built into this process. If you have lots of objects outside of the visible portion of the stage, you'll want to investigate disabling them as an optimization. + +## Frame Rates + +A note about frame rates. The render loop can't be run infinitely fast - drawing things to the screen takes time. In addition, it's not generally useful to have a frame updated more than once per screen update (commonly 60fps, but newer monitors can support 144fps and up). Finally, PixiJS runs in the context of a web browser like Chrome or Firefox. The browser itself has to balance the needs of various internal operations with servicing any open tabs. All this to say, determining when to draw a frame is a complex issue. + + + +In cases where you want to adjust that behavior, you can set the `minFPS` and `maxFPS` attributes on a Ticker to give PixiJS hints as to the range of tick speeds you want to support. Just be aware that due to the complex environment, your project cannot _guarantee_ a given FPS. Use the passed `delta` value in your ticker callbacks to scale any animations to ensure smooth playback. + +## Custom Render Loops + +What we've just covered is the default render loop provided out of the box by the Application helper class. There are many other ways of creating a render loop that may be helpful for advanced users looking to solve a given problem. While you're prototyping and learning PixiJS, sticking with the Application's provided system is the recommended approach. diff --git a/versioned_docs/version-7.3.2/guides/basics/scene-graph.md b/versioned_docs/version-7.3.2/guides/basics/scene-graph.md new file mode 100644 index 000000000..9e4370353 --- /dev/null +++ b/versioned_docs/version-7.3.2/guides/basics/scene-graph.md @@ -0,0 +1,152 @@ +# Scene Graph + +Every frame, PixiJS is updating and then rendering the scene graph. Let's talk about what's in the scene graph, and how it impacts how you develop your project. If you've built games before, this should all sound very familiar, but if you're coming from HTML and the DOM, it's worth understanding before we get into specific types of objects you can render. + +## The Scene Graph Is a Tree + +The scene graph's root node is a container maintained by the application, and referenced with `app.stage`. When you add a sprite or other renderable object as a child to the stage, it's added to the scene graph and will be rendered and interactable. Most PixiJS objects can also have children, and so as you build more complex scenes, you will end up with a tree of parent-child relationships, rooted at the app's stage. + +(A helpful tool for exploring your project is the [Pixi.js devtools plugin](https://chrome.google.com/webstore/detail/pixijs-devtools/aamddddknhcagpehecnhphigffljadon) for Chrome, which allows you to view and manipulate the scene graph in real time as it's running!) + +## Parents and Children + +When a parent moves, its children move as well. When a parent is rotated, its children are rotated too. Hide a parent, and the children will also be hidden. If you have a game object that's made up of multiple sprites, you can collect them under a container to treat them as a single object in the world, moving and rotating as one. + + + +Each frame, PixiJS runs through the scene graph from the root down through all the children to the leaves to calculate each object's final position, rotation, visibility, transparency, etc. If a parent's alpha is set to 0.5 (making it 50% transparent), all its children will start at 50% transparent as well. If a child is then set to 0.5 alpha, it won't be 50% transparent, it will be 0.5 x 0.5 = 0.25 alpha, or 75% transparent. Similarly, an object's position is relative to its parent, so if a parent is set to an x position of 50 pixels, and the child is set to an x position of 100 pixels, it will be drawn at a screen offset of 150 pixels, or 50 + 100. + +Here's an example. We'll create three sprites, each a child of the last, and animate their position, rotation, scale and alpha. Even though each sprite's properties are set to the same values, the parent-child chain amplifies each change: + +```javascript +// Create the application helper and add its render target to the page +const app = new PIXI.Application({ width: 640, height: 360 }); +document.body.appendChild(app.view); + +// Add a container to center our sprite stack on the page +const container = new PIXI.Container(); +container.x = app.screen.width / 2; +container.y = app.screen.height / 2; +app.stage.addChild(container); + +// Create the 3 sprites, each a child of the last +const sprites = []; +let parent = container; +for (let i = 0; i < 3; i++) { + let sprite = PIXI.Sprite.from('assets/images/sample.png'); + sprite.anchor.set(0.5); + parent.addChild(sprite); + sprites.push(sprite); + parent = sprite; +} + +// Set all sprite's properties to the same value, animated over time +let elapsed = 0.0; +app.ticker.add((delta) => { + elapsed += delta / 60; + const amount = Math.sin(elapsed); + const scale = 1.0 + 0.25 * amount; + const alpha = 0.75 + 0.25 * amount; + const angle = 40 * amount; + const x = 75 * amount; + for (let i = 0; i < sprites.length; i++) { + const sprite = sprites[i]; + sprite.scale.set(scale); + sprite.alpha = alpha; + sprite.angle = angle; + sprite.x = x; + } +}); +``` + +The cumulative translation, rotation, scale and skew of any given node in the scene graph is stored in the object's `worldTransform` property. Similarly, the cumulative alpha value is stored in the `worldAlpha` property. + +## Render Order + +So we have a tree of things to draw. Who gets drawn first? + +PixiJS renders the tree from the root down. At each level, the current object is rendered, then each child is rendered in order of insertion. So the second child is rendered on top of the first child, and the third over the second. + +Check out this example, with two parent objects A & D, and two children B & C under A: + +```javascript +// Create the application helper and add its render target to the page +const app = new PIXI.Application({ width: 640, height: 360 }); +document.body.appendChild(app.view); + +// Label showing scene graph hierarchy +const label = new PIXI.Text('Scene Graph:\n\napp.stage\n ┗ A\n ┗ B\n ┗ C\n ┗ D', {fill: '#ffffff'}); +label.position = {x: 300, y: 100}; +app.stage.addChild(label); + +// Helper function to create a block of color with a letter +const letters = []; +function addLetter(letter, parent, color, pos) { + const bg = new PIXI.Sprite(PIXI.Texture.WHITE); + bg.width = 100; + bg.height = 100; + bg.tint = color; + + const text = new PIXI.Text(letter, {fill: "#ffffff"}); + text.anchor.set(0.5); + text.position = {x: 50, y: 50}; + + const container = new PIXI.Container(); + container.position = pos; + container.visible = false; + container.addChild(bg, text); + parent.addChild(container); + + letters.push(container); + return container; +} + +// Define 4 letters +let a = addLetter('A', app.stage, 0xff0000, {x: 100, y: 100}); +let b = addLetter('B', a, 0x00ff00, {x: 20, y: 20}); +let c = addLetter('C', a, 0x0000ff, {x: 20, y: 40}); +let d = addLetter('D', app.stage, 0xff8800, {x: 140, y: 100}); + +// Display them over time, in order +let elapsed = 0.0; +app.ticker.add((delta) => { + elapsed += delta / 60.0; + if (elapsed >= letters.length) { elapsed = 0.0; } + for (let i = 0; i < letters.length; i ++) { + letters[i].visible = elapsed >= i; + } +}); +``` + +If you'd like to re-order a child object, you can use `setChildIndex()`. To add a child at a given point in a parent's list, use `addChildAt()`. Finally, you can enable automatic sorting of an object's children using the `sortableChildren` option combined with setting the `zIndex` property on each child. + +## Culling + +If you're building a project where a large proportion of your DisplayObject's are off-screen (say, a side-scrolling game), you will want to *cull* those objects. Culling is the process of evaluating if an object (or its children!) is on the screen, and if not, turning off rendering for it. If you don't cull off-screen objects, the renderer will still draw them, even though none of their pixels end up on the screen. + +PixiJS doesn't provide built-in support for viewport culling, but you can find 3rd party plugins that might fit your needs. Alternately, if you'd like to build your own culling system, simply run your objects during each tick and set `renderable` to false on any object that doesn't need to be drawn. + +## Local vs Global Coordinates + +If you add a sprite to the stage, by default it will show up in the top left corner of the screen. That's the origin of the global coordinate space used by PixiJS. If all your objects were children of the stage, that's the only coordinates you'd need to worry about. But once you introduce containers and children, things get more complicated. A child object at [50, 100] is 50 pixels right and 100 pixels down *from its parent*. + +We call these two coordinate systems "global" and "local" coordinates. When you use `position.set(x, y)` on an object, you're always working in local coordinates, relative to the object's parent. + +The problem is, there are many times when you want to know the global position of an object. For example, if you want to cull offscreen objects to save render time, you need to know if a given child is outside the view rectangle. + +To convert from local to global coordinates, you use the `toGlobal()` function. Here's a sample usage: + +```javascript +// Get the global position of an object, relative to the top-left of the screen +let globalPos = obj.toGlobal(new PIXI.Point(0,0)); +``` + +This snippet will set `globalPos` to be the global coordinates for the child object, relative to [0, 0] in the global coordinate system. + +## Global vs Screen Coordinates + +When your project is working with the host operating system or browser, there is a third coordinate system that comes into play - "screen" coordinates (aka "viewport" coordinates). Screen coordinates represent position relative to the top-left of the canvas element that PixiJS is rendering into. Things like the DOM and native mouse click events work in screen space. + +Now, in many cases, screen space is equivalent to world space. This is the case if the size of the canvas is the same as the size of the render view specified when you create you PIXI.Application. By default, this will be the case - you'll create for example an 800x600 application window and add it to your HTML page, and it will stay that size. 100 pixels in world coordinates will equal 100 pixels in screen space. BUT! It is common to stretch the rendered view to have it fill the screen, or to render at a lower resolution and up-scale for speed. In that case, the screen size of the canvas element will change (e.g. via CSS), but the underlying render view will *not*, resulting in a mis-match between world coordinates and screen coordinates. + + diff --git a/versioned_docs/version-7.3.2/guides/basics/what-pixijs-is-not.md b/versioned_docs/version-7.3.2/guides/basics/what-pixijs-is-not.md new file mode 100644 index 000000000..980435b39 --- /dev/null +++ b/versioned_docs/version-7.3.2/guides/basics/what-pixijs-is-not.md @@ -0,0 +1,39 @@ +# What PixiJS Is Not + +While PixiJS can do many things, there are things it can't do, or that require additional tools to accomplish. Newcomers to PixiJS often struggle to identify which tasks PixiJS can solve, and which require outside solutions. If you're about to start a project, it can be helpful to know if PixiJS is a good fit for your needs. The following list is obviously incomplete - PixiJS is also not, for example, a duck - but it includes many common tasks or features that you might expect us to support. + +## PixiJS Is Not ... A Framework + +PixiJS is a rendering engine, and it supports additional features such as interaction management that are commonly needed when using a render engine. But it is not a framework like Unity or Phaser. Frameworks are designed to do all the things you'd need to do when building a game - user settings management, music playback, object scripting, art pipeline management... the list goes on. PixiJS is designed to do one thing really well - render graphical content. This lets us focus on keeping up with new technology, and makes downloading PixiJS blazingly fast. + +## ... A 3D Renderer + +PixiJS is built for 2D. Platformers, adventure games, interactive ads, custom data visualization... all good. But if you want to render 3D models, you might want to check out [babylon.js](https://www.babylonjs.com) or [three.js](https://threejs.org). + +## ... A Mobile App + +If you're looking to build mobile games, you can do it with PixiJS, but you'll need to use a deployment system like [Apache Cordova](https://cordova.apache.org) if you want access to native bindings. We don't provide access to the camera, location services, notifications, etc. + +## ... A UI Library + +Building a truly generic UI system is a huge challenge, as anyone who has worked with Unity's UI tools can attest. We've chosen to avoid the complexity to stay true to our core focus on speed. While you can certainly build your own UI using PixiJS's scene graph and interaction manager, we don't ship with a UI library out of the box. + +## ... A Data Store + +There are many techniques and technologies that you can use to store settings, scores, and other data. Cookies, Web Storage, server-based storage... there are many solutions, each with advantages and disadvantages. You can use any of them with PixiJS, but we don't provide tools to do so. + +## ... An Audio Library + +At least, not out of the box. Again, web audio technology is a constantly evolving challenge, with constantly changing rules and requirements across many browsers. There are a number of dedicated web audio libraries (such as [Howler.js](https://howlerjs.com) that can be used with PixiJS to play sound effects and music. Alternatively, the [PixiJS Sound plugin](https://github.com/pixijs/pixi-sound) is designed to work well with PixiJS. + +## ... A Development Environment + +There are a number of tools that are useful for building 2D art and games that you might expect to be a part of PixiJS, but we're a rendering engine, not a development environment. Packing sprite sheets, processing images, building mipmaps or Retina-ready sprites - there are great standalone tools for this type of tooling. Where appropriate throughout the guides, we'll point you to tools that may be useful. + +## So Is PixiJS Right For Me? + +Only you know! If you're looking for a tightly focused, fast and efficient rendering engine for your next web-based project, PixiJS is likely a great fit. + +If you need a full game development framework, with native bindings and a rich UI library, you may want to explore other options. + +Or you may not. It can be faster and easier to build just the subset of a full framework that your project needs than it can be to digest a monolithic API with bells and whistles you don't need. There are hundreds of complex, rich games and visual projects that use PixiJS for rendering, with plugins or custom code to add the UI and sound effects. There are benefits to both approaches. Regardless, we hope you have a better feel for what PixiJS can (and cannot!) offer your project. diff --git a/versioned_docs/version-7.3.2/guides/basics/what-pixijs-is.md b/versioned_docs/version-7.3.2/guides/basics/what-pixijs-is.md new file mode 100644 index 000000000..a11c20d51 --- /dev/null +++ b/versioned_docs/version-7.3.2/guides/basics/what-pixijs-is.md @@ -0,0 +1,31 @@ +# What PixiJS Is + +So what exactly *is* PixiJS? At its heart, PixiJS is a rendering system that uses WebGL (or optionally Canvas) to display images and other 2D visual content. It provides a full scene graph (a hierarchy of objects to render), and provides interaction support to enable handling click and touch events. It is a natural replacement for Flash in the modern HTML5 world, but provides better performance and pixel-level effects that go beyond what Flash could achieve. It is perfect for online games, educational content, interactive ads, data visualization... any web-based application where complex graphics are important. And coupled with technology such as Cordova and Electron, PixiJS apps can be distributed beyond the browser as mobile and desktop applications. + + + +Here's what else you get with PixiJS: + +## PixiJS Is ... Fast + +One of the major features that distinguishes PixiJS from other web-based rendering solutions is *speed*. From the ground up, the render pipeline has been built to get the most performance possible out of your users' browsers. Automatic sprite and geometry batching, careful use of WebGL resources, a tight scene graph - no matter your application, speed is valuable, and PixiJS has it to spare. + +## ... More Than Just Sprites + +Drawing images on a page can be handled with HTML5 and the DOM, so why use PixiJS? Beyond performance, the answer is that PixiJS goes well beyond simple images. Draw trails and tracks with [SimpleRope](https://pixijs.download/release/docs/PIXI.SimpleRope.html). Draw polygons, lines, circles and other primitives with [Graphics](https://pixijs.download/release/docs/PIXI.Graphics.html). [Text](https://pixijs.download/release/docs/PIXI.Text.html) provides full text rendering support that's just as performant as sprites. And even when drawing simple images, PixiJS natively supports spritesheets for efficient loading and ease of development. + +## ... WebGL Native + +WebGL is the JavaScript API for accessing users' GPUs for fast rendering and advanced effects. PixiJS leverages WebGL to display thousands of moving sprites efficiently even on mobile devices. But using WebGL offers more than just speed. By using the [Filter](https://pixijs.download/release/docs/PIXI.Filter.html) class, you can write shader programs (or use pre-built ones!) to achieve displacement maps, blurring, and other advanced visual effects that cannot be accomplished with just the DOM or Canvas APIs. + +## ... Open Source + +Want to understand how the engine works? Trying to track down a bug? Been burned by closed-source projects going dark? With PixiJS, you get a mature project with full source code access. We're MIT licensed for compatibility, and [hosted on GitHub](https://github.com/pixijs/pixijs) for issue tracking and ease of access. + +## ... Extensible + +Open source helps. So does being based on JavaScript. But the real reason PixiJS is easy to extend is the clean internal API that underlies every part of the system. After years of development and 5 major releases, PixiJS is ready to make your project a success, no matter what your needs. + +## ... Easy to Deploy + +Flash required the player. Unity requires an installer or app store. PixiJS requires... a browser. Deploying PixiJS on the web is exactly like deploying a web site. That's all it is - JavaScript + images + audio, like you've done a hundred times. Your users simply visit a URL, and your game or other content is ready to run. But it doesn't stop at the web. If you want to deploy a mobile app, wrap your PixiJS code in Cordova. Want to deploy a standalone desktop program? Build an Electron wrapper, and you're ready to rock. diff --git a/versioned_docs/version-7.3.2/guides/components/assets.md b/versioned_docs/version-7.3.2/guides/components/assets.md new file mode 100644 index 000000000..ecd24388d --- /dev/null +++ b/versioned_docs/version-7.3.2/guides/components/assets.md @@ -0,0 +1,161 @@ +# Assets +## The Assets package + +The Assets package is a modern replacement for the old `PIXI.Loader` class. It is a promise-based resource management solution that will download, cache and parse your assets into something you can use. The downloads can be simultaneous and in the background, meaning faster startup times for your app, the cache ensures that you never download the same asset twice and the extensible parser system allows you to easily extend and customize the process to your needs. + + +## Getting started + +The `@pixi/assets` package doesn't come bundled with PixiJS in version 6.x and must be added externally, however it will become integrated with version 7. The class that does all the heavy lifting is called `AssetsClass` but you don't need to create your own instance since you will find one ready to use in `PIXI.Assets`. +This package relies heavily on JavaScript Promises that all modern browsers support, however, if your target browser [doesn't support promises](https://caniuse.com/promises) you should look into [polyfilling them](https://github.com/zloirock/core-js#ecmascript-promise). + +## Making our first Assets Promise +To quickly use the `PIXI.Assets` instance, you just need to call `PIXI.Assets.load` and pass in an asset. This will return a promise that when resolved will yield the value you seek. +In this example, we will load a texture and then turn it into a sprite. + +
+ +One very important thing to keep in mind while using `Assets` is that all requests are cached and if the URL is the same, the promise returned will also be the same. +To show it in code: +```js +promise1 = PIXI.Assets.load('bunny.png') +promise2 = PIXI.Assets.load('bunny.png') + +//promise1 === promise2 +``` + +Out of the box, the following assets types can be loaded without the need for external plugins: + +- Textures (`avif`, `webp`, `png`, `jpg`, `gif`) +- Sprite sheets (`json`) +- Bitmap fonts (`xml`, `fnt`, `txt`) +- Web fonts (`ttf`, `woff`, `woff2`) +- Json files (`json`) +- Text files (`txt`) + +More types can be added fairly easily by creating additional loader parsers. + +## Warning about solved promises + +When an asset is downloaded, it is cached as a promise inside the `Assets` instance and if you try to download it again you will get a reference to the already resolved promise. +However promise handlers `.then(...)`/`.catch(...)`/`.finally(...)` are always asynchronous, this means that even if a promise was already resolved the code below the `.then(...)`/`.catch(...)`/`.finally(...)` will execute before the code inside them. +See this example: + +```js +console.log(1); +alreadyResolvedPromise.then(() => console.log(2)); +console.log(3); + +// Console output: +// 1 +// 3 +// 2 +``` + +To learn more about why this happens you will need to learn about [Microtasks](https://javascript.info/microtask-queue), however, using async functions should mitigate this problem. + + +## Using Async/Await + +There is a way to work with promises that is more intuitive and easier to read: `async`/`await`. + +To use it we first need to create a function/method and mark it as `async`. + +```js +async function test() { + // ... +} +``` + +This function now wraps the return value in a promise and allows us to use the `await` keyword before a promise to halt the execution of the code until it is resolved and gives us the value. + +See this example: + +
+ +The `texture` variable now is not a promise but the resolved texture that resulted after waiting for this promise to resolve. + +```js +const texture = await PIXI.Assets.load('examples/assets/bunny.png'); +``` + +This allows us to write more readable code without falling into callback hell and to better think when our program halts and yields. + +## Loading multiple assets + +We can add assets to the cache and then load them all simultaneously by using `PIXI.Assets.add(...)` and then calling `PIXI.Assets.load(...)` with all the keys you want to have loaded. +See the following example: + +
+ +However, if you want to take full advantage of `@pixi/Assets` you should use bundles. +Bundles are just a way to group assets together and can be added manually by calling `PIXI.Assets.addBundle(...)`/`PIXI.Assets.loadBundle(...)`. + +```js + PIXI.Assets.addBundle('animals', { + bunny: 'bunny.png', + chicken: 'chicken.png', + thumper: 'thumper.png', + }); + + const assets = await PIXI.Assets.loadBundle('animals'); +``` + +However, the best way to handle bundles is to use a manifest and call `PIXI.Assets.init({manifest})` with said manifest (or even better, an URL pointing to it). +Splitting our assets into bundles that correspond to screens or stages of our app will come in handy for loading in the background while the user is using the app instead of locking them in a single monolithic loading screen. + +```json +{ + "bundles":[ + { + "name":"load-screen", + "assets":[ + { + "name":"background", + "srcs":"sunset.png" + }, + { + "name":"bar", + "srcs":"load-bar.{png,webp}" + } + ] + }, + { + "name":"game-screen", + "assets":[ + { + "name":"character", + "srcs":"robot.png" + }, + { + "name":"enemy", + "srcs":"bad-guy.png" + } + ] + } + ] +} +``` +```js +PIXI.Assets.init({manifest: "path/manifest.json"}); +``` + +Beware that **you can only call `init` once**. + +Remember there is no downside in repeating URLs since they will all be cached, so if you need the same asset in two bundles you can duplicate the request without any extra cost! + +## Background loading + +The old approach to loading was to use `PIXI.Loader` to load all your assets at the beginning of your app, but users are less patient now and want content to be instantly available so the practices are moving towards loading the bare minimum needed to show the user some content and, while they are interacting with that, we keep loading the following content in the background. + +Luckily, `@pixi/assets` has us covered with a system that allows us to load everything in the background and in case we need some assets right now, bump them to the top of the queue so we can minimize loading times. + +To achieve this, we have the methods `PIXI.Assets.backgroundLoad(...)` and `PIXI.Assets.backgroundLoadBundle(...)` that will passively begin to load these assets in the background. So when you finally come to loading them you will get a promise that resolves to the loaded assets immediately. + +When you finally need the assets to show, you call the usual `PIXI.Assets.load(...)` or `PIXI.Assets.loadBundle(...)` and you will get the corresponding promise. + +The best way to do this is using bundles, see the following example: + +
+ +We create one bundle for each screen our game will have and set them all to start downloading at the beginning of our app. If the user progresses slowly enough in our app then they should never get to see a loading screen after the first one! diff --git a/versioned_docs/version-7.3.2/guides/components/containers.md b/versioned_docs/version-7.3.2/guides/components/containers.md new file mode 100644 index 000000000..c4bd5de39 --- /dev/null +++ b/versioned_docs/version-7.3.2/guides/components/containers.md @@ -0,0 +1,96 @@ +# Containers + +The [Container](https://pixijs.download/release/docs/PIXI.Container.html) class provides a simple display object that does what its name implies - collect a set of child objects together. But beyond grouping objects, containers have a few uses that you should be aware of. + +## Containers as Groups + +Almost every type of display object is also derived from Container - even Sprites! This means that in many cases you can create a parent-child hierarchy with the objects you want to render. + +However, it's a good idea _not_ to do this. Standalone Container objects are **very** cheap to render, and having a proper hierarchy of Container objects, each containing one or more renderable objects, provides flexibility in rendering order. It also future-proofs your code, as when you need to add an additional object to a branch of the tree, your animation logic doesn't need to change - just drop the new object into the proper Container, and your logic moves the Container with no changes to your code. + +So that's the primary use for Containers - as groups of renderable objects in a hierarchy. + +Check out the [container example code](/examples/basic/container). + +## Masking + +Another common use for Container objects is as hosts for masked content. "Masking" is a technique where parts of your scene graph are only visible within a given area. + +Think of a pop-up window. It has a frame made of one or more Sprites, then has a scrollable content area that hides content outside the frame. A Container plus a mask makes that scrollable area easy to implement. Add the Container, set its `mask` property to a Graphics object with a rect, and add the text, image, etc. content you want to display as children of that masked Container. Any content that extends beyond the rectangular mask will simply not be drawn. Move the contents of the Container to scroll as desired. + +```javascript +// Create the application helper and add its render target to the page +let app = new PIXI.Application({ width: 640, height: 360 }); +document.body.appendChild(app.view); + +// Create window frame +let frame = new PIXI.Graphics(); +frame.beginFill(0x666666); +frame.lineStyle({ color: 0xffffff, width: 4, alignment: 0 }); +frame.drawRect(0, 0, 208, 208); +frame.position.set(320 - 104, 180 - 104); +app.stage.addChild(frame); + +// Create a graphics object to define our mask +let mask = new PIXI.Graphics(); +// Add the rectangular area to show +mask.beginFill(0xffffff); +mask.drawRect(0,0,200,200); +mask.endFill(); + +// Add container that will hold our masked content +let maskContainer = new PIXI.Container(); +// Set the mask to use our graphics object from above +maskContainer.mask = mask; +// Add the mask as a child, so that the mask is positioned relative to its parent +maskContainer.addChild(mask); +// Offset by the window's frame width +maskContainer.position.set(4,4); +// And add the container to the window! +frame.addChild(maskContainer); + +// Create contents for the masked container +let text = new PIXI.Text( + 'This text will scroll up and be masked, so you can see how masking works. Lorem ipsum and all that.\n\n' + + 'You can put anything in the container and it will be masked!', + { + fontSize: 24, + fill: 0x1010ff, + wordWrap: true, + wordWrapWidth: 180 + } +); +text.x = 10; +maskContainer.addChild(text); + +// Add a ticker callback to scroll the text up and down +let elapsed = 0.0; +app.ticker.add((delta) => { + // Update the text's y coordinate to scroll it + elapsed += delta; + text.y = 10 + -100.0 + Math.cos(elapsed/50.0) * 100.0; +}); +``` + +There are two types of masks supported by PixiJS: + +Use a [Graphics](https://pixijs.download/release/docs/PIXI.Graphics.html) object to create a mask with an arbitrary shape - powerful, but doesn't support anti-aliasing + +Sprite: Use the alpha channel from a [Sprite](https://pixijs.download/release/docs/PIXI.Sprite.html) as your mask, providing anti-aliased edging - _not_ supported on the Canvas renderer + +## Filtering + +Another common use for Container objects is as hosts for filtered content. Filters are an advanced, WebGL-only feature that allows PixiJS to perform per-pixel effects like blurring and displacements. By setting a filter on a Container, the area of the screen the Container encompasses will be processed by the filter after the Container's contents have been rendered. + +Below are list of filters available by default in PixiJS. There is, however, a community repository with [many more filters](https://github.com/pixijs/filters). + +| Filter | Description | +| --- | --- | +| AlphaFilter: `@pixi/filter-alpha` | Similar to setting `alpha` property, but flattens the Container instead of applying to children individually. | +| BlurFilter: `@pixi/filter-blur` | Apply a blur effect | +| ColorMatrixFilter: `@pixi/filter-color-matrix` | A color matrix is a flexible way to apply more complex tints or color transforms (e.g., sepia tone). | +| DisplacementFilter: `@pixi/filter-displacement` | Displacement maps create visual offset pixels, for instance creating a wavy water effect. | +| FXAAFilter: `@pixi/filter-fxaa` | Basic FXAA (Fast Approximate Anti-Aliasing) to create smoothing effect. | +| NoiseFilter: `@pixi/filter-noise` | Create random noise (e.g., grain effect). | + +_**Important:** Filters should be use somewhat sparingly. They can slow performance and increase memory if used too often in a scene._ diff --git a/versioned_docs/version-7.3.2/guides/components/display-object.md b/versioned_docs/version-7.3.2/guides/components/display-object.md new file mode 100644 index 000000000..dd2b90d7b --- /dev/null +++ b/versioned_docs/version-7.3.2/guides/components/display-object.md @@ -0,0 +1,21 @@ +# Display Objects + +[DisplayObject](https://pixijs.download/release/docs/PIXI.DisplayObject.html) is the core class for anything that can be rendered by the engine. It's the base class for sprites, text, complex graphics, containers, etc., and provides much of the common functionality for those objects. As you're learning PixiJS, it's important to [read through the documentation for this class](https://pixijs.download/release/docs/PIXI.DisplayObject.html) to understand how to move, scale, rotate and compose the visual elements of your project. + +Be aware that you won't use DisplayObject directly - you'll use its functions and attributes in derived classes. + +## Commonly Used Attributes + +The most common attributes you'll use when laying out and animating content in PixiJS are provided by the DisplayObject class: + +| Property | Description | +| --- | --- | +| **position** | X- and Y-position are given in pixels and change the position of the object relative to its parent, also available directly as `object.x` / `object.y` | +| **rotation** | Rotation is specified in radians, and turns an object clockwise (0.0 - 2 * Math.PI) | +| **angle** | Angle is an alias for rotation that is specified in degrees instead of radians (0.0 - 360.0) | +| **pivot** | Point the object rotates around, in pixels - also sets origin for child objects | +| **alpha** | Opacity from 0.0 (fully transparent) to 1.0 (fully opaque), inherited by children | +| **scale** | Scale is specified as a percent with 1.0 being 100% or actual-size, and can be set independently for the x and y axis | +| **skew** | Skew transforms the object in x and y similar to the CSS skew() function, and is specified in radians | +| **visible** | Whether the object is visible or not, as a boolean value - prevents updating and rendering object and children | +| **renderable** | Whether the object should be rendered - when `false`, object will still be updated, but won't be rendered, doesn't affect children | diff --git a/versioned_docs/version-7.3.2/guides/components/graphics.md b/versioned_docs/version-7.3.2/guides/components/graphics.md new file mode 100644 index 000000000..5c1e0c73b --- /dev/null +++ b/versioned_docs/version-7.3.2/guides/components/graphics.md @@ -0,0 +1,104 @@ +# Graphics + +[Graphics](https://pixijs.download/release/docs/PIXI.Graphics.html) is a complex and much misunderstood tool in the PixiJS toolbox. At first glance, it looks like a tool for drawing shapes. And it is! But it can also be used to generate masks. How does that work? + +In this guide, we're going to de-mystify the Graphics object, starting with how to think about what it does. + +Check out the [graphics example code](/examples/graphics/simple). + +## Graphics Is About Building - Not Drawing + +First-time users of the PIXI.Graphics class often struggle with how it works. Let's look at an example snippet that creates a Graphics object and draws a rectangle: + +```javascript +// Create a Graphics object, set a fill color, draw a rectangle +let obj = new PIXI.Graphics(); +obj.beginFill(0xff0000); +obj.drawRect(0, 0, 200, 100); + +// Add it to the stage to render +app.stage.addChild(obj); +``` + +That code will work - you'll end up with a red rectangle on the screen. But it's pretty confusing when you start to think about it. Why am I drawing a rectangle when *constructing* the object? Isn't drawing something a one-time action? How does the rectangle get drawn the *second* frame? And it gets even weirder when you create a Graphics object with a bunch of drawThis and drawThat calls, and then you use it as a *mask*. What??? + +The problem is that the function names are centered around *drawing*, which is an action that puts pixels on the screen. But in spite of that, the Graphics object is really about *building*. + +Let's look a bit deeper at that `drawRect()` call. When you call `drawRect()`, PixiJS doesn't actually draw anything. Instead, it stores the rectangle you "drew" into a list of geometry for later use. If you then add the Graphics object to the scene, the renderer will come along, and ask the Graphics object to render itself. At that point, your rectangle actually gets drawn - along with any other shapes, lines, etc. that you've added to the geometry list. + +Once you understand what's going on, things start to make a lot more sense. When you use a Graphics object as a mask, for example, the masking system uses that list of graphics primitives in the geometry list to constrain which pixels make it to the screen. There's no drawing involved. + +That's why it helps to think of the Graphics class not as a drawing tool, but as a geometry building tool. + +## Types of Primitives + +There are a lot of functions in the PIXI.Graphics class, but as a quick orientation, here's the list of basic primitives you can add: + +* Line +* Rect +* RoundRect +* Circle +* Ellipse +* Arc +* Bezier and Quadratic Curve + +In addition, the Graphics Extras package (`@pixi/graphics-extras`) optionally includes the following complex primitives: + +* Torus +* Chamfer Rect +* Fillet Rect +* Regular Polygon +* Star +* Rounded Polygon + +## The Geometry List + +Inside every Graphics object is a GraphicsGeometry object. The [GraphicsGeometry](https://pixijs.download/release/docs/PIXI.GraphicsGeometry.html) class manages the list of geometry primitives created by the Graphics parent object. For the most part, you will not work directly with this object. The owning Graphics object creates and manages it. However, there are two related cases where you *do* work with the list. + +First, you can re-use geometry from one Graphics object in another. No matter whether you're re-drawing the same shape over and over, or re-using it as a mask over and over, it's more efficient to share identical GraphicsGeometry. You can do this like so: + +```javascript +// Create a master graphics object +let template = new PIXI.Graphics(); +// Add a circle +template.drawCircle(100, 100, 50); + +// Create 5 duplicate objects +for (let i = 0; i < 5; i++) { + // Initialize the duplicate using our template's pre-built geometry + let duplicate = new PIXI.Graphics(template.geometry); +} +``` + +This leads to the second time you need to be aware of the underlying GraphicsGeometry object - avoiding memory leaks. Because Graphics objects can share geometry, you *must* call `destroy()` when you no longer need them. Failure to do so will prevent the GraphicsGeometry object it owns from being properly de-referenced, and will lead to memory leaks. + +## Graphics For Display + +OK, so now that we've covered how the PIXI.Graphics class works, let's look at how you use it. The most obvious use of a Graphics object is to draw dynamically generated shapes to the screen. + +Doing so is simple. Create the object, call the various builder functions to add your custom primitives, then add the object to the scene graph. Each frame, the renderer will come along, ask the Graphics object to render itself, and each primitive, with associated line and fill styles, will be drawn to the screen. + + +## Graphics as a Mask + +You can also use a Graphics object as a complex mask. To do so, build your object and primitives as usual. Next create a PIXI.Container object that will contain the masked content, and set its `mask` property to your Graphics object. The children of the container will now be clipped to only show through inside the geometry you've created. This technique works for both WebGL and Canvas-based rendering. + +Check out the [masking example code](/examples/graphics/simple). + +## Caveats and Gotchas + +The Graphics class is a complex beast, and so there are a number of things to be aware of when using it. + +**Memory Leaks**: The first has already been mentioned - call `destroy()` on any Graphics object you no longer need to avoid memory leaks. + +**Holes**: Holes you create have to be completely contained in the shape or else it may not be able to triangulate correctly. + +**Changing Geometry**: If you want to change the shape of a Graphics object, you don't need to delete and recreate it. Instead you can use the `clear()` function to reset the contents of the geometry list, then add new primitives as desired. Be careful of performance when doing this every frame. + +**Performance**: Graphics objects are generally quite performant. However, if you build highly complex geometry, you may pass the threshold that permits batching during rendering, which can negatively impact performance. It's better for batching to use many Graphics objects instead of a single Graphics with many shapes. + +**Transparency**: Because the Graphics object renders its primitives sequentially, be careful when using blend modes or partial transparency with overlapping geometry. Blend modes like `ADD` and `MULTIPLY` will work *on each primitive*, not on the final composite image. Similarly, partially transparent Graphics objects will show primitives overlapping. To apply transparency or blend modes to a single flattened surface, consider using AlphaFilter or RenderTexture. + + diff --git a/versioned_docs/version-7.3.2/guides/components/interaction.md b/versioned_docs/version-7.3.2/guides/components/interaction.md new file mode 100644 index 000000000..3aa113495 --- /dev/null +++ b/versioned_docs/version-7.3.2/guides/components/interaction.md @@ -0,0 +1,110 @@ +# Interaction + +PixiJS is primarily a rendering system, but it also includes support for interactivity. Adding support for mouse and touch events to your project is simple and consistent. + +## Event Modes + +The new event-based system that replaced InteractionManager from v6 has expanded the definition of what a DisplayObject means to be interactive. With this we have introduced `eventMode` which allows you to control how an object responds to interaction events. This is similar to the `interactive` property in v6 but with more options. + +| eventMode | Description | +|---|---| +| `none` | Ignores all interaction events, similar to CSS's `pointer-events: none`, good optimization for non-interactive children | +| `passive` | Does not emit events and ignores hit testing on itself but does allow for events and hit testing only its interactive children. If you want to be compatible with v6, set this as your default `eventMode` (see options in Renderer, Application, etc) | +| `auto` | Does not emit events and but is hit tested if parent is interactive. Same as `interactive = false` in v7 | +| `static` | Emit events and is hit tested. Same as `interaction = true` in v7, useful for objects like buttons that do not move. | +| `dynamic` | Emits events and is hit tested but will also receive mock interaction events fired from a ticker to allow for interaction when the mouse isn't moving. This is useful for elements that independently moving or animating. | + +## Event Types + +PixiJS supports the following event types: + +| Event Type | Description | +|---|---| +| `pointercancel` | Fired when a pointer device button is released outside the display object that initially registered a pointerdown. | +| `pointerdown` | Fired when a pointer device button is pressed on the display object. | +| `pointerenter` | Fired when a pointer device enters the display object. | +| `pointerleave` | Fired when a pointer device leaves the display object. | +| `pointermove` | Fired when a pointer device is moved while over the display object. | +| `globalpointermove` | Fired when a pointer device is moved, regardless of hit-testing the current object. | +| `pointerout` | Fired when a pointer device is moved off the display object. | +| `pointerover` | Fired when a pointer device is moved onto the display object. | +| `pointertap` | Fired when a pointer device is tapped twice on the display object. | +| `pointerup` | Fired when a pointer device button is released over the display object. | +| `pointerupoutside` | Fired when a pointer device button is released outside the display object that initially registered a pointerdown. | +| `mousedown ` | Fired when a mouse button is pressed on the display object. | +| `mouseenter` | Fired when the mouse cursor enters the display object. | +| `mouseleave` | Fired when the mouse cursor leaves the display object. | +| `mousemove ` | Fired when the mouse cursor is moved while over the display object. | +| `globalmousemove` | Fired when a mouse is moved, regardless of hit-testing the current object. | +| `mouseout ` | Fired when the mouse cursor is moved off the display object. | +| `mouseover ` | Fired when the mouse cursor is moved onto the display object. | +| `mouseup ` | Fired when a mouse button is released over the display object. | +| `mouseupoutside ` | Fired when a mouse button is released outside the display object that initially registered a mousedown. | +| `click ` | Fired when a mouse button is clicked (pressed and released) over the display object. | +| `touchcancel ` | Fired when a touch point is removed outside of the display object that initially registered a touchstart. | +| `touchend ` | Fired when a touch point is removed from the display object. | +| `touchendoutside ` | Fired when a touch point is removed outside of the display object that initially registered a touchstart. | +| `touchmove ` | Fired when a touch point is moved along the display object. | +| `globaltouchmove` | Fired when a touch point is moved, regardless of hit-testing the current object. | +| `touchstart ` | Fired when a touch point is placed on the display object. | +| `tap ` | Fired when a touch point is tapped twice on the display object. | +| `wheel ` | Fired when a mouse wheel is spun over the display object. | +| `rightclick ` | Fired when a right mouse button is clicked (pressed and released) over the display object. | +| `rightdown ` | Fired when a right mouse button is pressed on the display object. | +| `rightup ` | Fired when a right mouse button is released over the display object. | +| `rightupoutside ` | Fired when a right mouse button is released outside the display object that initially registered a rightdown. | + + +## Enabling Interaction + +Any DisplayObject-derived object (Sprite, Container, etc.) can become interactive simply by setting its `eventMode` property to any of the eventModes listed above. Doing so will cause the object to emit interaction events that can be responded to in order to drive your project's behavior. + +Check out the [interaction example code](/examples/events/click). + +To respond to clicks and taps, bind to the events fired on the object, like so: + +```javascript +let sprite = PIXI.Sprite.from('/some/texture.png'); +sprite.on('pointerdown', (event) => { alert('clicked!'); }); +sprite.eventMode = 'static'; +``` + +Check out the [DisplayObject](https://pixijs.download/release/docs/PIXI.DisplayObject.html) for the list of interaction events supported. + +### Checking if Object is Interactive + +You can check if an object is interactive by calling the `isInteractive` property. This will return true if `eventMode` is set to `static` or `dynamic`. + +```javascript +if (sprite.isInteractive()) { + // sprite is interactive +} +``` + +## Use Pointer Events + +PixiJS supports three types of interaction events - mouse, touch and pointer. Mouse events are fired by mouse movement, clicks etc. Touch events are fired for touch-capable devices. And pointer events are fired for _both_. + +What this means is that, in many cases, you can write your project to use pointer events and it will just work when used with _either_ mouse or touch input. Given that, the only reason to use non-pointer events is to support different modes of operation based on input type or to support multi-touch interaction. In all other cases, prefer pointer events. + +## Optimization + +Hit testing requires walking the full object tree, which in complex projects can become an optimization bottleneck. To mitigate this issue, PixiJS Container-derived objects have a property named `interactiveChildren`. If you have Containers or other objects with complex child trees that you know will never be interactive, you can set this property to `false` and the hit testing algorithm will skip those children when checking for hover and click events. As an example, if you were building a side-scrolling game, you would probably want to set `background.interactiveChildren = false` for your background layer with rocks, clouds, flowers, etc. Doing so would speed up hit testing substantially due to the number of unclickable child objects the background layer would contain. + +The `EventSystem` can also be customised to be more performant: +```js +const app = new PIXI.Application({ + /** + * by default we use `auto` for backwards compatibility. + * However `passive` is more performant and will be used by default in the future, + */ + eventMode: 'passive', + eventFeatures: { + move: true, + /** disables the global move events which can be very expensive in large scenes */ + globalMove: false, + click: true, + wheel: true, + } +}); +``` diff --git a/versioned_docs/version-7.3.2/guides/components/sprite-sheets.md b/versioned_docs/version-7.3.2/guides/components/sprite-sheets.md new file mode 100644 index 000000000..08511fa71 --- /dev/null +++ b/versioned_docs/version-7.3.2/guides/components/sprite-sheets.md @@ -0,0 +1,84 @@ +# Spritesheets + +Now that you understand basic sprites, it's time to talk about a better way to create them - the [Spritesheet](https://pixijs.download/release/docs/PIXI.Spritesheet.html) class. + +A Spritesheet is a media format for more efficiently downloading and rendering Sprites. While somewhat more complex to create and use, they are a key tool in optimizing your project. + +## Anatomy of a Spritesheet + +The basic idea of a spritesheet is to pack a series of images together into a single image, track where each source image ends up, and use that combined image as a shared BaseTexture for the resulting Sprites. + +The first step is to collect the images you want to combine. The sprite packer then collects the images, and creates a new combined image. + + + +As this image is being created, the tool building it keeps track of the location of the rectangle where each source image is stored. It then writes out a JSON file with that information. + + + +These two files, in combination, can be passed into a SpriteSheet constructor. The SpriteSheet object then parses the JSON, and creates a series of Texture objects, one for each source image, setting the source rectangle for each based on the JSON data. Each texture uses the same shared BaseTexture as its source. + +## Doubly Efficient + +SpriteSheets help your project in two ways. + +First, by __speeding up the loading process__. While downloading a SpriteSheet's texture requires moving the same (or even slightly more!) number of bytes, they're grouped into a single file. This means that the user's browser can request and download far fewer files for the same number of Sprites. The number of files *itself* is a key driver of download speed, because each request requires a round-trip to the webserver, and browsers are limited to how many files they can download simultaneously. Converting a project from individual source images to shared sprite sheets can cut your download time in half, at no cost in quality. + +Second, by __improving batch rendering__. WebGL rendering speed scales roughly with the number of draw calls made. Batching multiple Sprites, etc. into a single draw call is the main secret to how PixiJS can run so blazingly fast. Maximizing batching is a complex topic, but when multiple Sprites all share a common BaseTexture, it makes it more likely that they can be batched together and rendered in a single call. + +## Creating SpriteSheets + +You can use a 3rd party tool to assemble your sprite sheet files. Here are two that may fit your needs: + +[ShoeBox](http://renderhjs.net/shoebox/): ShoeBox is a free, Adobe AIR-based sprite packing utility that is great for small projects or learning how SpriteSheets work. + +[TexturePacker](https://www.codeandweb.com/texturepacker): TexturePacker is a more polished tool that supports advanced features and workflows. A free version is available which has all the necessary features for packing spritesheets for PixiJS. It's a good fit for larger projects and professional game development, or projects that need more complex tile mapping features. + +Spritesheet data can also be created manually or programmatically, and supplied to a new AnimatedSprite. This may be an easier option if your sprites are already contained in a single image. + +```javascript +// Create object to store sprite sheet data +const atlasData = { + frames: { + enemy1: { + frame: { x: 0, y:0, w:32, h:32 }, + sourceSize: { w: 32, h: 32 }, + spriteSourceSize: { x: 0, y: 0, w: 32, h: 32 } + }, + enemy2: { + frame: { x: 32, y:0, w:32, h:32 }, + sourceSize: { w: 32, h: 32 }, + spriteSourceSize: { x: 0, y: 0, w: 32, h: 32 } + }, + }, + meta: { + image: 'images/spritesheet.png', + format: 'RGBA8888', + size: { w: 128, h: 32 }, + scale: 1 + }, + animations: { + enemy: ['enemy1','enemy2'] //array of frames by name + } +} + + +// Create the SpriteSheet from data and image +const spritesheet = new PIXI.Spritesheet( + PIXI.BaseTexture.from(atlasData.meta.image), + atlasData +); + +// Generate all the Textures asynchronously +await spritesheet.parse(); + +// spritesheet is ready to use! +const anim = new PIXI.AnimatedSprite(spritesheet.animations.enemy); + +// set the animation speed +anim.animationSpeed = 0.1666; +// play the animation on a loop +anim.play(); +// add it to the stage to render +app.stage.addChild(anim); +``` diff --git a/versioned_docs/version-7.3.2/guides/components/sprites.md b/versioned_docs/version-7.3.2/guides/components/sprites.md new file mode 100644 index 000000000..db495b6b3 --- /dev/null +++ b/versioned_docs/version-7.3.2/guides/components/sprites.md @@ -0,0 +1,41 @@ +# Sprites + +Sprites are the simplest and most common renderable object in PixiJS. They represent a single image to be displayed on the screen. Each [Sprite](https://pixijs.download/release/docs/PIXI.Sprite.html) contains a [Texture](https://pixijs.download/release/docs/PIXI.Texture.html) to be drawn, along with all the transformation and display state required to function in the scene graph. + +## Creating Sprites + +To create a Sprite, all you need is a Texture (check out the Texture guide). Load a PNG's URL using the PIXI.Loader class, then call `PIXI.Sprite.from(url)` and you're all set. As a convenience during prototyping, you can pass a non-loaded URL to `from()` and PixiJS will handle it, but your sprite will "pop in" after it loads if you don't pre-load your textures. + +Check out the [sprite example code](/examples/sprite/basic). + +## Using Sprites + +In our [DisplayObject guide](display-object), we learned about the DisplayObject class and the various properties it defines. Since Sprite objects are also display objects, you can move a sprite, rotate it, and update any other display property. + +## Alpha, Tint and Blend Modes + +Alpha is a standard display object property. You can use it to fade sprites into the scene by animating each sprite's alpha from 0.0 to 1.0 over a period of time. + +Tinting allows you multiply the color value of every pixel by a single color. For example, if you had a dungeon game, you might show a character's poison status by setting `obj.tint = 0x00FF00`, which would give a green tint to the character. + +Blend modes change how pixel colors are added to the screen when rendering. The three main modes are __add__, which adds each pixel's RGB channels to whatever is under your sprite (useful for glows and lighting), __multiply__ which works like `tint`, but on a per-pixel basis, and __screen__, which overlays the pixels, brightening whatever is underneath them. + +## Scale vs Width & Height + +One common area of confusion when working with sprites lies in scaling and dimensions. The PIXI.DisplayObject class allows you to set the x and y scale for any object. Sprites, being DisplayObjects, also support scaling. In addition, however, Sprites support explicit `width` and `height` attributes that can be used to achieve the same effect, but are in pixels instead of a percentage. This works because a Sprite object owns a Texture, which has an explicit width and height. When you set a Sprite's width, internally PixiJS converts that width into a percentage of the underlying texture's width and updates the object's x-scale. So width and height are really just convenience methods for changing scale, based on pixel dimensions rather than percentages. + +## Pivot vs Anchor + +If you add a sprite to your stage and rotate it, it will by default rotate around the top-left corner of the image. In some cases, this is what you want. In many cases, however, what you want is for the sprite to rotate around the center of the image it contains, or around an arbitrary point. + +There are two ways to achieve this: *pivots* and *anchors* + +An object's __pivot__ is an offset, expressed in pixels, from the top-left corner of the Sprite. It defaults to (0, 0). If you have a Sprite whose texture is 100px x 50px, and want to set the pivot point to the center of the image, you'd set your pivot to (50, 25) - half the width, and half the height. Note that pivots can be set *outside* of the image, meaning the pivot may be less than zero or greater than the width/height. This can be useful in setting up complex animation hierarchies, for example. Every DisplayObject has a pivot. + +An __anchor__, in contrast, is only available for Sprites. Anchors are specified in percentages, from 0.0 to 1.0, in each dimension. To rotate around the center point of a texture using anchors, you'd set your Sprite's anchor to (0.5, 0.5) - 50% in width and height. While less common, anchors can also be outside the standard 0.0 - 1.0 range. + +The nice thing about anchors is that they are resolution and dimension agnostic. If you set your Sprite to be anchored in the middle then later change the size of the texture, your object will still rotate correctly. If you had instead set a pivot using pixel-based calculations, changing the texture size would require changing your pivot point. + +So, generally speaking, you'll want to use anchors when working with Sprites. + +One final note: unlike CSS, where setting the transform-origin of the image doesn't move it, in PixiJS setting an anchor or pivot *will* move your object on the screen. In other words, setting an anchor or pivot affects not just the rotation origin, but also the position of the sprite relative to its parent. diff --git a/versioned_docs/version-7.3.2/guides/components/text.md b/versioned_docs/version-7.3.2/guides/components/text.md new file mode 100644 index 000000000..d7a1b53c1 --- /dev/null +++ b/versioned_docs/version-7.3.2/guides/components/text.md @@ -0,0 +1,106 @@ +# Text + +Whether it's a high score or a diagram label, text is often the best way to convey information in your projects. Surprisingly, drawing text to the screen with WebGL is a very complex process - there's no built in support for it at all. One of the values PixiJS provides is in hiding this complexity to allow you to draw text in diverse styles, fonts and colors with a few lines of code. In addition, these bits of text are just as much scene objects as sprites - you can tint text, rotate it, alpha-blend it, and otherwise treat it like any other graphical object. + +Let's dig into how this works. + +## There Are Two Kinds of Text + +Because of the challenges of working with text in WebGL, PixiJS provides two very different solutions. In this guide, we're going to go over both methods in some detail to help you make the right choice for your project's needs. Selecting the wrong text type can have a large negative impact on your project's performance and appearance. + +## The Text Object + +In order to draw text to the screen, you use a [Text](https://pixijs.download/release/docs/PIXI.Text.html) object. Under the hood, this class draws text to an off-screen buffer using the browser's normal text rendering, then uses that offscreen buffer as the source for drawing the text object. Effectively what this means is that whenever you create or change text, PixiJS creates a new rasterized image of that text, and then treats it like a sprite. This approach allows truly rich text display while keeping rendering speed high. + +So when working with PIXI.Text objects, there are two sets of options - standard display object options like position, rotation, etc that work *after* the text is rasterized internally, and text style options that are used *while* rasterizing. Because text once rendered is basically just a sprite, there's no need to review the standard options. Instead, let's focus on how text is styled. + +Check out the [text example code](/examples/text/pixi-text). + +## Text Styles + +There are a lot of text style options available (see [TextStyle](https://pixijs.download/release/docs/PIXI.TextStyle.html)), but they break down into 5 main groups: + +**Font**: `fontFamily` to select the webfont to use, `fontSize` to specify the size of the text to draw, along with options for font weight, style and variant. + +**Appearance**: Set the color with `fill` or add a `stroke` outline, including options for gradient fills. + +**Drop-Shadows**: Set a drop-shadow with `dropShadow`, with a host of related options to specify offset, blur, opacity, etc. + +**Layout**: Enable with `wordWrap` and `wordWrapWidth`, and then customize the `lineHeight` and `align` or `letterSpacing` + +**Utilities**: Add `padding` or `trim` extra space to deal with funky font families if needed. + +To interactively test out feature of Text Style, [check out this tool](https://pixijs.io/pixi-text-style/). + +## Loading and Using Fonts + +In order for PixiJS to build a PIXI.Text object, you'll need to make sure that the font you want to use is loaded by the browser. Unfortunately, at the time of writing, the PIXI.Loader system does not support loading font files, so you'll need to use a 3rd party font loader to ensure that any custom web fonts you want to use are pre-loaded. It's not enough to add an @font-face declaration in your project's CSS because browsers will happily render text using a fallback font while your custom font loads. + +Any javascript library that can load a web font will work, you just want something that will delay starting your project until the font has been fully loaded by the browser. + +One such library is [FontFaceObserver](https://fontfaceobserver.com). Here's a simple example that shows how to use it to ensure the web font "Short Stack" is loaded before your app starts. First, we need a font-face declaration in CSS: + +```css +@font-face { + font-family: Short Stack; + src: url(short-stack.woff2) format('woff2'), + url(short-stack.woff) format('woff'); +} +``` + +Now that the browser knows what our font is and how to find the source files, it's time to use the library to load them: + +```javascript +// Create the loader +let font = new FontFaceObserver('Short Stack', {}); +// Start loading the font +font.load().then(() => { + // Successful load, start up your PixiJS app as usual + let app = new PIXI.Application({ width: 640, height: 360 }); + document.body.appendChild(app.view); + // ... etc ... + +}, () => { + // Failed load, log the error or display a message to the user + alert('Unable to load required font!'); +}); +``` + +## Caveats and Gotchas + +While PixiJS does make working with text easy, there are a few things you need to watch out for. + +First, changing an existing text string requires re-generating the internal render of that text, which is a slow operation that can impact performance if you change many text objects each frame. If your project requires lots of frequently changing text on the screen at once, consider using a PIXI.BitmapText object (explained below) which uses a fixed bitmap font that doesn't require re-generation when text changes. + +Second, be careful when scaling text. Setting a text object's scale to > 1.0 will result in blurry/pixely display, because the text is not re-rendered at the higher resolution needed to look sharp - it's still the same resolution it was when generated. To deal with this, you can render at a higher initial size and down-scale, instead. This will use more memory, but will allow your text to always look clear and crisp. + +## BitmapText + +In addition to the standard PIXI.Text approach to adding text to your project, PixiJS also supports *bitmap fonts*. Bitmap fonts are very different from TrueType or other general purpose fonts, in that they consist of a single image containing pre-rendered versions of every letter you want to use. When drawing text with a bitmap font, PixiJS doesn't need to render the font glyphs into a temporary buffer - it can simply copy and stamp out each character of a string from the master font image. + +The primary advantage of this approach is speed - changing text frequently is much cheaper and rendering each additional piece of text is much faster due to the shared source texture. + +Check out the [bitmap text example code](/examples/text/bitmap-text). + +## BitmapFont + +- 3rd party solutions +- BitmapFont.from auto-generation + +## Selecting the Right Approach + +PIXI.Text +- Static text +- Small number of text objects +- High fidelity text rendering (kerning e.g.) +- Text layout (line & letter spacing) + +PIXI.BitmapText +- Dynamic text +- Large number of text objects +- Lower memory + + diff --git a/versioned_docs/version-7.3.2/guides/components/textures.md b/versioned_docs/version-7.3.2/guides/components/textures.md new file mode 100644 index 000000000..492cf2f8c --- /dev/null +++ b/versioned_docs/version-7.3.2/guides/components/textures.md @@ -0,0 +1,75 @@ +# Textures + +We're slowly working our way down from the high level to the low. We've talked about the scene graph, and in general about display objects that live in it. We're about to get to sprites and other simple display objects. But before we do, we need to talk about textures. + +In PixiJS, textures are one of the core resources used by display objects. A texture, broadly speaking, represents a source of pixels to be used to fill in an area on the screen. The simplest example is a sprite - a rectangle that is completely filled with a single texture. But things can get much more complex. + +## Life-cycle of a Texture + +Let's examine how textures really work, by following the path your image data travels on its way to the screen. + +Here's the flow we're going to follow: Source Image > Loader > BaseTexture > Texture + +### Serving the Image + +To start with, you have the image you want to display. The first step is to make it available on your server. This may seem obvious, but if you're coming to PixiJS from other game development systems, it's worth remembering that everything has to be loaded over the network. If you're developing locally, please be aware that you *must* use a webserver to test, or your images won't load due to how browsers treat local file security. + +### Loading the Image + +To work with the image, the first step is to pull the image file from your webserver into the user's web browser. To do this, we can use `PIXI.Texture.from()`, which works for quick demos, but in production you'll use the Loader class. A Loader wraps and manages using an `` element to tell the browser to fetch the image, and then notifies you when that has been completed. This process is *asynchronous* - you request the load, then time passes, then an event fires to let you know the load is completed. We'll go into the loader in a lot more depth in a later guide. + +### BaseTextures Own the Data + +Once the Loader has done its work, the loaded `` element contains the pixel data we need. But to use it to render something, PixiJS has to take that raw image file and upload it to the GPU. This brings us to the real workhorse of the texture system - the [BaseTexture](https://pixijs.download/release/docs/PIXI.BaseTexture.html) class. Each BaseTexture manages a single pixel source - usually an image, but can also be a Canvas or Video element. BaseTextures allow PixiJS to convert the image to pixels and use those pixels in rendering. In addition, it also contains settings that control how the texture data is rendered, such as the wrap mode (for UV coordinates outside the 0.0-1.0 range) and scale mode (used when scaling a texture). + +BaseTextures are automatically cached, so that calling `PIXI.Texture.from()` repeatedly for the same URL returns the same BaseTexture each time. Destroying a BaseTexture frees the image data associated with it. + +### Textures are a View on BaseTextures + +So finally, we get to the PIXI.Texture class itself! At this point, you may be wondering what the Texture object *does*. After all, the BaseTexture manages the pixels and render settings. And the answer is, it doesn't do very much. Textures are light-weight views on an underlying BaseTexture. Their main attribute is the source rectangle within the BaseTexture from which to pull. + +If all PixiJS drew were sprites, that would be pretty redundant. But consider [SpriteSheets](./sprite-sheets). A SpriteSheet is a single image that contains multiple sprite images arranged within. In a [Spritesheet](https://pixijs.download/release/docs/PIXI.Spritesheet.html) object, a single BaseTexture is referenced by a set of Textures, one for each source image in the original sprite sheet. By sharing a single BaseTexture, the browser only downloads one file, and our batching renderer can blaze through drawing sprites since they all share the same underlying pixel data. The SpriteSheet's Textures pull out just the rectangle of pixels needed by each sprite. + + + +That is why we have both Textures and BaseTextures - to allow sprite sheets, animations, button states, etc to be loaded as a single image, while only displaying the part of the master image that is needed. + +## Loading Textures + +We will discuss resource loading in a later guide, but one of the most common issues new users face when building a PixiJS project is how best to load their textures. Using `PIXI.Texture.from()` as we do in our demo snippets will work, but will result in pop-in as each texture is loaded while your objects are already being rendered in the scene graph. + +Instead, here's a quick cheat sheet of one good solution: + +1. Show a loading image +2. Create a Loader +3. Run all texture-based objects, add their textures to the loader +4. Start the loader, and optionally update your loading image based on progress callbacks +5. On loader completion, run all objects and use `PIXI.Texture.from()` to pull the loaded textures out of the texture cache +6. Prepare your textures (optional - see below) +7. Hide your loading image, start rendering your scene graph + +Using this workflow ensures that your textures are pre-loaded, to prevent pop-in, and is relatively easy to code. + +Regarding preparing textures: Even after you've loaded your textures, the images still need to be pushed to the GPU and decoded. Doing this for a large number of source images can be slow and cause lag spikes when your project first loads. To solve this, you can use the [Prepare](https://pixijs.download/release/docs/PIXI.Prepare.html) plugin, which allows you to pre-load textures in a final step before displaying your project. + +## Unloading Textures + +Once you're done with a Texture, you may wish to free up the memory (both WebGL-managed buffers and browser-based) that it uses. To do so, you should call `destroy()` on the BaseTexture that owns the data. Remember that Textures don't manage pixel data! + +This is a particularly good idea for short-lived imagery like cut-scenes that are large and will only be used once. If you want to remove *all* textures and wipe the slate clean, you can use the `PIXI.utils.destroyTextureCache()` function. + +## Beyond Images + +As we alluded to above, you can make a Texture out of more than just images: + +Video: Pass an HTML5 `