From 939764c9e890b44d981e662bad5b94144ced811e Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 21 Apr 2023 13:34:00 +0000 Subject: [PATCH 001/188] UdpServer: docs --- libraries/UdpServer/UdpServer.h | 54 +++++++++++++++++++++------------ 1 file changed, 34 insertions(+), 20 deletions(-) diff --git a/libraries/UdpServer/UdpServer.h b/libraries/UdpServer/UdpServer.h index a51b5bd57..bc49bbe1c 100644 --- a/libraries/UdpServer/UdpServer.h +++ b/libraries/UdpServer/UdpServer.h @@ -4,9 +4,7 @@ * Created on: 19 May 2015 * Author: giulio moro */ - -#ifndef UDPSERVER_H_ -#define UDPSERVER_H_ +#pragma once #include #include @@ -40,34 +38,50 @@ class UdpServer{ ~UdpServer(); bool setup(int aPort); void cleanup(); - bool bindToPort(int aPort); + /** + * Get the port that the server is currently listening on + */ int getBoundPort() const; - /* + bool bindToPort(int aPort); + /** * Reads bytes from the socket. * - * Drop-in replacement for JUCE DatagramSocket::read() - * - If blockUntilSpecifiedAmountHasArrived is true, the method will block until maxBytesToRead - bytes have been read, (or until an error occurs). If this flag is false, the method will - return as much data as is currently available without blocking. + * @param destBuffer the destination buffer + * @param maxBytesToRead the maximum number of bytes to read + * @param blockUntilSpecifiedAmountHasArrived If `true`, the method + * will block until @p maxBytesToRead bytes have been read, (or + * until an error occurs). If it is false, the method + * will return as much data as is currently available without + * blocking. */ int read(void* destBuffer, int maxBytesToRead, bool blockUntilSpecifiedAmountHasArrived); void close(); + /** + * Drain the input buffer + */ int empty(); int empty(int maxCount); - /* - * Waits until the socket is ready for reading or writing. + /** + * Waits until the socket is ready for reading. + * + * @param timeoutMsecs If it is < 0, it will wait forever, + * or else will give up after the specified time in milliseconds. * - Drop-in replacement for JUCE DatagramSocket::waitUntilReady. - If readyForReading is true, it will wait until the socket is ready for reading; if false, it will wait until it's ready for writing. - If the timeout is < 0, it will wait forever, or else will give up after the specified time. - If the socket is ready on return, this returns 1. If it times-out before the socket becomes ready, it returns 0. If an error occurs, it returns -1. + * @return If the socket is ready on return, this returns 1. + * If it times-out before the socket becomes ready, it + * returns 0. If an error occurs, it returns -1. + */ + int waitUntilReady(int timeoutMsecs); + /** + * Deprecated. Should be called with `readyForReading=true` */ int waitUntilReady(bool readyForReading, int timeoutMsecs); + /** + * Get the source port for the last received message + */ int getLastRecvPort(); + /** + * Get the source address for the last received message + */ const char* getLastRecvAddr(); }; - - - -#endif /* UDPSERVER_H_ */ From 8a416100e08f7fc1a03b493386ab09838cbd8378 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 21 Apr 2023 13:40:00 +0000 Subject: [PATCH 002/188] UdpServer: better cleanup, provided implementation for new version of waitUntilReady() --- libraries/OscReceiver/OscReceiver.cpp | 2 +- libraries/UdpServer/UdpServer.cpp | 19 +++++++++++++++---- libraries/UdpServer/UdpServer.h | 2 +- 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/libraries/OscReceiver/OscReceiver.cpp b/libraries/OscReceiver/OscReceiver.cpp index 15e6c4b67..6611f24a5 100644 --- a/libraries/OscReceiver/OscReceiver.cpp +++ b/libraries/OscReceiver/OscReceiver.cpp @@ -51,7 +51,7 @@ void OscReceiver::setup(int port, std::functionwaitUntilReady(true, timeout); + int ret = socket->waitUntilReady(timeout); if (ret == -1){ fprintf(stderr, "OscReceiver: Error polling UDP socket: %d %s\n", errno, strerror(errno)); return -1; diff --git a/libraries/UdpServer/UdpServer.cpp b/libraries/UdpServer/UdpServer.cpp index 8c0f003af..a03e4eaef 100644 --- a/libraries/UdpServer/UdpServer.cpp +++ b/libraries/UdpServer/UdpServer.cpp @@ -50,14 +50,25 @@ bool UdpServer::bindToPort(int aPort){ return true; } +int UdpServer::getBoundPort() const { + return enabled ? server.sin_port : -1; +} + void UdpServer::close(){ - int ret=::close(inSocket); - if(ret != 0) - printf("Error while closing socket, errno: %d\n", errno);//Stop receiving data for this socket. If further data arrives, reject it. - inSocket=0; + if(inSocket >= 0) + { + int ret =::close(inSocket); + if(ret != 0) + fprintf(stderr, "Error while closing socket, errno: %d\n", errno); + } + inSocket = -1; + enabled = false; } int UdpServer::waitUntilReady(bool readyForReading, int timeoutMsecs){ + return waitUntilReady(timeoutMsecs); +} +int UdpServer::waitUntilReady(int timeoutMsecs){ // If the socket is ready on return, this returns 1. If it times-out before the socket becomes ready, it returns 0. If an error occurs, it returns -1. if(enabled==false) return -1; diff --git a/libraries/UdpServer/UdpServer.h b/libraries/UdpServer/UdpServer.h index bc49bbe1c..9843b0a6d 100644 --- a/libraries/UdpServer/UdpServer.h +++ b/libraries/UdpServer/UdpServer.h @@ -21,7 +21,7 @@ class UdpServer{ private: int port; int enabled; - int inSocket; + int inSocket = -1; struct sockaddr_in server; struct timeval stTimeOut; struct timeval stZeroTimeOut; From da4a4df857f183c03eb0d0fb6a226f4cb379d67b Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 21 Apr 2023 13:49:54 +0000 Subject: [PATCH 003/188] NIT: UdpServer: fixed (most?) whitespaces --- libraries/UdpServer/UdpServer.cpp | 78 +++++++++++++++---------------- 1 file changed, 39 insertions(+), 39 deletions(-) diff --git a/libraries/UdpServer/UdpServer.cpp b/libraries/UdpServer/UdpServer.cpp index a03e4eaef..637157bf8 100644 --- a/libraries/UdpServer/UdpServer.cpp +++ b/libraries/UdpServer/UdpServer.cpp @@ -17,36 +17,36 @@ UdpServer::~UdpServer(){ cleanup(); }; bool UdpServer::setup(int aPort){ - enabled=true; + enabled = true; stZeroTimeOut.tv_sec = 0; //set timeout to 0 stZeroTimeOut.tv_usec = 0; - inSocket=socket(AF_INET, SOCK_DGRAM, 0); - if (inSocket < 0){ - enabled=false; + inSocket = socket(AF_INET, SOCK_DGRAM, 0); + if(inSocket < 0) { + enabled = false; return false; } length = sizeof(server); - server.sin_family=AF_INET; - server.sin_addr.s_addr=INADDR_ANY; - enabled=bindToPort(aPort); - wasteBufferSize=2048; - wasteBuffer=malloc(wasteBufferSize); - memset(&stTimeOut,0,sizeof(struct timeval)); + server.sin_family = AF_INET; + server.sin_addr.s_addr = INADDR_ANY; + enabled = bindToPort(aPort); + wasteBufferSize = 2048; + wasteBuffer = malloc(wasteBufferSize); + memset(&stTimeOut, 0, sizeof(struct timeval)); return enabled; } bool UdpServer::bindToPort(int aPort){ - port=aPort; - if(port<1){ - enabled=false; + port = aPort; + if(port < 1){ + enabled = false; return false; } - server.sin_port=htons(port); - if (bind(inSocket,(struct sockaddr *)&server,length)<0){ - enabled=false; + server.sin_port = htons(port); + if (bind(inSocket, (struct sockaddr *)&server, length) < 0){ + enabled = false; return false; } - enabled=true; + enabled = true; return true; } @@ -70,21 +70,21 @@ int UdpServer::waitUntilReady(bool readyForReading, int timeoutMsecs){ } int UdpServer::waitUntilReady(int timeoutMsecs){ // If the socket is ready on return, this returns 1. If it times-out before the socket becomes ready, it returns 0. If an error occurs, it returns -1. - if(enabled==false) + if(enabled == false) return -1; - if(timeoutMsecs<0) - return select(inSocket+1, &stReadFDS, NULL, NULL, NULL); //calling this with a NULL timeout will block indefinitely + if(timeoutMsecs < 0) + return select(inSocket + 1, &stReadFDS, NULL, NULL, NULL); //calling this with a NULL timeout will block indefinitely FD_ZERO(&stReadFDS); FD_SET(inSocket, &stReadFDS); - float timeOutSecs=timeoutMsecs*0.001; - stTimeOut.tv_sec=(long int)timeOutSecs; - timeOutSecs-=(int)timeOutSecs; - long int timeOutUsecs=timeOutSecs*1000000; - stTimeOut.tv_usec=timeOutUsecs; - int descriptorReady= select(inSocket+1, &stReadFDS, NULL, NULL, &stTimeOut); -// printf("stTimeOut.tv_sec=%ld, stTimeOut.tv_usec=%ld, descriptorReady: \n",stTimeOut.tv_sec,stTimeOut.tv_usec, descriptorReady); -// return descriptorReady>0 ? (timeOutUsecs-stTimeOut.tv_usec) : descriptorReady; - return descriptorReady>0 ? 1 : descriptorReady; + float timeOutSecs = timeoutMsecs * 0.001; + stTimeOut.tv_sec = (long int)timeOutSecs; + timeOutSecs -= (int)timeOutSecs; + long int timeOutUsecs = timeOutSecs * 1000000; + stTimeOut.tv_usec = timeOutUsecs; + int descriptorReady = select(inSocket + 1, &stReadFDS, NULL, NULL, &stTimeOut); +// printf("stTimeOut.tv_sec = %ld, stTimeOut.tv_usec = %ld, descriptorReady: \n", stTimeOut.tv_sec, stTimeOut.tv_usec, descriptorReady); +// return descriptorReady > 0 ? (timeOutUsecs-stTimeOut.tv_usec) : descriptorReady; + return descriptorReady > 0 ? 1 : descriptorReady; } int UdpServer::read(//Returns the number of bytes read, or -1 if there was an error. @@ -92,26 +92,26 @@ int UdpServer::read(//Returns the number of bytes read, or -1 if there was an er int maxBytesToRead, bool blockUntilSpecifiedAmountHasArrived) { - if(enabled==false) + if(enabled == false) return -1; FD_ZERO(&stReadFDS); FD_SET(inSocket, &stReadFDS); - int descriptorReady= select(inSocket+1, &stReadFDS, NULL, NULL, &stZeroTimeOut); //TODO: this is not JUCE-compliant - if(descriptorReady<0){ //an error occurred + int descriptorReady = select(inSocket + 1, &stReadFDS, NULL, NULL, &stZeroTimeOut); //TODO: this is not JUCE-compliant + if(descriptorReady < 0){ //an error occurred return -1; } - int numberOfBytes=0; + int numberOfBytes = 0; // do { if (FD_ISSET(inSocket, &stReadFDS)) { fromLength = sizeof(from); numberOfBytes += recvfrom(inSocket, destBuffer, maxBytesToRead - numberOfBytes, 0, (struct sockaddr*)&from, &fromLength); - if(numberOfBytes<0) + if(numberOfBytes < 0) return -1; } } -// while (blockUntilSpecifiedAmountHasArrived && numberOfBytes==maxBytesToRead); +// while (blockUntilSpecifiedAmountHasArrived && numberOfBytes == maxBytesToRead); return numberOfBytes; } int UdpServer::getLastRecvPort() @@ -128,15 +128,15 @@ int UdpServer::empty(){ return empty(0); } int UdpServer::empty(int maxCount){ - int count=0; + int count = 0; int n; do { - if(waitUntilReady(true, 0)==0) + if(waitUntilReady(true, 0) == 0) return 0; float waste; - n=read(&waste, sizeof(float), false); + n = read(&waste, sizeof(float), false); count++; - } while (n>0 && (maxCount<=0 || maxCount 0 && (maxCount <= 0 || maxCount < count)); printf("socket emptied with %d reads\n", count); return count; } From a5bde776d4f9b2533016d0b3b486c0874c6d14cb Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 21 Apr 2023 13:53:33 +0000 Subject: [PATCH 004/188] UdpServer: removed unnecessary variables and memory leak --- libraries/UdpServer/UdpServer.cpp | 5 +---- libraries/UdpServer/UdpServer.h | 3 --- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/libraries/UdpServer/UdpServer.cpp b/libraries/UdpServer/UdpServer.cpp index 637157bf8..1a22ed03e 100644 --- a/libraries/UdpServer/UdpServer.cpp +++ b/libraries/UdpServer/UdpServer.cpp @@ -25,12 +25,9 @@ bool UdpServer::setup(int aPort){ enabled = false; return false; } - length = sizeof(server); server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; enabled = bindToPort(aPort); - wasteBufferSize = 2048; - wasteBuffer = malloc(wasteBufferSize); memset(&stTimeOut, 0, sizeof(struct timeval)); return enabled; } @@ -42,7 +39,7 @@ bool UdpServer::bindToPort(int aPort){ return false; } server.sin_port = htons(port); - if (bind(inSocket, (struct sockaddr *)&server, length) < 0){ + if (bind(inSocket, (struct sockaddr *)&server, sizeof(server)) < 0){ enabled = false; return false; } diff --git a/libraries/UdpServer/UdpServer.h b/libraries/UdpServer/UdpServer.h index 9843b0a6d..a64b8b92e 100644 --- a/libraries/UdpServer/UdpServer.h +++ b/libraries/UdpServer/UdpServer.h @@ -27,9 +27,6 @@ class UdpServer{ struct timeval stZeroTimeOut; fd_set stReadFDS; int size; - void *wasteBuffer; - int wasteBufferSize; - int length; socklen_t fromLength; struct sockaddr_in from; public: From fd35d48b9864799bb5579dfc7fd76e1b5936ecfb Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 21 Apr 2023 14:12:51 +0000 Subject: [PATCH 005/188] UdpServer: removed more unnecessary instance variables, factored out initialisation of fd_set --- libraries/UdpServer/UdpServer.cpp | 23 ++++++++++++++--------- libraries/UdpServer/UdpServer.h | 5 +---- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/libraries/UdpServer/UdpServer.cpp b/libraries/UdpServer/UdpServer.cpp index 1a22ed03e..ad81b48aa 100644 --- a/libraries/UdpServer/UdpServer.cpp +++ b/libraries/UdpServer/UdpServer.cpp @@ -18,8 +18,6 @@ UdpServer::~UdpServer(){ }; bool UdpServer::setup(int aPort){ enabled = true; - stZeroTimeOut.tv_sec = 0; //set timeout to 0 - stZeroTimeOut.tv_usec = 0; inSocket = socket(AF_INET, SOCK_DGRAM, 0); if(inSocket < 0) { enabled = false; @@ -28,7 +26,6 @@ bool UdpServer::setup(int aPort){ server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; enabled = bindToPort(aPort); - memset(&stTimeOut, 0, sizeof(struct timeval)); return enabled; } @@ -65,15 +62,19 @@ void UdpServer::close(){ int UdpServer::waitUntilReady(bool readyForReading, int timeoutMsecs){ return waitUntilReady(timeoutMsecs); } +#define FD_INIT(fd, fds) \ + FD_ZERO(&fds); \ + FD_SET(fd, &fds); + int UdpServer::waitUntilReady(int timeoutMsecs){ -// If the socket is ready on return, this returns 1. If it times-out before the socket becomes ready, it returns 0. If an error occurs, it returns -1. if(enabled == false) return -1; + fd_set stReadFDS; + FD_INIT(inSocket, stReadFDS); if(timeoutMsecs < 0) return select(inSocket + 1, &stReadFDS, NULL, NULL, NULL); //calling this with a NULL timeout will block indefinitely - FD_ZERO(&stReadFDS); - FD_SET(inSocket, &stReadFDS); float timeOutSecs = timeoutMsecs * 0.001; + struct timeval stTimeOut; stTimeOut.tv_sec = (long int)timeOutSecs; timeOutSecs -= (int)timeOutSecs; long int timeOutUsecs = timeOutSecs * 1000000; @@ -91,9 +92,13 @@ int UdpServer::read(//Returns the number of bytes read, or -1 if there was an er { if(enabled == false) return -1; - FD_ZERO(&stReadFDS); - FD_SET(inSocket, &stReadFDS); - int descriptorReady = select(inSocket + 1, &stReadFDS, NULL, NULL, &stZeroTimeOut); //TODO: this is not JUCE-compliant + fd_set stReadFDS; + FD_INIT(inSocket, stReadFDS); + struct timeval stZeroTimeOut = { + .tv_sec = 0, + .tv_usec = 0, + }; + int descriptorReady = select(inSocket + 1, &stReadFDS, NULL, NULL, &stZeroTimeOut); if(descriptorReady < 0){ //an error occurred return -1; } diff --git a/libraries/UdpServer/UdpServer.h b/libraries/UdpServer/UdpServer.h index a64b8b92e..c83f1e315 100644 --- a/libraries/UdpServer/UdpServer.h +++ b/libraries/UdpServer/UdpServer.h @@ -20,12 +20,9 @@ class UdpServer{ private: int port; - int enabled; + int enabled = false; int inSocket = -1; struct sockaddr_in server; - struct timeval stTimeOut; - struct timeval stZeroTimeOut; - fd_set stReadFDS; int size; socklen_t fromLength; struct sockaddr_in from; From 98c4d6935acda3bd544fb0933fa98d291512b722 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 21 Apr 2023 14:17:29 +0000 Subject: [PATCH 006/188] UdpServer: re-enabled (and fixed) blockUntilSpecifiedAmountHasArrived --- libraries/UdpServer/UdpServer.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries/UdpServer/UdpServer.cpp b/libraries/UdpServer/UdpServer.cpp index ad81b48aa..bfd24d92b 100644 --- a/libraries/UdpServer/UdpServer.cpp +++ b/libraries/UdpServer/UdpServer.cpp @@ -103,17 +103,17 @@ int UdpServer::read(//Returns the number of bytes read, or -1 if there was an er return -1; } int numberOfBytes = 0; -// do + do { if (FD_ISSET(inSocket, &stReadFDS)) { fromLength = sizeof(from); - numberOfBytes += recvfrom(inSocket, destBuffer, maxBytesToRead - numberOfBytes, 0, (struct sockaddr*)&from, &fromLength); + numberOfBytes += recvfrom(inSocket, ((char*)destBuffer) + numberOfBytes, maxBytesToRead - numberOfBytes, 0, (struct sockaddr*)&from, &fromLength); if(numberOfBytes < 0) return -1; } } -// while (blockUntilSpecifiedAmountHasArrived && numberOfBytes == maxBytesToRead); + while (blockUntilSpecifiedAmountHasArrived && numberOfBytes < maxBytesToRead); return numberOfBytes; } int UdpServer::getLastRecvPort() From 521a0ac3c666571874c002b57dfe4b947946ce1d Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 21 Apr 2023 14:31:58 +0000 Subject: [PATCH 007/188] NIT: UdpServer: check for !enabled instead --- libraries/UdpServer/UdpServer.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/UdpServer/UdpServer.cpp b/libraries/UdpServer/UdpServer.cpp index bfd24d92b..306b29c1e 100644 --- a/libraries/UdpServer/UdpServer.cpp +++ b/libraries/UdpServer/UdpServer.cpp @@ -67,7 +67,7 @@ int UdpServer::waitUntilReady(bool readyForReading, int timeoutMsecs){ FD_SET(fd, &fds); int UdpServer::waitUntilReady(int timeoutMsecs){ - if(enabled == false) + if(!enabled) return -1; fd_set stReadFDS; FD_INIT(inSocket, stReadFDS); @@ -90,7 +90,7 @@ int UdpServer::read(//Returns the number of bytes read, or -1 if there was an er int maxBytesToRead, bool blockUntilSpecifiedAmountHasArrived) { - if(enabled == false) + if(!enabled) return -1; fd_set stReadFDS; FD_INIT(inSocket, stReadFDS); From 7ea1a428b924bc8538ef52acf2c3c5268916f5b5 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 21 Apr 2023 14:33:38 +0000 Subject: [PATCH 008/188] UdpServer: removed bindToPort() which was anyhow not working. Also throwing if the constructor fails. --- libraries/UdpServer/UdpServer.cpp | 37 +++++++++++-------------------- libraries/UdpServer/UdpServer.h | 5 ++--- 2 files changed, 15 insertions(+), 27 deletions(-) diff --git a/libraries/UdpServer/UdpServer.cpp b/libraries/UdpServer/UdpServer.cpp index 306b29c1e..92fde90a9 100644 --- a/libraries/UdpServer/UdpServer.cpp +++ b/libraries/UdpServer/UdpServer.cpp @@ -5,43 +5,32 @@ * Author: giulio moro */ #include "UdpServer.h" +#include void UdpServer::cleanup(){ close(); } -UdpServer::UdpServer(int aPort){ - setup(aPort); +UdpServer::UdpServer(unsigned int port){ + if(!setup(port)) + throw std::runtime_error("UdpServer: could not bind to port " + std::to_string(port)); }; UdpServer::UdpServer(){} UdpServer::~UdpServer(){ cleanup(); }; -bool UdpServer::setup(int aPort){ - enabled = true; +bool UdpServer::setup(unsigned int port){ + close(); inSocket = socket(AF_INET, SOCK_DGRAM, 0); - if(inSocket < 0) { - enabled = false; - return false; - } + if(inSocket < 0) + return enabled = false; server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; - enabled = bindToPort(aPort); - return enabled; -} - -bool UdpServer::bindToPort(int aPort){ - port = aPort; - if(port < 1){ - enabled = false; - return false; - } + if(port < 1 || port >= 65536) + return enabled = false; server.sin_port = htons(port); - if (bind(inSocket, (struct sockaddr *)&server, sizeof(server)) < 0){ - enabled = false; - return false; - } - enabled = true; - return true; + if(bind(inSocket, (struct sockaddr *)&server, sizeof(server)) < 0) + return enabled = false; + return enabled = true; } int UdpServer::getBoundPort() const { diff --git a/libraries/UdpServer/UdpServer.h b/libraries/UdpServer/UdpServer.h index c83f1e315..08f67d257 100644 --- a/libraries/UdpServer/UdpServer.h +++ b/libraries/UdpServer/UdpServer.h @@ -28,15 +28,14 @@ class UdpServer{ struct sockaddr_in from; public: UdpServer(); - UdpServer(int aPort); + UdpServer(unsigned int port); ~UdpServer(); - bool setup(int aPort); + bool setup(unsigned int aPort); void cleanup(); /** * Get the port that the server is currently listening on */ int getBoundPort() const; - bool bindToPort(int aPort); /** * Reads bytes from the socket. * From 0bd6d7a6466d665865b5498242a3e258ac8bae9c Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 21 Apr 2023 14:47:33 +0000 Subject: [PATCH 009/188] UdpServer: further removing unused instance variables, simplified includes --- libraries/UdpServer/UdpServer.cpp | 12 +++++------- libraries/UdpServer/UdpServer.h | 18 ------------------ 2 files changed, 5 insertions(+), 25 deletions(-) diff --git a/libraries/UdpServer/UdpServer.cpp b/libraries/UdpServer/UdpServer.cpp index 92fde90a9..d2ca4d025 100644 --- a/libraries/UdpServer/UdpServer.cpp +++ b/libraries/UdpServer/UdpServer.cpp @@ -1,11 +1,9 @@ -/* - * udpServer.cpp - * - * Created on: 19 May 2015 - * Author: giulio moro - */ #include "UdpServer.h" #include +#include +#include +#include +#include void UdpServer::cleanup(){ close(); @@ -96,7 +94,7 @@ int UdpServer::read(//Returns the number of bytes read, or -1 if there was an er { if (FD_ISSET(inSocket, &stReadFDS)) { - fromLength = sizeof(from); + socklen_t fromLength = sizeof(from); numberOfBytes += recvfrom(inSocket, ((char*)destBuffer) + numberOfBytes, maxBytesToRead - numberOfBytes, 0, (struct sockaddr*)&from, &fromLength); if(numberOfBytes < 0) return -1; diff --git a/libraries/UdpServer/UdpServer.h b/libraries/UdpServer/UdpServer.h index 08f67d257..ed8022852 100644 --- a/libraries/UdpServer/UdpServer.h +++ b/libraries/UdpServer/UdpServer.h @@ -1,21 +1,5 @@ -/* - * udpServer.h - * - * Created on: 19 May 2015 - * Author: giulio moro - */ #pragma once - -#include -#include #include -#include -#include -#include -#include -#include -#include -#include class UdpServer{ private: @@ -23,8 +7,6 @@ class UdpServer{ int enabled = false; int inSocket = -1; struct sockaddr_in server; - int size; - socklen_t fromLength; struct sockaddr_in from; public: UdpServer(); From 4f1bd6d5cea6756bdb704435d4ef1f037be561e6 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 12 May 2023 10:41:19 -0500 Subject: [PATCH 010/188] Bela.h: added support for printf-style compiler warnings --- include/Bela.h | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/include/Bela.h b/include/Bela.h index ef00a56c4..4bbb0f2cd 100644 --- a/include/Bela.h +++ b/include/Bela.h @@ -96,10 +96,17 @@ extern "C" // these functions are currently provided by xenomai. // We put these declarations here so we do not have to include // Xenomai specific files -int rt_printf(const char *format, ...); -int rt_fprintf(FILE *stream, const char *format, ...); -int rt_vprintf(const char *format, va_list ap); -int rt_vfprintf(FILE *stream, const char *format, va_list ap); +// use attributes to provide printf-style compiler warnings +#ifdef __GNUC__ +#define _ATTRIBUTE(attrs) __attribute__ (attrs) +#else +#define _ATTRIBUTE(attrs) +#endif + +int rt_printf(const char *format, ...) _ATTRIBUTE ((__format__ (__printf__, 1, 2))); +int rt_fprintf(FILE *stream, const char *format, ...) _ATTRIBUTE ((__format__ (__printf__, 2, 3))); +int rt_vprintf(const char *format, va_list ap) _ATTRIBUTE ((__format__ (__printf__, 1, 0))); +int rt_vfprintf(FILE *stream, const char *format, va_list ap) _ATTRIBUTE ((__format__ (__printf__, 2, 0))); /** * A type of Bela hardware. From ea7a398ba01c4067feed001530a684bcca300dd1 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 23 May 2023 14:07:38 +0000 Subject: [PATCH 011/188] Spi_Codec: enable reset pin of ADS816x. --- core/Spi_Codec.cpp | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/core/Spi_Codec.cpp b/core/Spi_Codec.cpp index 61fd8510e..35e461881 100644 --- a/core/Spi_Codec.cpp +++ b/core/Spi_Codec.cpp @@ -194,8 +194,20 @@ int Spi_Codec::initCodec(){ int Spi_Codec::startAudio(int shouldBeReady){ // Enable PLL - return writeRegister(REG_PLL_CLK_CONTROL_0, 0x9C); - // TODO: wait till we are ready + if(writeRegister(REG_PLL_CLK_CONTROL_0, 0x9C)) + return 1; + // when combined with Bela cape rev C, we need to enable the + // ADC by toggling its reset pin. As this pin (P8.32) is already reserved + // by us as part of the SPI GPIO device, we can set it here regardless + // of the actual board we are running on. + const size_t kAds816xReset = 11; + if(gpio_export(kAds816xReset)) + return 1; + if(gpio_set_dir(kAds816xReset, OUTPUT_PIN)) + return 1; + if(gpio_set_value(kAds816xReset, HIGH)) + return 1; + return 0; } int Spi_Codec::stopAudio(){ From 21eaac1b40e4474e1b47637ef64b52a243ec25f0 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Wed, 31 May 2023 14:42:18 +0000 Subject: [PATCH 012/188] When ADS816x, ensure you sleep or otherwise wait enough between reset the ADS816x and starting the PRU --- core/Es9080_Codec.cpp | 7 +++++++ core/PRU.cpp | 4 ++++ core/Spi_Codec.cpp | 6 ++++++ 3 files changed, 17 insertions(+) diff --git a/core/Es9080_Codec.cpp b/core/Es9080_Codec.cpp index b53b64af1..53eb14234 100644 --- a/core/Es9080_Codec.cpp +++ b/core/Es9080_Codec.cpp @@ -42,10 +42,17 @@ Es9080_Codec::Es9080_Codec(int i2cBus, int i2cAddress, AudioCodecParams::ClockSo // polarity also changes below params.bitDelay = (kClockSourceMcasp == params.wclk) ? 1 : 0; initI2C_RW(i2cBus, i2cAddress, -1); + + // toggle reset pin gpio.open(resetPin, Gpio::OUTPUT); gpio.clear(); usleep(1000); gpio.set(); + // The ADS816x is also wired on this reset pin, so we wait: + // ADS8166 datasheet 6.7 Switching characteristics + // Delay time: RST rising to READY rising is 4ms MAX + // However, there is typically enough time between here and the moment + // the PRU start, so we don't have to explicitly wait here } Es9080_Codec::~Es9080_Codec() diff --git a/core/PRU.cpp b/core/PRU.cpp index d028e7aae..25ab71673 100644 --- a/core/PRU.cpp +++ b/core/PRU.cpp @@ -442,6 +442,10 @@ int PRU::initialise(BelaHw newBelaHw, int pru_num, bool uniformSampleRate, int m adcNrstPin.clear(); usleep(1000); adcNrstPin.set(); + // ADS8166 datasheet 6.7 Switching characteristics + // Delay time: RST rising to READY rising is 4ms MAX + // However, there is typically enough time between here and the moment + // the PRU start, so we don't have to explicitly wait here } } diff --git a/core/Spi_Codec.cpp b/core/Spi_Codec.cpp index 35e461881..f6b00f808 100644 --- a/core/Spi_Codec.cpp +++ b/core/Spi_Codec.cpp @@ -205,8 +205,14 @@ int Spi_Codec::startAudio(int shouldBeReady){ return 1; if(gpio_set_dir(kAds816xReset, OUTPUT_PIN)) return 1; + if(gpio_set_value(kAds816xReset, LOW)) + return 1; + usleep(1000); if(gpio_set_value(kAds816xReset, HIGH)) return 1; + // ADS8166 datasheet 6.7 Switching characteristics + // Delay time: RST rising to READY rising is 4ms MAX + usleep(4000); return 0; } From 255962397c5244c1ed2ee2e6a3207a26106f3f5a Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 2 Jun 2023 00:13:48 +0000 Subject: [PATCH 013/188] default_libpd_render: BELA_LIBBPD_SERIAL: added support for raw bytes --- core/default_libpd_render.cpp | 50 ++++++++++++++++++++++++++--------- 1 file changed, 38 insertions(+), 12 deletions(-) diff --git a/core/default_libpd_render.cpp b/core/default_libpd_render.cpp index 1c06d9953..43b30a67f 100644 --- a/core/default_libpd_render.cpp +++ b/core/default_libpd_render.cpp @@ -168,6 +168,7 @@ std::string gSerialId; int gSerialEom; enum SerialType { kSerialFloats, + kSerialBytes, kSerialSymbol, kSerialSymbols, } gSerialType = kSerialFloats; @@ -593,27 +594,36 @@ void Bela_messageHook(const char *source, const char *symbol, int argc, t_atom * { if( argc < 5 - || !libpd_is_symbol(argv + 0) - || !libpd_is_symbol(argv + 1) - || !libpd_is_float(argv + 2) - || !libpd_is_symbol(argv + 3) - || !libpd_is_symbol(argv + 4) + || !libpd_is_symbol(argv + 0) // serial_id + || !libpd_is_symbol(argv + 1) // device + || !libpd_is_float(argv + 2) // baudrate + || !(libpd_is_symbol(argv + 3) || libpd_is_float(argv + 3)) // EOM + || !libpd_is_symbol(argv + 4) // tyoe ) { - fprintf(stderr, "Invalid bela_setSerial arguments. Should be: `new serial_id device baudrate EOM type`, where `EOM` is one of `newline` or `none` and `type` is one of `floats`, `symbol`, `symbols`\n"); + fprintf(stderr, "Invalid bela_setSerial arguments. Should be:\n" + "`new serial_id device baudrate EOM type`,\n" + "where `EOM` is one of `newline` or `none` or a character (expressed as an integer" + " between 0 and 255)\n" + "and `type` is one of `bytes`, `floats`, `symbol`, `symbols`\n"); return; } gSerialId = libpd_get_symbol(argv + 0); const char* device = libpd_get_symbol(argv + 1); unsigned int baudrate = libpd_get_float(argv + 2); - const char* eom = libpd_get_symbol(argv + 3); - if(0 == strcmp(eom, "newline")) - gSerialEom = '\n'; - else - gSerialEom = -1; + gSerialEom = -1; + if(libpd_is_symbol(argv + 3)) { + const char* eom = libpd_get_symbol(argv + 3); + if(0 == strcmp(eom, "newline")) + gSerialEom = '\n'; + } else if(libpd_is_float(argv + 3)) { + gSerialEom = libpd_get_float(argv + 3); + } const char* type = libpd_get_symbol(argv + 4); if(0 == strcmp("floats", type)) gSerialType = kSerialFloats; + else if(0 == strcmp("bytes", type)) + gSerialType = kSerialBytes; else if(0 == strcmp("symbol", type)) gSerialType = kSerialSymbol; else if(0 == strcmp("symbols", type)) @@ -1135,6 +1145,22 @@ void render(BelaContext *context, void *userData) if(kSerialSymbol == gSerialType) { libpd_symbol(rec, data); + } else if(kSerialBytes == gSerialType) { + if(gSerialEom >= 0) { + // messages are separated: send as a list + libpd_start_message(h.dataSize); + for(size_t n = 0; n < h.dataSize; ++n) + libpd_add_float(data[n]); + libpd_finish_message(rec, id); + } else { + // messages are not separated: send one byte at a time + for(size_t n = 0; n < h.dataSize; ++n) + { + libpd_start_message(h.dataSize); + libpd_add_float(data[n]); + libpd_finish_message(rec, id); + } + } } else { unsigned int nTokens = 1; const uint8_t separators[] = { ' ', '\0'}; @@ -1177,7 +1203,7 @@ void render(BelaContext *context, void *userData) start = n + 1; } } - libpd_finish_message("bela_serial", id); + libpd_finish_message(rec, id); } } waitingFor = kHeader; From 1e116c15d3747b54737ce68446e5928da3338b3e Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 2 Jun 2023 00:14:34 +0000 Subject: [PATCH 014/188] default_libpd_render: fixed argument to rt_printf --- core/default_libpd_render.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/default_libpd_render.cpp b/core/default_libpd_render.cpp index 43b30a67f..a935538d1 100644 --- a/core/default_libpd_render.cpp +++ b/core/default_libpd_render.cpp @@ -742,7 +742,7 @@ void Bela_messageHook(const char *source, const char *symbol, int argc, t_atom * value = 0; if(Trill::prescalerMax < value) value = Trill::prescalerMax; - rt_printf("bela_setTrill prescaler value out of range, clipping to %u\n", value); + rt_printf("bela_setTrill prescaler value out of range, clipping to %.0f\n", value); } gTouchSensors[idx].second->setPrescaler(value); } From f6f258787301283b713a24a0710757ba34812f8c Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 18 Jul 2023 13:44:59 +0000 Subject: [PATCH 015/188] WSServer: pass address and identifier to each callback. Amended Gui and Scope accordingly --- libraries/Gui/Gui.cpp | 30 +++++++++++++++--------------- libraries/Gui/Gui.h | 13 +++++++------ libraries/Scope/Scope.cpp | 6 +++--- libraries/WSServer/WSServer.cpp | 24 +++++++++++++++--------- libraries/WSServer/WSServer.h | 7 ++++++- 5 files changed, 46 insertions(+), 34 deletions(-) diff --git a/libraries/Gui/Gui.cpp b/libraries/Gui/Gui.cpp index c52285f1f..a567a276c 100644 --- a/libraries/Gui/Gui.cpp +++ b/libraries/Gui/Gui.cpp @@ -20,27 +20,27 @@ int Gui::setup(unsigned int port, std::string address) ws_server = std::unique_ptr(new WSServer()); ws_server->setup(port); ws_server->addAddress(_addressData, - [this](std::string address, void* buf, int size) + [this](const std::string& address, const WSServerDetails* id, const unsigned char* buf, size_t size) { - ws_onData((const char*) buf, size); + ws_onData(address, id, buf, size); }, nullptr, nullptr, true); ws_server->addAddress(_addressControl, // onData() - [this](std::string address, void* buf, int size) + [this](const std::string& address, const WSServerDetails* id, const unsigned char* buf, size_t size) { - ws_onControlData((const char*) buf, size); + ws_onControlData(address, id, buf, size); }, // onConnect() - [this](std::string address) + [this](const std::string& address, const WSServerDetails* id) { - ws_connect(); + ws_connect(address, id); }, // onDisconnect() - [this](std::string address) + [this](const std::string& address, const WSServerDetails* id) { - ws_disconnect(); + ws_disconnect(address, id); } ); return 0; @@ -58,7 +58,7 @@ int Gui::setup(std::string projectName, unsigned int port, std::string address) * with initial settings. * The client replies with 'connection-ack', which should be parsed accordingly. */ -void Gui::ws_connect() +void Gui::ws_connect(const std::string& address, const WSServerDetails* id) { // send connection JSON JSONObject root; @@ -77,19 +77,19 @@ void Gui::ws_connect() * Called when websocket is disconnected. * */ -void Gui::ws_disconnect() +void Gui::ws_disconnect(const std::string& address, const WSServerDetails* id) { wsIsConnected = false; } /* - * on_data callback for scope_control websocket + * on_data callback for gui_control websocket * runs on the (linux priority) seasocks thread */ -void Gui::ws_onControlData(const char* data, unsigned int size) +void Gui::ws_onControlData(const std::string& address, const WSServerDetails* id, const unsigned char* data, unsigned int size) { // parse the data into a JSONValue - JSONValue *value = JSON::Parse(data); + JSONValue *value = JSON::Parse((const char*)data); if (value == NULL || !value->IsObject()){ fprintf(stderr, "Could not parse JSON:\n%s\n", data); return; @@ -111,9 +111,9 @@ void Gui::ws_onControlData(const char* data, unsigned int size) return; } -void Gui::ws_onData(const char* data, unsigned int size) +void Gui::ws_onData(const std::string& address, const WSServerDetails* id, const unsigned char* data, size_t size) { - if(customOnData && !customOnData(data, size, binaryCallbackArg)) + if(customOnData && !customOnData(address, id, data, size, binaryCallbackArg)) { return; } diff --git a/libraries/Gui/Gui.h b/libraries/Gui/Gui.h index 4bb93055a..a83bd4b61 100644 --- a/libraries/Gui/Gui.h +++ b/libraries/Gui/Gui.h @@ -10,6 +10,7 @@ // forward declarations class WSServer; +class WSServerDetails; class Gui { @@ -20,10 +21,10 @@ class Gui bool wsIsConnected = false; - void ws_connect(); - void ws_disconnect(); - void ws_onControlData(const char* data, unsigned int size); - void ws_onData(const char* data, unsigned int size); + void ws_connect(const std::string& address, const WSServerDetails* id); + void ws_disconnect(const std::string& address, const WSServerDetails* id); + void ws_onControlData(const std::string& address, const WSServerDetails* id, const unsigned char* data, size_t size); + void ws_onData(const std::string& address, const WSServerDetails* id, const unsigned char* data, size_t size); int doSendBuffer(const char* type, unsigned int bufferId, const void* data, size_t size); unsigned int _port; @@ -33,7 +34,7 @@ class Gui // User defined functions std::function customOnControlData; - std::function customOnData; + std::function customOnData; void* controlCallbackArg = nullptr; void* binaryCallbackArg = nullptr; @@ -107,7 +108,7 @@ class Gui * @param callbackArg: Pointer to be passed to the * callback. **/ - void setBinaryDataCallback(std::function callback, void* callbackArg=nullptr){ + void setBinaryDataCallback(std::function callback, void* callbackArg=nullptr){ customOnData = callback; binaryCallbackArg = callbackArg; }; diff --git a/libraries/Scope/Scope.cpp b/libraries/Scope/Scope.cpp index 98dbe7ec4..28829b099 100644 --- a/libraries/Scope/Scope.cpp +++ b/libraries/Scope/Scope.cpp @@ -57,13 +57,13 @@ void Scope::setup(unsigned int _numChannels, float _sampleRate){ ws_server->setup(5432); ws_server->addAddress("scope_data", nullptr, nullptr, nullptr, true); ws_server->addAddress("scope_control", - [this](std::string address, void* buf, int size){ + [this](const std::string& address, const WSServerDetails* id, const unsigned char* buf, size_t size){ scope_control_data((const char*) buf); }, - [this](std::string address){ + [this](const std::string& address, const WSServerDetails* id){ scope_control_connected(); }, - [this](std::string address){ + [this](const std::string& address, const WSServerDetails* id){ stop(); }); diff --git a/libraries/WSServer/WSServer.cpp b/libraries/WSServer/WSServer.cpp index 47f271973..c8bf39497 100644 --- a/libraries/WSServer/WSServer.cpp +++ b/libraries/WSServer/WSServer.cpp @@ -18,25 +18,26 @@ struct WSServerDataHandler : seasocks::WebSocket::Handler { std::shared_ptr server; std::set connections; std::string address; - std::function on_receive; - std::function on_connect; - std::function on_disconnect; + std::function on_receive; + std::function on_connect; + std::function on_disconnect; bool binary; void onConnect(seasocks::WebSocket *socket) override { connections.insert(socket); - if(on_connect) - on_connect(address); + if(on_connect) { + on_connect(address, (WSServerDetails*)socket); + } } void onData(seasocks::WebSocket *socket, const char *data) override { - on_receive(address, (void*)data, std::strlen(data)); + on_receive(address, (WSServerDetails*)socket, (const unsigned char*)data, std::strlen(data)); } void onData(seasocks::WebSocket *socket, const uint8_t* data, size_t size) override { - on_receive(address, (void*)data, size); + on_receive(address, (WSServerDetails*)socket, data, size); } void onDisconnect(seasocks::WebSocket *socket) override { connections.erase(socket); if (on_disconnect) - on_disconnect(address); + on_disconnect(address, (WSServerDetails*)socket); } }; @@ -72,7 +73,12 @@ void WSServer::setup(int _port) { server_task->schedule(); } -void WSServer::addAddress(std::string _address, std::function on_receive, std::function on_connect, std::function on_disconnect, bool binary){ +void WSServer::addAddress(const std::string& _address, + std::function on_receive, + std::function on_connect, + std::function on_disconnect, + bool binary) +{ auto handler = std::make_shared(); handler->server = server; handler->address = _address; diff --git a/libraries/WSServer/WSServer.h b/libraries/WSServer/WSServer.h index 5c6da38cf..38fb785d0 100644 --- a/libraries/WSServer/WSServer.h +++ b/libraries/WSServer/WSServer.h @@ -13,6 +13,7 @@ namespace seasocks{ } class AuxTaskNonRT; struct WSServerDataHandler; +class WSServerDetails; class WSServer{ friend struct WSServerDataHandler; @@ -23,7 +24,11 @@ class WSServer{ void setup(int port); - void addAddress(std::string address, std::function on_receive = nullptr, std::function on_connect = nullptr, std::function on_disconnect = nullptr, bool binary = false); + void addAddress(const std::string& address, + std::function on_receive = nullptr, + std::function on_connect = nullptr, + std::function on_disconnect = nullptr, + bool binary = false); int sendNonRt(const char* address, const char* str); int sendNonRt(const char* address, const void* buf, unsigned int size); From 53313d414c76b638d393fe65066d2bdfb0617ddc Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 18 Jul 2023 01:06:16 +0000 Subject: [PATCH 016/188] Gui: better handle num of connections by keeping track of individual connection IDs --- examples/Gui/graph/render.cpp | 2 +- libraries/Gui/Gui.cpp | 12 ++++++------ libraries/Gui/Gui.h | 6 +++--- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/examples/Gui/graph/render.cpp b/examples/Gui/graph/render.cpp index a04b968dc..70bb9935d 100755 --- a/examples/Gui/graph/render.cpp +++ b/examples/Gui/graph/render.cpp @@ -94,7 +94,7 @@ void render(BelaContext *context, void *userData) // Send data to GUI for visualisation once enough frames have elapsed if(sendFramesElapsed > gSendPeriod * context->analogSampleRate) { // If GUI is connected - if(gui.isConnected()) { + if(gui.numConnections()) { // send buffers gui.sendBuffer(0, gTimestamps); gui.sendBuffer(1, gVoltage); diff --git a/libraries/Gui/Gui.cpp b/libraries/Gui/Gui.cpp index a567a276c..092bed621 100644 --- a/libraries/Gui/Gui.cpp +++ b/libraries/Gui/Gui.cpp @@ -56,18 +56,16 @@ int Gui::setup(std::string projectName, unsigned int port, std::string address) * Called when websocket is connected. * Communication is started here with the server sending a 'connection' JSON object * with initial settings. - * The client replies with 'connection-ack', which should be parsed accordingly. + * The client replies with 'connection-reply', which should be parsed accordingly. */ void Gui::ws_connect(const std::string& address, const WSServerDetails* id) { + // TODO: this is currently sent to all clients, but it should only be sent to the new one // send connection JSON JSONObject root; root[L"event"] = new JSONValue(L"connection"); if(!_projectName.empty()) root[L"projectName"] = new JSONValue(_projectName); - - // Parse whatever needs to be parsed on connection - JSONValue *value = new JSONValue(root); sendControl(value); delete value; @@ -79,7 +77,8 @@ void Gui::ws_connect(const std::string& address, const WSServerDetails* id) */ void Gui::ws_disconnect(const std::string& address, const WSServerDetails* id) { - wsIsConnected = false; + if(wsConnections.count(id)) + wsConnections.erase(id); } /* @@ -104,7 +103,8 @@ void Gui::ws_onControlData(const std::string& address, const WSServerDetails* id if (root.find(L"event") != root.end() && root[L"event"]->IsString()){ std::wstring event = root[L"event"]->AsString(); if (event.compare(L"connection-reply") == 0){ - wsIsConnected = true; + if(!wsConnections.count(id)) + wsConnections.insert(id); } } delete value; diff --git a/libraries/Gui/Gui.h b/libraries/Gui/Gui.h index a83bd4b61..400984b2f 100644 --- a/libraries/Gui/Gui.h +++ b/libraries/Gui/Gui.h @@ -7,6 +7,7 @@ #include // for types in templates #include #include +#include // forward declarations class WSServer; @@ -18,8 +19,7 @@ class Gui std::vector _buffers; std::unique_ptr ws_server; - - bool wsIsConnected = false; + std::set wsConnections; void ws_connect(const std::string& address, const WSServerDetails* id); void ws_disconnect(const std::string& address, const WSServerDetails* id); @@ -56,7 +56,7 @@ class Gui int setup(std::string projectName, unsigned int port = 5555, std::string address = "gui"); void cleanup(); - bool isConnected(){ return wsIsConnected; }; + size_t numConnections(){ return wsConnections.size(); }; // BUFFERS /** From 32f34fd1e8e751e234749c06f047a7bccfbbafd8 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Wed, 19 Jul 2023 19:19:04 +0000 Subject: [PATCH 017/188] WriteFile: overhaul, removed C-style string manipulation, any reliance on Bela or Xenomai (well ... except for rt_fprintf()...), using std::thread and a std::mutex to manipulate the static constructor and properties. It could still use use some clarity around thread starting/stopping --- libraries/WriteFile/WriteFile.cpp | 215 +++++++++++++++--------------- libraries/WriteFile/WriteFile.h | 44 +++--- 2 files changed, 125 insertions(+), 134 deletions(-) diff --git a/libraries/WriteFile/WriteFile.cpp b/libraries/WriteFile/WriteFile.cpp index 576c2b454..335f99c7b 100644 --- a/libraries/WriteFile/WriteFile.cpp +++ b/libraries/WriteFile/WriteFile.cpp @@ -8,34 +8,69 @@ #include "WriteFile.h" #include // alternative to dirent.h to handle files in dirs #include +#include +#include +#include +#include +#include + //setupialise static members bool WriteFile::staticConstructed=false; -AuxiliaryTask WriteFile::writeAllFilesTask=NULL; -std::vector WriteFile::objAddrs(0); +std::vector WriteFile::objAddrs; bool WriteFile::threadRunning; bool WriteFile::threadScheduled; bool WriteFile::threadIsExiting; -int WriteFile::sleepTimeMs; + +class autojointhread { +public: + void setup(std::function fun) { + thread = std::thread(fun); + } + ~autojointhread() { + if(thread.joinable()) + { + thread.join(); + } + } + pthread_t native_handle() { + return thread.native_handle(); + } + bool joinable() { + return thread.joinable(); + } + void join() { + return thread.join(); + } +private: + std::thread thread; +}; +static autojointhread writeAllFilesThread; +static std::mutex mutex; void WriteFile::staticConstructor(){ - if(staticConstructed==true) + std::unique_lock lock(mutex); + if(staticConstructed) return; + // if previously running thread is exiting, wait for it + while(writeAllFilesThread.joinable()) { + lock.unlock(); + usleep(100000); + lock.lock(); + } staticConstructed=true; threadIsExiting=false; threadRunning=false; threadScheduled = false; - writeAllFilesTask = Bela_createAuxiliaryTask(WriteFile::run, 60, "writeAllFilesTask", NULL); + writeAllFilesThread.setup(&WriteFile::run); + sched_param sch = {}; + sch.sched_priority = 60; + pthread_setschedparam(writeAllFilesThread.native_handle(), SCHED_FIFO, &sch); } WriteFile::WriteFile(){ - format = NULL; - header = NULL; - footer = NULL; - stringBuffer = NULL; - _filename = NULL; }; -WriteFile::WriteFile(const char* filename, bool overwrite, bool append){ +WriteFile::WriteFile(const std::string& filename, bool overwrite, bool append){ setup(filename, overwrite, append); } @@ -44,39 +79,45 @@ WriteFile::~WriteFile(){ } void WriteFile::cleanup(){ - // this will disable all instances when - // you destroy the first one, but at least it's safe + std::unique_lock lock(mutex); + //write all that's left + writeOutput(true); + writeFooter(); + fflush(file); + fclose(file); + // remove from objAddrs list + auto it = std::find(objAddrs.begin(), objAddrs.end(), this); + if(it != objAddrs.end()) + objAddrs.erase(it); + if(objAddrs.size()) + return; + // if there are no instances left, stop the thread stopThread(); - while(threadRunning) - usleep(100000); - free(format); - free(header); - free(footer); - free(stringBuffer); - free(_filename); + staticConstructed = false; + lock.unlock(); + // let the thread run to completion + if(writeAllFilesThread.joinable()) + writeAllFilesThread.join(); } -char* WriteFile::generateUniqueFilename(const char* original) +std::string WriteFile::generateUniqueFilename(const std::string& original) { - int originalLen = strlen(original); + int originalLen = original.size(); - // search for a dot in the file (from the end) + // search for a dot in the file name (from the end) int dot = originalLen; for(int n = dot; n >= 0; --n) { if(original[n] == '.') dot = n; } - char temp[originalLen + 2]; int count = dot; - snprintf(temp, count + 1, "%s", original); // add a * before the dot - count += sprintf(temp + count, "*") - 1; - count += sprintf(temp + count + 1, "%s", original + dot); + std::string temp = std::string({original.begin(), original.begin() + dot}) + "*" + std::string({original.begin() + dot, original.end()}); // check how many log files are already there, and choose name according to this glob_t globbuf; - glob(temp, 0, NULL, &globbuf); + glob(temp.c_str(), 0, NULL, &globbuf); int logNum; int logMax = -1; @@ -91,51 +132,44 @@ char* WriteFile::generateUniqueFilename(const char* original) if(logMax == -1) { // use the same filename - char* out = (char*)malloc(sizeof(char) * (originalLen +1)); - strcpy(out, original); - return out; + return original; } else { // generate a new filename logNum = logMax + 1; // new index - count = snprintf(NULL, 0, "%d", logNum); - char* out = (char*)malloc(sizeof(char) * (count + originalLen + 1)); - count = dot; - snprintf(out, count + 1, "%s", original); - count += sprintf(out + count, "%d", logNum) - 1; - count += sprintf(out + count + 1, "%s", original + dot); - printf("File %s exists, writing to %s instead\n", original, out); + std::string out = std::string({original.begin(), original.begin() + dot}) + std::to_string(logNum) + std::string({original.begin() + dot, original.end()}); + printf("File %s exists, writing to %s instead\n", original.c_str(), out.c_str()); return out; } } -void WriteFile::setup(const char* filename, bool overwrite, bool append){ +void WriteFile::setup(const std::string& newFilename, bool overwrite, bool append){ + filename = newFilename; if(!overwrite) { - _filename = generateUniqueFilename(filename); - file = fopen(_filename, "w"); + filename = generateUniqueFilename(filename); + file = fopen(filename.c_str(), "w"); } else { - printf("Overwrite %s\n", filename); - _filename = (char*)malloc(sizeof(char) * (strlen(filename) + 1)); + printf("Overwrite %s\n", filename.c_str()); if(!append) { - file = fopen(filename, "w"); + file = fopen(filename.c_str(), "w"); } else { - file = fopen(filename, "a"); + file = fopen(filename.c_str(), "a"); } } - variableOpen = false; + fileType = kBinary; lineLength = 0; setEcho(false); textReadPointer = 0; binaryReadPointer = 0; writePointer = 0; - sleepTimeMs = 1; - stringBufferLength = 1000; - stringBuffer = (char*)malloc(sizeof(char) * (stringBufferLength)); + stringBuffer.resize(1000); setHeader("variable=[\n"); setFooter("];\n"); - staticConstructor(); //TODO: this line should be in the constructor, but cannot be because of a bug in Bela + staticConstructor(); + mutex.lock(); objAddrs.push_back(this); + mutex.unlock(); echoedLines = 0; echoPeriod = 1; } @@ -161,16 +195,17 @@ void WriteFile::setBufferSize(unsigned int newSize) buffer.resize(newSize); } -void WriteFile::print(const char* string){ +void WriteFile::print(const std::string& string){ + return; if(echo == true){ echoedLines++; if (echoedLines >= echoPeriod){ echoedLines = 0; - printf("%s", string); + printf("%s", string.c_str()); } } if(file != NULL && fileType != kBinary){ - fprintf(file, "%s", string); + fprintf(file, "%s", string.c_str()); } } @@ -178,15 +213,15 @@ void WriteFile::writeLine(){ if(echo == true || fileType != kBinary){ int stringBufferPointer = 0; for(unsigned int n = 0; n < formatTokens.size(); n++){ - int numOfCharsWritten = snprintf( &stringBuffer[stringBufferPointer], stringBufferLength - stringBufferPointer, - formatTokens[n], buffer[textReadPointer]); + int numOfCharsWritten = snprintf( &stringBuffer[stringBufferPointer], stringBuffer.size() - stringBufferPointer, + formatTokens[n].c_str(), buffer[textReadPointer]); stringBufferPointer += numOfCharsWritten; textReadPointer++; if(textReadPointer >= buffer.size()){ textReadPointer -= buffer.size(); } } - print(stringBuffer); + print({stringBuffer.begin(), stringBuffer.begin() + strlen(stringBuffer.data())}); } } @@ -197,7 +232,7 @@ void WriteFile::setLineLength(int newLineLength){ } void WriteFile::log(float value){ - if(fileType != kBinary && (format == NULL || buffer.size() == 0)) + if(fileType != kBinary && (!format.size() || !buffer.size())) return; buffer[writePointer] = value; writePointer++; @@ -206,7 +241,7 @@ void WriteFile::log(float value){ } if((fileType == kText && writePointer == textReadPointer - 1) || (fileType == kBinary && writePointer == binaryReadPointer - 1)){ - rt_fprintf(stderr, "WriteFile: %s pointers crossed, you should probably slow down your writing to disk\n", _filename); + rt_fprintf(stderr, "WriteFile: %s pointers crossed, you should probably slow down your writing to disk\n", filename.c_str()); } if(threadScheduled == false){ startThread(); @@ -219,15 +254,11 @@ void WriteFile::log(const float* array, int length){ } } -void WriteFile::setFormat(const char* newFormat){ - allocateAndCopyString(newFormat, &format); - for(unsigned int n = 0; n < formatTokens.size(); n++){ - free(formatTokens[n]); - } +void WriteFile::setFormat(const std::string& format){ formatTokens.clear(); int tokenStart = 0; bool firstToken = true; - for(unsigned int n = 0; n < strlen(format)+1; n++){ + for(unsigned int n = 0; n < format.size() + 1; n++){ if(format[n] == '%' && format[n + 1] == '%'){ n++; } else if (format[n] == '%' || format[n] == 0){ @@ -235,15 +266,10 @@ void WriteFile::setFormat(const char* newFormat){ firstToken = false; continue; } - char* string; unsigned int tokenLength = n - tokenStart; if(tokenLength == 0) continue; - string = (char*)malloc((1+tokenLength)*sizeof(char)); - for(unsigned int i = 0; i < tokenLength; i++){ - string[i] = format[tokenStart + i]; - } - string[tokenLength] = 0; + std::string string = {format.begin() + tokenStart, format.begin() + tokenStart + tokenLength}; formatTokens.push_back(string); tokenStart = n; } @@ -257,7 +283,6 @@ int WriteFile::getNumInstances(){ void WriteFile::startThread(){ threadScheduled = true; - Bela_scheduleAuxiliaryTask(writeAllFilesTask); } void WriteFile::stopThread(){ @@ -265,7 +290,7 @@ void WriteFile::stopThread(){ } bool WriteFile::threadShouldExit(){ - return(Bela_stopRequested() || threadIsExiting); + return threadIsExiting; } bool WriteFile::isThreadRunning(){ @@ -327,65 +352,39 @@ void WriteFile::writeOutput(bool flush){ } void WriteFile::writeAllOutputs(bool flush){ + std::lock_guard lock(mutex); for(unsigned int n = 0; n < objAddrs.size(); n++){ objAddrs[n] -> writeOutput(flush); } } -void WriteFile::writeAllHeaders(){ - for(unsigned int n = 0; n < objAddrs.size(); n++){ - objAddrs[n] -> writeHeader(); - } -} - -void WriteFile::writeAllFooters(){ - for(unsigned int n = 0; n < objAddrs.size(); n++){ - objAddrs[n] -> writeFooter(); - } -} - void WriteFile::writeHeader(){ print(header); } void WriteFile::writeFooter(){ print(footer); - fflush(file); - fclose(file); } -void WriteFile::setHeader(const char* newHeader){ - allocateAndCopyString(newHeader, &header); - sanitizeString(header); +void WriteFile::setHeader(const std::string& newHeader){ + header = sanitizeString(newHeader); } -void WriteFile::setFooter(const char* newFooter){ - allocateAndCopyString(newFooter, &footer); +void WriteFile::setFooter(const std::string& newFooter){ + footer = sanitizeString(newFooter); } -void WriteFile::sanitizeString(char* string){ - for(int unsigned n = 0; n < strlen(string); n++){ //purge %'s from the string - if(string[n] == '%'){ - string[n] = ' '; - } - } +std::string WriteFile::sanitizeString(const std::string& string){ + std::string ret = string; + std::replace(ret.begin(), ret.end(), '%', ' '); + return ret; } -void WriteFile::run(void* arg){ +void WriteFile::run(){ threadRunning = true; - printf("Running\n"); - writeAllHeaders(); while(threadShouldExit()==false){ writeAllOutputs(false); usleep(sleepTimeMs*1000); } - writeAllOutputs(true); - writeAllFooters(); // when ctrl-c is pressed, the last line is closed and the file is closed threadRunning = false; } - -void WriteFile::allocateAndCopyString(const char* source, char** destination){ - free(*destination); - *destination = (char*)malloc(sizeof(char) * (strlen(source) + 1)); - strcpy(*destination, source); -} diff --git a/libraries/WriteFile/WriteFile.h b/libraries/WriteFile/WriteFile.h index 86dcbe690..2a67fe81f 100644 --- a/libraries/WriteFile/WriteFile.h +++ b/libraries/WriteFile/WriteFile.h @@ -13,6 +13,7 @@ #include #include #include +#include typedef enum { kBinary, @@ -21,38 +22,31 @@ typedef enum { class WriteFile { private: - static AuxiliaryTask writeAllFilesTask; - bool echo; int echoedLines; int echoPeriod; - char *header; - char *footer; - char *stringBuffer; - int stringBufferLength; + std::string header; + std::string footer; + std::vector stringBuffer; std::vector buffer; int textReadPointer; int binaryReadPointer; int writePointer; - bool variableOpen; - char* format; + std::string format; int lineLength; WriteFileType fileType; - static int sleepTimeMs; FILE *file; - char* _filename; + std::string filename; + std::vector formatTokens; + bool echo; + static constexpr size_t sleepTimeMs = 5; void writeLine(); void writeHeader(); void writeFooter(); - void allocateAndCopyString(const char* source, char** destination); - void print(const char* string); - void printBinary(const char* string); + void print(const std::string& string); void setLineLength(int newLineLength); int getOffsetFromPointer(int aPointer); - std::vector formatTokens; - static void sanitizeString(char* string); - static void sanitizeString(char* string, int numberOfArguments); + static std::string sanitizeString(const std::string& string); static bool isThreadRunning(); - static bool auxiliaryTaskRunning; static bool threadShouldExit(); static bool threadIsExiting; static bool threadRunning; @@ -63,7 +57,7 @@ class WriteFile { void writeOutput(bool flush); public: WriteFile(); - WriteFile(const char* filename, bool overwrite, bool append); + WriteFile(const std::string& filename, bool overwrite, bool append); /** * Set the type of file to write, can be either kText or kBinary. @@ -100,19 +94,19 @@ class WriteFile { * Only %f is allowed (with modifiers). When in binary mode, * the specified format is used only for echoing to console. */ - void setFormat(const char* newFormat); + void setFormat(const std::string& newFormat); /** * Set one or more lines to be printed at the beginning of the file. * * This is ignored in binary mode. */ - void setHeader(const char* newHeader); + void setHeader(const std::string& newHeader); /** * Set one or more lines to be printed at the end of the file. * * This is ignored in binary mode. */ - void setFooter(const char* newFooter); + void setFooter(const std::string& newFooter); /** * Log one value to the file. @@ -129,7 +123,7 @@ class WriteFile { * If `overwrite` is false, existing files will not be overwritten * and the filename will be automatically incremented. */ - void setup(const char* filename, bool overwrite = false, bool append = false); + void setup(const std::string& filename, bool overwrite = false, bool append = false); /** * Gets the distance between the write and read pointers of @@ -147,12 +141,10 @@ class WriteFile { void cleanup(); ~WriteFile(); static int getNumInstances(); - static void writeAllHeaders(); - static void writeAllFooters(); static void writeAllOutputs(bool flush); static void startThread(); static void stopThread(); - static void run(void*); + static void run(); /** * Returns a unique filename by appending a number at the end of the original * filename. @@ -160,7 +152,7 @@ class WriteFile { * @return a pointer to the unique filename. This MUST be freed by the * invoking function. */ - static char* generateUniqueFilename(const char* original); + static std::string generateUniqueFilename(const std::string& original); }; #endif /* WRITEFILE_H_ */ From 378a88a7c3d58db7e8b9378a931bd4fde4bcecc7 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Wed, 19 Jul 2023 19:51:51 +0000 Subject: [PATCH 018/188] PRU: cleared up cleanup, factored out to its own method, also assume it is idempotent. Fixed a couple uninitialised values. Thanks valgrind --- core/PRU.cpp | 57 ++++++++++++++++++++---------------------------- core/RTAudio.cpp | 1 - include/PRU.h | 1 + 3 files changed, 25 insertions(+), 34 deletions(-) diff --git a/core/PRU.cpp b/core/PRU.cpp index 25ab71673..8aa5ac196 100644 --- a/core/PRU.cpp +++ b/core/PRU.cpp @@ -218,6 +218,7 @@ PRU::PRU(InternalBelaContext *input_context) digital_enabled(false), gpio_enabled(false), led_enabled(false), analog_out_is_audio(false), pru_audio_out_channels(0), pru_buffer_comm(0), + last_analog_out_frame(0), last_digital_buffer(0), audio_expander_input_history(0), audio_expander_output_history(0), audio_expander_filter_coeff(0), pruUsesMcaspIrq(false), belaHw(BelaHw_NoHw) { @@ -230,12 +231,7 @@ PRU::~PRU() disable(); exitPRUSS(); delete pruMemory; - if(gpio_enabled) - cleanupGPIO(); - if(audio_expander_input_history != 0) - free(audio_expander_input_history); - if(audio_expander_output_history != 0) - free(audio_expander_output_history); + cleanup(); } // Prepare the GPIO pins needed for the PRU @@ -343,12 +339,12 @@ void PRU::cleanupGPIO() if(digital_enabled){ for(unsigned int i = 0; i < context->digitalChannels; i++){ if(belaHw == BelaHw_Salt) { - if(gDigitalPins[i] == saltSwitch1Gpio) + if(gDigitalPins && gDigitalPins[i] == saltSwitch1Gpio) continue; // leave alone this pin as it is used by bela_button.service } if(disabledDigitalChannels & (1 << i)) continue; // leave alone this pin because the user asked for it - if(gpio_unexport(gDigitalPins[i])) + if(gDigitalPins && gpio_unexport(gDigitalPins[i])) { // if unexport fails, we at least turn off the outputs gpio_set_dir(gDigitalPins[i], OUTPUT_PIN); @@ -377,6 +373,7 @@ void PRU::cleanupGPIO() // Initialise and open the PRU int PRU::initialise(BelaHw newBelaHw, int pru_num, bool uniformSampleRate, int mux_channels, int stopButtonPin, bool enableLed, uint32_t disabledDigitalChannels) { + cleanup(); this->disabledDigitalChannels = disabledDigitalChannels; belaHw = newBelaHw; if(BelaHw_BelaRevC == belaHw) @@ -1602,35 +1599,29 @@ void PRU::loop(void *userData, void(*render)(BelaContext*, void*), bool highPerf // Wait for the PRU to finish task_sleep_ns(100000000); +} - // Clean up after ourselves +void PRU::cleanup() +{ + cleanupGPIO(); free(context->audioIn); + context->audioIn = 0; free(context->audioOut); - - if(analog_enabled) { - free(context->analogIn); - free(context->analogOut); - free(last_analog_out_frame); - if(context->multiplexerAnalogIn != 0) - free(context->multiplexerAnalogIn); - if(audio_expander_input_history != 0) { - free(audio_expander_input_history); - audio_expander_input_history = 0; - } - if(audio_expander_output_history != 0) { - free(audio_expander_output_history); - audio_expander_output_history = 0; - } - } - - if(digital_enabled) { - free(last_digital_buffer); - } - - context->audioIn = context->audioOut = 0; - context->analogIn = context->analogOut = 0; - context->digital = 0; + context->audioOut = 0; + free(context->analogIn); + context->analogIn = 0; + free(context->analogOut); + context->analogOut = 0; + free(last_analog_out_frame); + last_analog_out_frame = 0; + free(context->multiplexerAnalogIn); context->multiplexerAnalogIn = 0; + free(audio_expander_input_history); + audio_expander_input_history = 0; + free(audio_expander_output_history); + audio_expander_output_history = 0; + free(last_digital_buffer); + last_digital_buffer = 0; } // Wait for an interrupt from the PRU indicate it is finished diff --git a/core/RTAudio.cpp b/core/RTAudio.cpp index 0def82ad6..147adc266 100644 --- a/core/RTAudio.cpp +++ b/core/RTAudio.cpp @@ -822,7 +822,6 @@ void audioLoop(void *) // gPRU->waitForFinish(); gPRU->disable(); gAudioCodec->stopAudio(); - gPRU->cleanupGPIO(); if(gBelaAudioThreadDone) gBelaAudioThreadDone(gUserContext, gUserData); diff --git a/include/PRU.h b/include/PRU.h index 1dfc0a2ec..cb7d27e59 100644 --- a/include/PRU.h +++ b/include/PRU.h @@ -171,6 +171,7 @@ class PRU // Loop: read and write data from the PRU and call the user-defined audio callback void loop(void *userData, void(*render)(BelaContext*, void*), bool highPerformanceMode, BelaCpuData* cpuData); + void cleanup(); // Wait for an interrupt from the PRU indicate it is finished void waitForFinish(); From 2cd6c718c284c0c2388e3e9b8e30d451a38fb112 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Wed, 19 Jul 2023 19:52:27 +0000 Subject: [PATCH 019/188] RTAudio: if exiting early because of error in setup(), ensure we clean up after ourselves --- core/RTAudio.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/RTAudio.cpp b/core/RTAudio.cpp index 147adc266..b14bb8aab 100644 --- a/core/RTAudio.cpp +++ b/core/RTAudio.cpp @@ -794,6 +794,10 @@ int Bela_initAudio(BelaInitSettings *settings, void *userData) if(settings->setup && !(*settings->setup)(gUserContext, userData)) { if(gRTAudioVerbose) fprintf(stderr, "Couldn't initialise audio rendering: setup() returned false\n"); + delete gPRU; + delete gAudioCodec; + delete gDisabledCodec; + delete gBcf; return 1; } From fbdff0ca08e1ebf6399f23c52590b2d909014dc0 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Wed, 19 Jul 2023 20:12:41 +0000 Subject: [PATCH 020/188] GPIOcontrol: gpio_export(): close fd only if it's valid, not the other way around --- core/GPIOcontrol.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/GPIOcontrol.cpp b/core/GPIOcontrol.cpp index 5c2dc7089..bfe0e4e55 100644 --- a/core/GPIOcontrol.cpp +++ b/core/GPIOcontrol.cpp @@ -73,9 +73,9 @@ int gpio_export(unsigned int gpio) len = snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d", gpio); fd = open(buf, O_RDONLY); if(fd > 0) { + close(fd); return 0; } - close(fd); fd = open(SYSFS_GPIO_DIR "/export", O_WRONLY); if (fd < 0) { perror("gpio/export"); From 6ccb4ad35388ea36084cf6b906f877a16b69c37e Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 20 Jul 2023 20:28:42 +0000 Subject: [PATCH 021/188] WSServer: do _not_ store a shared_ptr to the server on the handler, or the ref count of neither will ever reach zero and destructors won't be called --- libraries/WSServer/WSServer.cpp | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/libraries/WSServer/WSServer.cpp b/libraries/WSServer/WSServer.cpp index c8bf39497..9d3470dde 100644 --- a/libraries/WSServer/WSServer.cpp +++ b/libraries/WSServer/WSServer.cpp @@ -15,7 +15,6 @@ WSServer::~WSServer(){ } struct WSServerDataHandler : seasocks::WebSocket::Handler { - std::shared_ptr server; std::set connections; std::string address; std::function on_receive; @@ -46,19 +45,19 @@ void WSServer::client_task_func(std::shared_ptr handler, co // make a copy of the data before we send it out auto data = std::make_shared >(size); memcpy(data->data(), buf, size); - handler->server->execute([handler, data, size]{ - for (auto c : handler->connections){ + for (auto c : handler->connections){ + c->server().execute([data, size, c]{ c->send((uint8_t*) data->data(), size); - } - }); + }); + } } else { // make a copy of the data before we send it out std::string str = (const char*)buf; - handler->server->execute([handler, str]{ - for (auto c : handler->connections){ + for (auto c : handler->connections){ + c->server().execute([str, c]{ c->send(str.c_str()); - } - }); + }); + } } } @@ -80,7 +79,6 @@ void WSServer::addAddress(const std::string& _address, bool binary) { auto handler = std::make_shared(); - handler->server = server; handler->address = _address; handler->on_receive = on_receive; handler->on_connect = on_connect; From 80862edab87ee20076021c781a043ae5e4107243 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 20 Jul 2023 20:32:24 +0000 Subject: [PATCH 022/188] WSServer: avoid possible future pitfalls by capturing weak_ptr instead of shared_ptr. See https://floating.io/2017/07/lambda-shared_ptr-memory-leak/ for reasoning. This was not an immediate issue, but worth avoiding future issues and it makes more sense to have the shared_ptr for _managing_ objects and the weak_ptr for _using_ them --- libraries/WSServer/WSServer.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/libraries/WSServer/WSServer.cpp b/libraries/WSServer/WSServer.cpp index 9d3470dde..5d365de73 100644 --- a/libraries/WSServer/WSServer.cpp +++ b/libraries/WSServer/WSServer.cpp @@ -40,7 +40,10 @@ struct WSServerDataHandler : seasocks::WebSocket::Handler { } }; +// this is either called directly from sendNonRt(), or via callback when scheduled from sendRt() void WSServer::client_task_func(std::shared_ptr handler, const void* buf, unsigned int size){ + if(!handler) + return; if (handler->binary){ // make a copy of the data before we send it out auto data = std::make_shared >(size); @@ -90,7 +93,16 @@ void WSServer::addAddress(const std::string& _address, .thread = std::unique_ptr(new AuxTaskNonRT()), .handler = handler, }; - address_book[_address].thread->create(std::string("WSClient_")+_address, [this, handler](void* buf, int size){ client_task_func(handler, buf, size); }); + // do _not_ capture a shared_ptr in a lambda. + // See possible pitfalls here + // https://floating.io/2017/07/lambda-shared_ptr-memory-leak/ + std::weak_ptr wkHdl(handler); + address_book[_address].thread->create(std::string("WSClient_")+_address, + [this,wkHdl](void* buf, int size){ + auto handler = wkHdl.lock(); + if(handler) + client_task_func(handler, buf, size); + }); } int WSServer::sendNonRt(const char* _address, const char* str) { From b096836613498d5ae09f92ca990ab6b015ea099f Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 20 Jul 2023 21:00:48 +0000 Subject: [PATCH 023/188] Gui: ensure the last ws_disconnect is called while the object (and its members) are still valid --- libraries/Gui/Gui.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/libraries/Gui/Gui.cpp b/libraries/Gui/Gui.cpp index 092bed621..2181fb3a0 100644 --- a/libraries/Gui/Gui.cpp +++ b/libraries/Gui/Gui.cpp @@ -170,6 +170,9 @@ DataBuffer& Gui::getDataBuffer( unsigned int bufferId ) Gui::~Gui() { cleanup(); + // trigger the destruction of the server so that ws_disconnect is called + // while the object is still valid + ws_server.reset(); } void Gui::cleanup() { From 753df1fec4299575dc82b05ac9e93f732db68c8e Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 21 Jul 2023 20:09:06 +0000 Subject: [PATCH 024/188] AuxTask{Non,}RT: hardened by removing mallocs --- core/AuxTaskNonRT.cpp | 18 ++++++++---------- core/AuxTaskRT.cpp | 13 +++++++------ 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/core/AuxTaskNonRT.cpp b/core/AuxTaskNonRT.cpp index 83420750a..837573c75 100644 --- a/core/AuxTaskNonRT.cpp +++ b/core/AuxTaskNonRT.cpp @@ -5,6 +5,7 @@ #include #include #include +#include extern int volatile gRTAudioVerbose; @@ -144,30 +145,28 @@ int AuxTaskNonRT::openPipe(){ } void AuxTaskNonRT::empty_loop(){ - void* buf = malloc(1); + char c; while(!shouldStop()){ - read(pipe_fd, buf, 1); + read(pipe_fd, &c, sizeof(c)); if (shouldStop()) break; empty_callback(); } - free(buf); } void AuxTaskNonRT::str_loop(){ - void* buf = malloc(AUX_MAX_BUFFER_SIZE); - memset(buf, 0, AUX_MAX_BUFFER_SIZE); + std::vector buffer(AUX_MAX_BUFFER_SIZE); + char* buf = buffer.data(); while(!shouldStop()){ ssize_t size = read(pipe_fd, buf, AUX_MAX_BUFFER_SIZE); if (shouldStop()) break; - str_callback(std::string((const char*)buf)); + str_callback(std::string(buf)); memset(buf, 0, size); } - free(buf); } void AuxTaskNonRT::buf_loop(){ - void* buf = malloc(AUX_MAX_BUFFER_SIZE); - memset(buf, 0, AUX_MAX_BUFFER_SIZE); + std::vector buffer(AUX_MAX_BUFFER_SIZE); + char* buf = buffer.data(); while(!shouldStop()){ ssize_t size = read(pipe_fd, buf, AUX_MAX_BUFFER_SIZE); if (shouldStop()) @@ -175,7 +174,6 @@ void AuxTaskNonRT::buf_loop(){ buf_callback(buf, size); memset(buf, 0, size); } - free(buf); } void AuxTaskNonRT::thread_func(void* ptr){ diff --git a/core/AuxTaskRT.cpp b/core/AuxTaskRT.cpp index 62c21b5d7..326352397 100644 --- a/core/AuxTaskRT.cpp +++ b/core/AuxTaskRT.cpp @@ -3,6 +3,7 @@ #include "../include/xenomai_wraps.h" #include #include +#include extern int volatile gRTAudioVerbose; @@ -138,7 +139,8 @@ void AuxTaskRT::empty_loop(){ } #endif #ifdef XENOMAI_SKIN_posix - char* buffer = (char*)malloc(AUX_RT_POOL_SIZE); + std::vector buf(AUX_RT_POOL_SIZE); + char* buffer = buf.data(); while(!shouldStop()) { unsigned int prio; @@ -152,7 +154,6 @@ void AuxTaskRT::empty_loop(){ empty_callback(); } } - free(buffer); #endif } void AuxTaskRT::str_loop(){ @@ -166,7 +167,8 @@ void AuxTaskRT::str_loop(){ } #endif #ifdef XENOMAI_SKIN_posix - char* buffer = (char*)malloc(AUX_RT_POOL_SIZE); + std::vector buf(AUX_RT_POOL_SIZE); + char* buffer = buf.data(); while(!shouldStop()) { unsigned int prio; @@ -179,7 +181,6 @@ void AuxTaskRT::str_loop(){ if(!shouldStop()) str_callback((std::string)buffer); } - free(buffer); #endif } void AuxTaskRT::buf_loop(){ @@ -193,7 +194,8 @@ void AuxTaskRT::buf_loop(){ } #endif #ifdef XENOMAI_SKIN_posix - char* buffer = (char*)malloc(AUX_RT_POOL_SIZE); + std::vector buf(AUX_RT_POOL_SIZE); + char* buffer = buf.data(); while(!shouldStop()) { unsigned int prio; @@ -206,7 +208,6 @@ void AuxTaskRT::buf_loop(){ if(!shouldStop()) buf_callback((void*)buffer, ret); } - free(buffer); #endif } From c5eed1d3b405f7a130323eed4277b733196a5c26 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 21 Jul 2023 20:11:07 +0000 Subject: [PATCH 025/188] Scope: removed some memory leaks --- libraries/Scope/Scope.cpp | 10 +++++----- libraries/Scope/Scope.h | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/libraries/Scope/Scope.cpp b/libraries/Scope/Scope.cpp index 28829b099..bef67c26a 100644 --- a/libraries/Scope/Scope.cpp +++ b/libraries/Scope/Scope.cpp @@ -550,8 +550,8 @@ void Scope::scope_control_connected(){ for (auto setting : settings){ root[setting.first] = new JSONValue(setting.second); } - JSONValue *value = new JSONValue(root); - std::wstring wide = value->Stringify().c_str(); + JSONValue value(root); + std::wstring wide = value.Stringify().c_str(); std::string str( wide.begin(), wide.end() ); // printf("sending JSON: \n%s\n", str.c_str()); ws_server->sendNonRt("scope_control", str.c_str()); @@ -564,8 +564,8 @@ void Scope::scope_control_data(const char* data){ // printf("recieved: %s\n", data); // parse the data into a JSONValue - JSONValue *value = JSON::Parse(data); - if (value == NULL || !value->IsObject()){ + std::shared_ptr value = std::shared_ptr(JSON::Parse(data)); + if (!value || !value->IsObject()){ printf("could not parse JSON:\n%s\n", data); return; } @@ -585,7 +585,7 @@ void Scope::scope_control_data(const char* data){ parse_settings(value); } -void Scope::parse_settings(JSONValue* value){ +void Scope::parse_settings(std::shared_ptr value){ // printf("parsing settings\n"); std::vector keys = value->ObjectKeys(); for (auto& key : keys){ diff --git a/libraries/Scope/Scope.h b/libraries/Scope/Scope.h index 5e7268073..8e46fd89d 100644 --- a/libraries/Scope/Scope.h +++ b/libraries/Scope/Scope.h @@ -101,7 +101,7 @@ class Scope{ void setXParams(); void scope_control_connected(); void scope_control_data(const char* data); - void parse_settings(JSONValue* value); + void parse_settings(std::shared_ptr value); bool volatile isUsingOutBuffer; bool volatile isUsingBuffer; From 8a195b3117a4e8f13997da2f6ac9adaa5d764425 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 21 Jul 2023 21:39:57 +0000 Subject: [PATCH 026/188] Scope: do not call disconnect callback on a destroyed object --- libraries/Scope/Scope.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/libraries/Scope/Scope.cpp b/libraries/Scope/Scope.cpp index bef67c26a..b8d7421e0 100644 --- a/libraries/Scope/Scope.cpp +++ b/libraries/Scope/Scope.cpp @@ -25,6 +25,10 @@ Scope::Scope(unsigned int numChannels, float sampleRate){ void Scope::cleanup(){ dealloc(); + // ensure that all connections are closed before + // destroying the object, so we avoid calling the disconnect callback + // after the Scope object has been destroyed + ws_server.reset(); } Scope::~Scope(){ cleanup(); From 14e7e940ed38fca40837e668f448f93d506ce5b4 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 21 Jul 2023 21:54:21 +0000 Subject: [PATCH 027/188] WSServer: do not capture connection in the lambda for execution on the server thread as it may become stale by the time the callback is executed. Instead, use the same weak_ptr approach used elsewhere. Also, use the same procedure where possible for sending binary or string. --- libraries/WSServer/WSServer.cpp | 36 ++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/libraries/WSServer/WSServer.cpp b/libraries/WSServer/WSServer.cpp index 5d365de73..24949680b 100644 --- a/libraries/WSServer/WSServer.cpp +++ b/libraries/WSServer/WSServer.cpp @@ -44,21 +44,25 @@ struct WSServerDataHandler : seasocks::WebSocket::Handler { void WSServer::client_task_func(std::shared_ptr handler, const void* buf, unsigned int size){ if(!handler) return; - if (handler->binary){ - // make a copy of the data before we send it out - auto data = std::make_shared >(size); - memcpy(data->data(), buf, size); - for (auto c : handler->connections){ - c->server().execute([data, size, c]{ - c->send((uint8_t*) data->data(), size); - }); - } - } else { - // make a copy of the data before we send it out - std::string str = (const char*)buf; - for (auto c : handler->connections){ - c->server().execute([str, c]{ - c->send(str.c_str()); + // make a copy of the data before we send it out + if(handler->connections.size()) + { + // make a copy of input data + auto data = std::make_shared >(size); + memcpy(data->data(), buf, size); + std::weak_ptr wkHdl(handler); + // schedule execution on the seasocks thread + // passing in a weak_ptr + (*handler->connections.begin())->server().execute([data, size, wkHdl]{ + auto handler = wkHdl.lock(); + if(!handler) + return; + for (auto c : handler->connections){ + if(handler->binary) + c->send((uint8_t*) data->data(), size); + else + c->send((const char*)data->data()); + } }); } } @@ -106,7 +110,7 @@ void WSServer::addAddress(const std::string& _address, } int WSServer::sendNonRt(const char* _address, const char* str) { - return sendNonRt(_address, (const void*)str, strlen(str)); + return sendNonRt(_address, (const void*)str, strlen(str) + 1); } int WSServer::sendNonRt(const char* _address, const void* buf, unsigned int size) { From a154fb8fef52358c2f74df50ff09ff91163c8213 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 21 Jul 2023 22:50:18 +0000 Subject: [PATCH 028/188] WSServer: when calling sendNonRt(), allow to specify if calling directly from the same thread as the callback. This allows to avoid allocation and copy as the send can be executed immediately instead of postponed in a lambda. --- libraries/Gui/Gui.cpp | 6 +++--- libraries/Gui/Gui.h | 5 ++--- libraries/Scope/Scope.cpp | 2 +- libraries/WSServer/WSServer.cpp | 21 +++++++++++++++------ libraries/WSServer/WSServer.h | 12 ++++++++---- 5 files changed, 29 insertions(+), 17 deletions(-) diff --git a/libraries/Gui/Gui.cpp b/libraries/Gui/Gui.cpp index 2181fb3a0..d0f6f3689 100644 --- a/libraries/Gui/Gui.cpp +++ b/libraries/Gui/Gui.cpp @@ -67,7 +67,7 @@ void Gui::ws_connect(const std::string& address, const WSServerDetails* id) if(!_projectName.empty()) root[L"projectName"] = new JSONValue(_projectName); JSONValue *value = new JSONValue(root); - sendControl(value); + sendControl(value, WSServer::kThreadCallback); delete value; } @@ -178,10 +178,10 @@ void Gui::cleanup() { } -int Gui::sendControl(JSONValue* root) { +int Gui::sendControl(JSONValue* root, WSServer::CallingThread callingThread) { std::wstring wide = JSON::Stringify(root); std::string str(wide.begin(), wide.end()); - return ws_server->sendNonRt(_addressControl.c_str(), str.c_str()); + return ws_server->sendNonRt(_addressControl.c_str(), str.c_str(), callingThread); } int Gui::doSendBuffer(const char* type, unsigned int bufferId, const void* data, size_t size) diff --git a/libraries/Gui/Gui.h b/libraries/Gui/Gui.h index 400984b2f..a8286640f 100644 --- a/libraries/Gui/Gui.h +++ b/libraries/Gui/Gui.h @@ -8,10 +8,9 @@ #include #include #include +#include "libraries/WSServer/WSServer.h" // forward declarations -class WSServer; -class WSServerDetails; class Gui { @@ -115,7 +114,7 @@ class Gui /** Sends a JSON value to the control websocket. * @returns 0 on success, or an error code otherwise. * */ - int sendControl(JSONValue* root); + int sendControl(JSONValue* root, WSServer::CallingThread callingThread); /** * Sends a buffer (a vector) through the web-socket to the client with a given ID. diff --git a/libraries/Scope/Scope.cpp b/libraries/Scope/Scope.cpp index b8d7421e0..b5f18e13a 100644 --- a/libraries/Scope/Scope.cpp +++ b/libraries/Scope/Scope.cpp @@ -558,7 +558,7 @@ void Scope::scope_control_connected(){ std::wstring wide = value.Stringify().c_str(); std::string str( wide.begin(), wide.end() ); // printf("sending JSON: \n%s\n", str.c_str()); - ws_server->sendNonRt("scope_control", str.c_str()); + ws_server->sendNonRt("scope_control", str.c_str(), WSServer::kThreadCallback); } // on_data callback for scope_control websocket diff --git a/libraries/WSServer/WSServer.cpp b/libraries/WSServer/WSServer.cpp index 24949680b..c3e70ce7f 100644 --- a/libraries/WSServer/WSServer.cpp +++ b/libraries/WSServer/WSServer.cpp @@ -41,12 +41,21 @@ struct WSServerDataHandler : seasocks::WebSocket::Handler { }; // this is either called directly from sendNonRt(), or via callback when scheduled from sendRt() -void WSServer::client_task_func(std::shared_ptr handler, const void* buf, unsigned int size){ +void WSServer::sendToAllConnections(std::shared_ptr handler, const void* buf, unsigned int size, CallingThread callingThread){ if(!handler) return; // make a copy of the data before we send it out if(handler->connections.size()) { + if(kThreadCallback == callingThread) { + // avoid memory copy and a lot of work + for (auto c : handler->connections){ + if (handler->binary) + c->send((uint8_t*)buf, size); + else + c->send((const char*)buf); + } + } else { // make a copy of input data auto data = std::make_shared >(size); memcpy(data->data(), buf, size); @@ -105,17 +114,17 @@ void WSServer::addAddress(const std::string& _address, [this,wkHdl](void* buf, int size){ auto handler = wkHdl.lock(); if(handler) - client_task_func(handler, buf, size); + sendToAllConnections(handler, buf, size, kThreadOther); }); } -int WSServer::sendNonRt(const char* _address, const char* str) { - return sendNonRt(_address, (const void*)str, strlen(str) + 1); +int WSServer::sendNonRt(const char* _address, const char* str, CallingThread callingThread) { + return sendNonRt(_address, (const void*)str, strlen(str) + 1, callingThread); } -int WSServer::sendNonRt(const char* _address, const void* buf, unsigned int size) { +int WSServer::sendNonRt(const char* _address, const void* buf, unsigned int size, CallingThread callingThread) { try { - client_task_func(address_book.at(_address).handler, buf, size); + sendToAllConnections(address_book.at(_address).handler, buf, size, callingThread); return 0; } catch (std::exception&) { return -1; diff --git a/libraries/WSServer/WSServer.h b/libraries/WSServer/WSServer.h index 38fb785d0..2eda9b7d7 100644 --- a/libraries/WSServer/WSServer.h +++ b/libraries/WSServer/WSServer.h @@ -1,4 +1,4 @@ -/***** WSServer.h *****/ +#pragma once #include #include #include @@ -18,6 +18,10 @@ class WSServerDetails; class WSServer{ friend struct WSServerDataHandler; public: + enum CallingThread { + kThreadCallback, + kThreadOther, + }; WSServer(); WSServer(int _port); ~WSServer(); @@ -30,8 +34,8 @@ class WSServer{ std::function on_disconnect = nullptr, bool binary = false); - int sendNonRt(const char* address, const char* str); - int sendNonRt(const char* address, const void* buf, unsigned int size); + int sendNonRt(const char* address, const char* str, CallingThread callingThread = kThreadOther); + int sendNonRt(const char* address, const void* buf, unsigned int size, CallingThread callingThread = kThreadOther); int sendRt(const char* address, const char* str); int sendRt(const char* address, const void* buf, unsigned int size); @@ -49,5 +53,5 @@ class WSServer{ std::map address_book; std::unique_ptr server_task; - void client_task_func(std::shared_ptr handler, const void* buf, unsigned int size); + void sendToAllConnections(std::shared_ptr handler, const void* buf, unsigned int size, CallingThread callingThread); }; From 4174384a5f15e8ffffa1b95e924dfd266e90daa2 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 21 Jul 2023 23:54:04 +0000 Subject: [PATCH 029/188] AuxTaskRT: timed write on exit, to avoid hanging the destructor if the thread has already exited. Should close https://github.com/BelaPlatform/Bela/issues/722 --- core/AuxTaskRT.cpp | 5 ++++- libraries/Gui/Gui.cpp | 2 +- libraries/Gui/Gui.h | 8 +++++++- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/core/AuxTaskRT.cpp b/core/AuxTaskRT.cpp index 326352397..9a21c48ab 100644 --- a/core/AuxTaskRT.cpp +++ b/core/AuxTaskRT.cpp @@ -109,7 +109,10 @@ void AuxTaskRT::cleanup(){ #endif #ifdef XENOMAI_SKIN_posix // unblock and join thread - schedule(); + char c = 0; + struct timespec absoluteTimeout = {0, 0}; + // non blocking write, so if the queue is full it won't fail + __wrap_mq_timedsend(queueDesc, &c, sizeof(c), 0, &absoluteTimeout); int ret = __wrap_pthread_join(thread, NULL); if (ret < 0){ fprintf(stderr, "AuxTaskNonRT %s: unable to join thread: (%i) %s\n", name.c_str(), ret, strerror(ret)); diff --git a/libraries/Gui/Gui.cpp b/libraries/Gui/Gui.cpp index d0f6f3689..72b3d9bd7 100644 --- a/libraries/Gui/Gui.cpp +++ b/libraries/Gui/Gui.cpp @@ -178,7 +178,7 @@ void Gui::cleanup() { } -int Gui::sendControl(JSONValue* root, WSServer::CallingThread callingThread) { +int Gui::sendControl(const JSONValue* root, WSServer::CallingThread callingThread) { std::wstring wide = JSON::Stringify(root); std::string str(wide.begin(), wide.end()); return ws_server->sendNonRt(_addressControl.c_str(), str.c_str(), callingThread); diff --git a/libraries/Gui/Gui.h b/libraries/Gui/Gui.h index a8286640f..0a184a72b 100644 --- a/libraries/Gui/Gui.h +++ b/libraries/Gui/Gui.h @@ -112,9 +112,15 @@ class Gui binaryCallbackArg = callbackArg; }; /** Sends a JSON value to the control websocket. + * + * @param root the JSONValue to send + * @param callingThread set this to WSServer::ThreadCallback if + * you are calling this method from the same thread that called + * the control or data callback in order to save a memory + * allocation and copy. Otherwise, leave it at its default value. * @returns 0 on success, or an error code otherwise. * */ - int sendControl(JSONValue* root, WSServer::CallingThread callingThread); + int sendControl(const JSONValue* root, WSServer::CallingThread callingThread); /** * Sends a buffer (a vector) through the web-socket to the client with a given ID. From 2bce2672bb8a85677b096168235be06ca6daea4b Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Sat, 22 Jul 2023 00:07:51 +0000 Subject: [PATCH 030/188] default_libpd_render: remove uses of malloc and new [] (which were leaking in case of file not found) --- core/default_libpd_render.cpp | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/core/default_libpd_render.cpp b/core/default_libpd_render.cpp index a935538d1..93ce8e508 100644 --- a/core/default_libpd_render.cpp +++ b/core/default_libpd_render.cpp @@ -813,7 +813,7 @@ void fdLoop(void* arg){ #ifdef BELA_LIBPD_SCOPE Scope scope; -float* gScopeOut; +std::vector gScopeOut; #endif // BELA_LIBPD_SCOPE void* gPatch; bool gDigitalEnabled = 0; @@ -857,20 +857,17 @@ bool setup(BelaContext *context, void *userData) #endif // BELA_LIBPD_MIDI #ifdef BELA_LIBPD_SCOPE scope.setup(gScopeChannelsInUse, context->audioSampleRate); - gScopeOut = new float[gScopeChannelsInUse]; + gScopeOut.resize(gScopeChannelsInUse); #endif // BELA_LIBPD_SCOPE // Check first of all if the patch file exists. Will actually open it later. char file[] = "_main.pd"; char folder[] = "./"; - unsigned int strSize = strlen(file) + strlen(folder) + 1; - char* str = (char*)malloc(sizeof(char) * strSize); - snprintf(str, strSize, "%s%s", folder, file); - if(access(str, F_OK) == -1 ) { - printf("Error file %s/%s not found. The %s file should be your main patch.\n", folder, file, file); + std::string path = std::string(folder) + file; + if(access(path.c_str(), F_OK) == -1 ) { + printf("Error file %s not found. The %s file should be your main patch.\n", path.c_str(), file); return false; } - free(str); // analog setup gAnalogChannelsInUse = context->analogInChannels; @@ -1462,10 +1459,10 @@ void render(BelaContext *context, void *userData) #ifdef BELA_LIBPD_SCOPE // scope output for (j = 0, p0 = gOutBuf; j < gLibpdBlockSize; ++j, ++p0) { - for (k = 0, p1 = p0 + gLibpdBlockSize * gFirstScopeChannel; k < gScopeChannelsInUse; k++, p1 += gLibpdBlockSize) { + for (k = 0, p1 = p0 + gLibpdBlockSize * gFirstScopeChannel; k < gScopeOut.size(); k++, p1 += gLibpdBlockSize) { gScopeOut[k] = *p1; } - scope.log(gScopeOut[0], gScopeOut[1], gScopeOut[2], gScopeOut[3]); + scope.log(gScopeOut.data()); } #endif // BELA_LIBPD_SCOPE @@ -1507,7 +1504,4 @@ void cleanup(BelaContext *context, void *userData) } #endif // BELA_LIBPD_TRILL libpd_closefile(gPatch); -#ifdef BELA_LIBPD_SCOPE - delete [] gScopeOut; -#endif // BELA_LIBPD_SCOPE } From c86f1f7dce6881d55c33ef4d96257df596aa14fc Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Sat, 22 Jul 2023 00:25:31 +0000 Subject: [PATCH 031/188] WSServer: stop the server (and its callbacks) before everything else --- libraries/WSServer/WSServer.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/libraries/WSServer/WSServer.cpp b/libraries/WSServer/WSServer.cpp index c3e70ce7f..599e205fe 100644 --- a/libraries/WSServer/WSServer.cpp +++ b/libraries/WSServer/WSServer.cpp @@ -149,4 +149,7 @@ int WSServer::sendRt(const char* _address, const void* buf, unsigned int size){ void WSServer::cleanup(){ server->terminate(); + // wait for server to terminate and call all callbacks before + // destroying the objects it may depend on + server_task.reset(); } From 53a793bbc2735699afde2839208ebd427f24eeac Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Sat, 22 Jul 2023 00:33:46 +0000 Subject: [PATCH 032/188] I2c: do not leak file descriptor on shutdown. Closes https://github.com/BelaPlatform/Bela/issues/720 --- include/I2c.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/include/I2c.h b/include/I2c.h index 0da089cc8..cde8be272 100644 --- a/include/I2c.h +++ b/include/I2c.h @@ -87,4 +87,7 @@ inline ssize_t I2c::writeBytes(const void *buf, size_t count) return write(i2C_file, buf, count); } -inline I2c::~I2c(){} +inline I2c::~I2c(){ + if(i2C_file >= 0) + close(i2C_file); +} From ccbad7bcb1846fc69a117ddfaec8f871a627e25b Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Mon, 24 Jul 2023 17:28:22 +0000 Subject: [PATCH 033/188] default_libpd_render: handle bidirectional UART data --- core/default_libpd_render.cpp | 312 ++++++++++++++++++++-------------- 1 file changed, 186 insertions(+), 126 deletions(-) diff --git a/core/default_libpd_render.cpp b/core/default_libpd_render.cpp index 93ce8e508..b330091ba 100644 --- a/core/default_libpd_render.cpp +++ b/core/default_libpd_render.cpp @@ -177,20 +177,166 @@ AuxiliaryTask gSerialOutputTask; struct serialMessageHeader { - uint32_t idSize; - uint32_t dataSize; + uint32_t idSize = 0; + uint32_t dataSize = 0; +}; +enum WaitingFor { + kHeader, + kId, + kData, +}; + +struct SerialPipeState { + struct serialMessageHeader h; + enum WaitingFor waitingFor = kHeader; + char id[100]; }; -void serialOutputLoop(void* arg) { - // TODO: implement +static void processSerialPipe(bool rt, SerialPipeState& s) +{ + // Not sure we actually need while() below. We were using it earlier + // when this was coded inside render() in order to be able to perform early returns + while(1) + { + auto& h = s.h; + auto& waitingFor = s.waitingFor; + auto& id = s.id; + if(kHeader == waitingFor) + { + int ret = rt ? gSerialPipe.readRt(h) : gSerialPipe.readNonRt(h); + if(ret <= 0) + break; + waitingFor = kId; + } + if(kId == waitingFor) + { + if(h.idSize > sizeof(id) - 1) + rt_fprintf(stderr, "Serial: ID too large\n"); + else + { + int ret = rt ? gSerialPipe.readRt(id, h.idSize) : gSerialPipe.readNonRt(id, h.idSize); + if(ret <= 0) + break; + if(int(h.idSize) != ret) + { + rt_fprintf(stderr, "Invalid number of bytes read from gSerialPipe. Expected: %u, got %u\n", h.idSize, ret); + break; + } + id[ret] = '\0'; // ensure it's null-terminated + waitingFor = kData; + } + } + if(kData == waitingFor) + { + char data[h.dataSize + 1]; + int ret = rt ? gSerialPipe.readRt(data, h.dataSize) : gSerialPipe.readNonRt(data, h.dataSize); + if(ret <= 0) + break; + if(int(h.dataSize) != ret) + { + rt_fprintf(stderr, "Invalid number of bytes read from gSerialPipe. Expected: %u, got %u\n", h.dataSize, ret); + break; + } + if(rt) + { + // rt: forward data from pipe to Pd + data[h.dataSize] = '\0'; // ensure it's null-terminated + if(h.dataSize) + { + const char* rec = "bela_serialIn"; + if(kSerialSymbol == gSerialType) + { + libpd_symbol(rec, data); + } else if(kSerialBytes == gSerialType) { + if(gSerialEom >= 0) { + // messages are separated: send as a list + libpd_start_message(h.dataSize); + for(size_t n = 0; n < h.dataSize; ++n) + libpd_add_float(data[n]); + libpd_finish_message(rec, id); + } else { + // messages are not separated: send one byte at a time + for(size_t n = 0; n < h.dataSize; ++n) + { + libpd_start_message(h.dataSize); + libpd_add_float(data[n]); + libpd_finish_message(rec, id); + } + } + } else { + unsigned int nTokens = 1; + const uint8_t separators[] = { ' ', '\0'}; + // find number of delimiters + size_t start = 0; + for(size_t n = 0; n < sizeof(data); ++n) + { + for(size_t c = 0; c < sizeof(separators); ++c) + { + if(separators[c] == data[n] && n != start) // exclude empty tokens + { + start = n + 1; + nTokens++; + } + } + } + libpd_start_message(nTokens); + start = 0; + for(size_t n = 0; n < sizeof(data); ++n) + { + bool end = false; + for(size_t c = 0; c < sizeof(separators); ++c) + { + if(separators[c] == data[n]) + { + if(start == n) + start++; // remove empty tokens + else + end = true; + break; // no need to check for more separators + } + } + if(end) + { + data[n] = '\0'; // ensure the string is null-terminated so the next line works + if(kSerialSymbols == gSerialType) + libpd_add_symbol(data + start); + else if (kSerialFloats == gSerialType) + libpd_add_float(atof(data + start)); + start = n + 1; + } + } + libpd_finish_message(rec, id); + } + } + } else { + // non-rt: forward data from pipe to serial + if(h.dataSize) + gSerial.write(data, h.dataSize); + } + waitingFor = kHeader; + } + } } -void serialInputLoop(void* arg) { +static void serialOutputLoop(void* arg) { + // blocking read with timeout + gSerialPipe.setBlockingNonRt(true); + gSerialPipe.setTimeoutMsNonRt(100); + std::vector rec(1024); + std::vector id(100); + + SerialPipeState serialStateNonRt {}; + while(!Bela_stopRequested()) + { + processSerialPipe(false, serialStateNonRt); + } +} + +static void serialInputLoop(void* arg) { char serialBuffer[10000]; unsigned int i = 0; - serialMessageHeader h = { - .idSize = strlen(gSerialId.c_str()) + 1, - }; + serialMessageHeader h; + h.idSize = strlen(gSerialId.c_str()) + 1; while(!Bela_stopRequested()) { // read from the serial port with a timeout of 100ms @@ -598,7 +744,7 @@ void Bela_messageHook(const char *source, const char *symbol, int argc, t_atom * || !libpd_is_symbol(argv + 1) // device || !libpd_is_float(argv + 2) // baudrate || !(libpd_is_symbol(argv + 3) || libpd_is_float(argv + 3)) // EOM - || !libpd_is_symbol(argv + 4) // tyoe + || !libpd_is_symbol(argv + 4) // type ) { fprintf(stderr, "Invalid bela_setSerial arguments. Should be:\n" @@ -635,6 +781,34 @@ void Bela_messageHook(const char *source, const char *symbol, int argc, t_atom * gSerialOutputTask = Bela_runAuxiliaryTask(serialOutputLoop, 0); } } + if(0 == strcmp(source, "bela_serialOut")) + { + if(!argc) { + fprintf(stderr, "Invalid bela_serialOut arguments. Should be:\n" + "`serial_id firstByte `\n"); + return; + } + const char* id = symbol; + // convert floats to bytes + char data[argc]; + for(size_t n = 0; n < argc; ++n) + { + t_atom *a = argv + n; + if(libpd_is_float(a)) + { + data[n] = libpd_get_float(a); + } else { + fprintf(stderr, "bela_serialOut received non-float\n"); + return; + } + } + struct serialMessageHeader h; + h.idSize = strlen(id); + h.dataSize = sizeof(data); + gSerialPipe.writeRt(h); + gSerialPipe.writeRt(id, h.idSize); + gSerialPipe.writeRt(data, h.dataSize); + } #endif // BELA_LIBPD_SERIAL #ifdef BELA_LIBPD_TRILL if(0 == strcmp(source, "bela_setTrill")) @@ -1089,123 +1263,9 @@ void render(BelaContext *context, void *userData) } #endif // BELA_LIBPD_GUI #ifdef BELA_LIBPD_SERIAL - while(gSerialInputTask) // proxy for 'isEnabled. Using `while` so we can do early return - { - enum WaitingFor_t { - kHeader, - kId, - kData, - }; - static struct serialMessageHeader h; - static enum WaitingFor_t waitingFor = kHeader; - static char id[100]; - if(kHeader == waitingFor) - { - int ret = gSerialPipe.readRt(h); - if(ret <= 0) - break; - waitingFor = kId; - } - if(kId == waitingFor) - { - if(h.idSize > sizeof(id) - 1) - rt_fprintf(stderr, "Serial: ID too large\n"); - else - { - int ret = gSerialPipe.readRt(id, h.idSize); - if(ret <= 0) - break; - if(int(h.idSize) != ret) - { - rt_fprintf(stderr, "Invalid number of bytes read from gSerialPipe. Expected: %u, got %u\n", h.idSize, ret); - break; - } - id[ret] = '\0'; // ensure it's null-terminated - waitingFor = kData; - } - } - if(kData == waitingFor) - { - char data[h.dataSize + 1]; - int ret = gSerialPipe.readRt(data, h.dataSize); - if(ret <= 0) - break; - if(int(h.dataSize) != ret) - { - rt_fprintf(stderr, "Invalid number of bytes read from gSerialPipe. Expected: %u, got %u\n", h.dataSize, ret); - break; - } - data[h.dataSize] = '\0'; // ensure it's null-terminated - if(h.dataSize) - { - const char* rec = "bela_serial"; - if(kSerialSymbol == gSerialType) - { - libpd_symbol(rec, data); - } else if(kSerialBytes == gSerialType) { - if(gSerialEom >= 0) { - // messages are separated: send as a list - libpd_start_message(h.dataSize); - for(size_t n = 0; n < h.dataSize; ++n) - libpd_add_float(data[n]); - libpd_finish_message(rec, id); - } else { - // messages are not separated: send one byte at a time - for(size_t n = 0; n < h.dataSize; ++n) - { - libpd_start_message(h.dataSize); - libpd_add_float(data[n]); - libpd_finish_message(rec, id); - } - } - } else { - unsigned int nTokens = 1; - const uint8_t separators[] = { ' ', '\0'}; - // find number of delimiters - size_t start = 0; - for(size_t n = 0; n < sizeof(data); ++n) - { - for(size_t c = 0; c < sizeof(separators); ++c) - { - if(separators[c] == data[n] && n != start) // exclude empty tokens - { - start = n + 1; - nTokens++; - } - } - } - libpd_start_message(nTokens); - start = 0; - for(size_t n = 0; n < sizeof(data); ++n) - { - bool end = false; - for(size_t c = 0; c < sizeof(separators); ++c) - { - if(separators[c] == data[n]) - { - if(start == n) - start++; // remove empty tokens - else - end = true; - break; // no need to check for more separators - } - } - if(end) - { - data[n] = '\0'; // ensure the string is null-terminated so the next line works - if(kSerialSymbols == gSerialType) - libpd_add_symbol(data + start); - else if (kSerialFloats == gSerialType) - libpd_add_float(atof(data + start)); - start = n + 1; - } - } - libpd_finish_message(rec, id); - } - } - waitingFor = kHeader; - } - } + static SerialPipeState serialPipeStateRt {}; + if(gSerialInputTask) + processSerialPipe(true, serialPipeStateRt); #endif // BELA_LIBPD_SERIAL #ifdef BELA_LIBPD_TRILL for(auto& name : gTrillAcks) From f7d843be99f9bf22e1e898a9f898b24ca27181d2 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Mon, 24 Jul 2023 17:52:49 +0000 Subject: [PATCH 034/188] uart-communication example for Pd --- examples/PureData/uart-communication/_main.pd | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 examples/PureData/uart-communication/_main.pd diff --git a/examples/PureData/uart-communication/_main.pd b/examples/PureData/uart-communication/_main.pd new file mode 100644 index 000000000..cd57801df --- /dev/null +++ b/examples/PureData/uart-communication/_main.pd @@ -0,0 +1,41 @@ +#N canvas 190 75 1090 589 12; +#X obj 31 350 loadbang; +#X obj 31 398 s bela_setSerial; +#X obj 29 462 route myserial; +#X msg 31 374 new myserial /dev/ttyS4 9600 none bytes; +#X obj 355 486 s bela_serialOut; +#X obj 355 385 metro 1000; +#X obj 355 361 loadbang; +#X obj 403 413 + 1; +#X obj 355 412 f; +#X msg 355 455 myserial \$1 2 3 4 5 6; +#X obj 29 438 r bela_serialIn; +#X obj 29 486 print serialIn; +#X text 73 20 Send a `new` message to bela_setSerial to initialise UART communication. Arguments are:; +#X text 69 50 [new ; +#X text 72 65 Where:; +#X text 82 78 serialId: symbol to use in future communications pertaining this object; +#X text 85 133 bps: a valid baudrate supported by the device; +#X text 85 111 device: path to the serial device; +#X text 85 154 EOM: End Of Message byte \, used to identify boundaries; +#X text 102 168 in incoming messages. Possible values are:; +#X text 101 183 `none` (no message splitting) \, `newline` \, or a float; +#X text 103 198 representing the character code; +#X text 82 216 type: how the data is output from bela_serialIn. Possible; +#X text 101 231 values are:; +#X text 99 263 symbol: convert incoming message string to a symbol; +#X text 100 246 floats: convert incoming message string to a float; +#X text 99 279 symbols: convert incoming data to a symbol ignoring EOM; +#X text 98 294 bytes: convert each incoming byte to a float \, output them; +#X text 98 307 one byte at a time if EOM is none \, or as one list per message; +#X text 442 413 Output raw bytes (that's the only output mode supported right now); +#X connect 0 0 3 0; +#X connect 2 0 11 0; +#X connect 3 0 1 0; +#X connect 5 0 8 0; +#X connect 6 0 5 0; +#X connect 7 0 8 1; +#X connect 8 0 7 0; +#X connect 8 0 9 0; +#X connect 9 0 4 0; +#X connect 10 0 2 0; From 903ba4e289964ba7bc05b150419898c0cdc21849 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 3 Aug 2023 21:25:09 +0000 Subject: [PATCH 035/188] DataBuffer: support all data types that the GUI already supports --- include/DataBuffer.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/DataBuffer.h b/include/DataBuffer.h index 7c31b4daf..28c7cea83 100644 --- a/include/DataBuffer.h +++ b/include/DataBuffer.h @@ -18,7 +18,7 @@ class DataBuffer void setType (char type) { - if(type == 'c' || type == 'd' || type == 'f') + if(type == 'c' || type == 'j' || type == 'i' || type == 'd' || type == 'f') { _type = type; } From 23bf06660a740da67bb50a6d085208b598b899de Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 4 Aug 2023 17:16:42 +0000 Subject: [PATCH 036/188] Gui: backwards-compatible API --- libraries/Gui/Gui.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/Gui/Gui.h b/libraries/Gui/Gui.h index 0a184a72b..31f6455e9 100644 --- a/libraries/Gui/Gui.h +++ b/libraries/Gui/Gui.h @@ -120,7 +120,7 @@ class Gui * allocation and copy. Otherwise, leave it at its default value. * @returns 0 on success, or an error code otherwise. * */ - int sendControl(const JSONValue* root, WSServer::CallingThread callingThread); + int sendControl(const JSONValue* root, WSServer::CallingThread callingThread = WSServer::kThreadOther); /** * Sends a buffer (a vector) through the web-socket to the client with a given ID. From 50af3c07efc89b2cc7eb093e392d150f94994408 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Mon, 7 Aug 2023 19:13:20 +0000 Subject: [PATCH 037/188] AudioFileReader: allow to set starting frame at setup --- libraries/AudioFile/AudioFile.cpp | 15 +++++++++++---- libraries/AudioFile/AudioFile.h | 6 ++++-- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/libraries/AudioFile/AudioFile.cpp b/libraries/AudioFile/AudioFile.cpp index 054ab28b7..6eca18acb 100644 --- a/libraries/AudioFile/AudioFile.cpp +++ b/libraries/AudioFile/AudioFile.cpp @@ -12,16 +12,19 @@ std::vector& AudioFile::getRtBuffer() return internalBuffers[idx]; } -int AudioFile::setup(const std::string& path, size_t bufferSize, Mode mode, size_t channels /* = 0 */, unsigned int sampleRate /* = 0 */) +int AudioFile::setup(const std::string& path, size_t bufferSize, Mode mode, size_t arg0 /* = 0 */, unsigned int arg1 /* = 0 */) { cleanup(); int sf_mode; switch(mode){ - case kWrite: + case kWrite: { + unsigned int channels = arg0; + unsigned int sampleRate = arg1; sf_mode = SFM_WRITE; sfinfo.samplerate = sampleRate; sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16; sfinfo.channels = channels; + } break; case kRead: sfinfo.format = 0; @@ -50,6 +53,9 @@ int AudioFile::setup(const std::string& path, size_t bufferSize, Mode mode, size ioBufferOld = ioBuffer; if(kRead == mode) { + size_t readFirstFrame = arg0; + if(!ramOnly) + sf_seek(sndfile, readFirstFrame, SEEK_SET); // fill up the first buffer io(internalBuffers[ioBuffer]); // signal threadLoop() to start filling in the next buffer @@ -94,10 +100,11 @@ AudioFile::~AudioFile() cleanup(); } -int AudioFileReader::setup(const std::string& path, size_t bufferSize) +int AudioFileReader::setup(const std::string& path, size_t bufferSize, size_t firstFrame) { loop = false; - return AudioFile::setup(path, bufferSize, kRead); + idx = firstFrame; + return AudioFile::setup(path, bufferSize, kRead, firstFrame); } int AudioFileReader::setLoop(bool doLoop) diff --git a/libraries/AudioFile/AudioFile.h b/libraries/AudioFile/AudioFile.h index 43457ed97..dd8c41844 100644 --- a/libraries/AudioFile/AudioFile.h +++ b/libraries/AudioFile/AudioFile.h @@ -89,7 +89,7 @@ class AudioFile } Mode; enum { kNumBufs = 2}; protected: - int setup(const std::string& path, size_t bufferSize, Mode mode, size_t channels = 0, unsigned int sampleRate = 0); + int setup(const std::string& path, size_t bufferSize, Mode mode, size_t arg0 = 0, unsigned int arg1 = 0); public: size_t getLength() const { return sfinfo.frames; }; size_t getChannels() const { return sfinfo.channels; }; @@ -125,8 +125,10 @@ class AudioFileReader : public AudioFile * @param bufferSize the size of the internal buffer. If this is larger * than the file itself, the whole file will be loaded in memory, otherwise * the file will be read from disk from a separate thread. + * @param firstFrame the first frame to start plaback from. When + * looping, unless set differnetly with setLoop(), it will start back from 0. */ - int setup(const std::string& path, size_t bufferSize); + int setup(const std::string& path, size_t bufferSize, size_t firstFrame = 0); /** * Write interleaved samples from the file to the destination. * From 71dec078c169b8e6da06a9da658eecf25b31d1f4 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 11 Aug 2023 16:40:38 +0000 Subject: [PATCH 038/188] WriteFile: using + separator between base of filename and counter. Also added getName() --- libraries/WriteFile/WriteFile.cpp | 25 ++++++++++++++++++++----- libraries/WriteFile/WriteFile.h | 6 ++++++ 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/libraries/WriteFile/WriteFile.cpp b/libraries/WriteFile/WriteFile.cpp index 335f99c7b..6f27833bb 100644 --- a/libraries/WriteFile/WriteFile.cpp +++ b/libraries/WriteFile/WriteFile.cpp @@ -112,8 +112,10 @@ std::string WriteFile::generateUniqueFilename(const std::string& original) dot = n; } int count = dot; + constexpr char sep = '+'; + constexpr size_t sepLen = 1; // add a * before the dot - std::string temp = std::string({original.begin(), original.begin() + dot}) + "*" + std::string({original.begin() + dot, original.end()}); + std::string temp = std::string({original.begin(), original.begin() + dot}) + '*' + std::string({original.begin() + dot, original.end()}); // check how many log files are already there, and choose name according to this glob_t globbuf; @@ -122,21 +124,34 @@ std::string WriteFile::generateUniqueFilename(const std::string& original) int logNum; int logMax = -1; // cycle through all and find the existing one with the highest index - for(unsigned int i=0; i logMax) logMax = logNum; } globfree(&globbuf); - if(logMax == -1) + if(logMax == -1 && originalFree) { // use the same filename return original; } else { // generate a new filename logNum = logMax + 1; // new index - std::string out = std::string({original.begin(), original.begin() + dot}) + std::to_string(logNum) + std::string({original.begin() + dot, original.end()}); + std::string out = std::string({original.begin(), original.begin() + dot}) + sep + std::to_string(logNum) + std::string({original.begin() + dot, original.end()}); printf("File %s exists, writing to %s instead\n", original.c_str(), out.c_str()); return out; } diff --git a/libraries/WriteFile/WriteFile.h b/libraries/WriteFile/WriteFile.h index 2a67fe81f..d1603748d 100644 --- a/libraries/WriteFile/WriteFile.h +++ b/libraries/WriteFile/WriteFile.h @@ -125,6 +125,12 @@ class WriteFile { */ void setup(const std::string& filename, bool overwrite = false, bool append = false); + /** + * Get the name of the file being written. This may be different from + * the filename passed to setup() if it was called with `overwrite = + * false`. + */ + const std::string& getName() { return filename; } /** * Gets the distance between the write and read pointers of * the buffer that holds data to be written to disk. From 5f1c0bc918df45dfcb70c018a93e4692a967932c Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 11 Aug 2023 16:41:10 +0000 Subject: [PATCH 039/188] WriteFile: use 1MB buffer per binary file as default instead of 10MB --- libraries/WriteFile/WriteFile.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/WriteFile/WriteFile.cpp b/libraries/WriteFile/WriteFile.cpp index 6f27833bb..f69170890 100644 --- a/libraries/WriteFile/WriteFile.cpp +++ b/libraries/WriteFile/WriteFile.cpp @@ -192,7 +192,7 @@ void WriteFile::setup(const std::string& newFilename, bool overwrite, bool appen void WriteFile::setFileType(WriteFileType newFileType){ fileType = newFileType; if(fileType == kBinary) - setBufferSize(1e7); + setBufferSize(1e6); } void WriteFile::setEcho(bool newEcho){ echo=newEcho; From 8fdc5c80f77ee0c8a956a78b75b3d7b0b3c8fd4f Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 11 Aug 2023 19:18:21 +0000 Subject: [PATCH 040/188] WriteFile: allow to delete file upon cleanup() --- libraries/WriteFile/WriteFile.cpp | 12 +++++++++++- libraries/WriteFile/WriteFile.h | 9 ++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/libraries/WriteFile/WriteFile.cpp b/libraries/WriteFile/WriteFile.cpp index f69170890..257a80871 100644 --- a/libraries/WriteFile/WriteFile.cpp +++ b/libraries/WriteFile/WriteFile.cpp @@ -78,13 +78,23 @@ WriteFile::~WriteFile(){ cleanup(); } -void WriteFile::cleanup(){ +void WriteFile::cleanup(bool discard){ + if(cleaned) + return; + cleaned = true; std::unique_lock lock(mutex); //write all that's left writeOutput(true); writeFooter(); fflush(file); fclose(file); + if(discard) + { + int ret = unlink(filename.c_str()); + if(ret) + fprintf(stderr, "Error while deleting file %s: %d %s\n", filename.c_str(), errno, strerror(errno)); + } + // remove from objAddrs list auto it = std::find(objAddrs.begin(), objAddrs.end(), this); if(it != objAddrs.end()) diff --git a/libraries/WriteFile/WriteFile.h b/libraries/WriteFile/WriteFile.h index d1603748d..71a7a3557 100644 --- a/libraries/WriteFile/WriteFile.h +++ b/libraries/WriteFile/WriteFile.h @@ -38,6 +38,7 @@ class WriteFile { std::string filename; std::vector formatTokens; bool echo; + bool cleaned = false; static constexpr size_t sleepTimeMs = 5; void writeLine(); void writeHeader(); @@ -144,7 +145,13 @@ class WriteFile { * and 1 being buffer empty (writing to disk is fast enough). */ float getBufferStatus(); - void cleanup(); + /** + * Stop the logging, flush to disk and remove the file from the writing + * thread. After this, you need a new call to setup(). + * + * @param discard Whether to delete the file after closing it. + */ + void cleanup(bool discard = false); ~WriteFile(); static int getNumInstances(); static void writeAllOutputs(bool flush); From 75c274b44e9509ed986eef1ae5a54dd68e8ff51c Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Sat, 12 Aug 2023 00:21:55 +0000 Subject: [PATCH 041/188] Gui: (js) add .type to each buffer --- IDE/public/gui/js/BelaData.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/IDE/public/gui/js/BelaData.js b/IDE/public/gui/js/BelaData.js index 41816dca0..888a80366 100644 --- a/IDE/public/gui/js/BelaData.js +++ b/IDE/public/gui/js/BelaData.js @@ -108,7 +108,9 @@ export default class BelaData extends BelaWebSocket { } if(err) return; - this.buffers[this.newBuffer['id']] = this.newBuffer['data']; + let idx = this.newBuffer['id']; + this.buffers[idx] = this.newBuffer['data']; + this.buffers[idx].type = type; this.bufferReady = true; this.target.dispatchEvent( new CustomEvent('buffer-ready', { detail: this.newBuffer['id'] }) ); From ca4abd46d9191822959082dbb9dfa043230ea087 Mon Sep 17 00:00:00 2001 From: anbjoernskov <77576836+anbjoernskov@users.noreply.github.com> Date: Fri, 11 Aug 2023 14:15:38 +0200 Subject: [PATCH 042/188] createXenomaiPipe: poolsz should be size_t --- include/xenomai_wraps.h | 2 +- libraries/Pipe/Pipe.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/include/xenomai_wraps.h b/include/xenomai_wraps.h index 5fcf7ab86..a9985d87d 100644 --- a/include/xenomai_wraps.h +++ b/include/xenomai_wraps.h @@ -176,7 +176,7 @@ inline int create_and_start_thread(pthread_t* task, const char* taskName, int pr return 0; } // from xenomai-3/demo/posix/cobalt/xddp-echo.c -inline int createXenomaiPipe(const char* portName, int poolsz) +inline int createXenomaiPipe(const char* portName, size_t poolsz) { /* * Get a datagram socket to bind to the RT endpoint. Each diff --git a/libraries/Pipe/Pipe.h b/libraries/Pipe/Pipe.h index ae8c9f667..fe5b478fd 100644 --- a/libraries/Pipe/Pipe.h +++ b/libraries/Pipe/Pipe.h @@ -84,7 +84,7 @@ class Pipe std::string path; int pipeSocket; int fd = 0; - int pipeSize; + size_t pipeSize; double timeoutMsRt = 0; double timeoutMsNonRt = 0; bool blockingRt = false; From fe1c43323c5b2bb602b22e95c646e6b0db8f740f Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 15 Aug 2023 16:08:41 +0000 Subject: [PATCH 043/188] OscReceiver: missing include --- libraries/OscReceiver/OscReceiver.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries/OscReceiver/OscReceiver.cpp b/libraries/OscReceiver/OscReceiver.cpp index 6611f24a5..8a557173a 100644 --- a/libraries/OscReceiver/OscReceiver.cpp +++ b/libraries/OscReceiver/OscReceiver.cpp @@ -1,6 +1,7 @@ #include "OscReceiver.h" #include #include +#include constexpr unsigned int OscReceiverBlockReadUs = 50000; constexpr unsigned int OscReceiverSleepBetweenReadsUs = 5000; From 512a21df888bd2368416818a2a350ea60b698aa1 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 15 Aug 2023 16:09:00 +0000 Subject: [PATCH 044/188] NIT: UdpClient: const --- libraries/UdpClient/UdpClient.cpp | 2 +- libraries/UdpClient/UdpClient.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/UdpClient/UdpClient.cpp b/libraries/UdpClient/UdpClient.cpp index 55f456418..7e2b541c7 100644 --- a/libraries/UdpClient/UdpClient.cpp +++ b/libraries/UdpClient/UdpClient.cpp @@ -52,7 +52,7 @@ static void dieUninitialized(std::string str){ inet_pton(AF_INET,aServerName,&destinationServer.sin_addr); isSetServer=true; }; - int UdpClient::send(void * message, int size){ + int UdpClient::send(const void * message, int size){ if(!enabled) return -1; unsigned int length; diff --git a/libraries/UdpClient/UdpClient.h b/libraries/UdpClient/UdpClient.h index 99d2394e2..507315e54 100644 --- a/libraries/UdpClient/UdpClient.h +++ b/libraries/UdpClient/UdpClient.h @@ -42,7 +42,7 @@ class UdpClient{ * @param size The number of bytes to be read from memory and sent to the destination. * @return the number of bytes sent or -1 if an error occurred. */ - int send(void* message, int size); + int send(const void* message, int size); int write(const char* remoteHostname, int remotePortNumber, void* sourceBuffer, int numBytesToWrite); int waitUntilReady(bool readyForReading, int timeoutMsecs); From b58758f1488df140f3f48883324236af77a47845 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 15 Aug 2023 16:22:58 +0000 Subject: [PATCH 045/188] OscSender: added sendNonRt() which bypasses the outgoing pipe --- libraries/OscSender/OscSender.cpp | 19 +++++++++++++++---- libraries/OscSender/OscSender.h | 11 ++++++++++- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/libraries/OscSender/OscSender.cpp b/libraries/OscSender/OscSender.cpp index 480054cc6..704decdd1 100644 --- a/libraries/OscSender/OscSender.cpp +++ b/libraries/OscSender/OscSender.cpp @@ -14,9 +14,8 @@ OscSender::OscSender(int port, std::string ip_address){ } OscSender::~OscSender(){} -void OscSender::send_task_func(void* buf, int size){ - OscSender* instance = this; - instance->socket->send(buf, size); +void OscSender::doSendToSocket(const void* buf, size_t size) { + socket->send(buf, size); } void OscSender::setup(int port, std::string ip_address){ @@ -29,7 +28,9 @@ void OscSender::setup(int port, std::string ip_address){ socket->setup(port, ip_address.c_str()); send_task = std::unique_ptr(new AuxTaskNonRT()); - send_task->create(std::string("OscSndrTsk_") + ip_address + std::to_string(port), [this](void* buf, int size){send_task_func(buf, size); }); + send_task->create(std::string("OscSndrTsk_") + ip_address + std::to_string(port), [this](const void* buf, int size){ + doSendToSocket(buf, size); + }); } OscSender &OscSender::newMessage(std::string address){ @@ -63,7 +64,17 @@ void OscSender::send(){ send_task->schedule(pw->packetData(), pw->packetSize()); } +void OscSender::sendNonRt(){ + pw->init().addMessage(*msg); + doSendToSocket(pw->packetData(), pw->packetSize()); +} + void OscSender::send(const oscpkt::Message& extMsg){ pw->init().addMessage(extMsg); send_task->schedule(pw->packetData(), pw->packetSize()); } + +void OscSender::sendNonRt(const oscpkt::Message& extMsg){ + pw->init().addMessage(extMsg); + doSendToSocket(pw->packetData(), pw->packetSize()); +} diff --git a/libraries/OscSender/OscSender.h b/libraries/OscSender/OscSender.h index 051686975..27f4323ae 100644 --- a/libraries/OscSender/OscSender.h +++ b/libraries/OscSender/OscSender.h @@ -102,6 +102,10 @@ class OscSender{ * */ void send(); + /** + * \brief Sends the message from the non-realtime thread. + */ + void sendNonRt(); /** * \brief Sends a message * @@ -109,6 +113,10 @@ class OscSender{ * externally. It is safe to call from the audio thread. */ void send(const oscpkt::Message& extMsg); + /** + * \brief Sends a message from the non-realtime thread. + */ + void sendNonRt(const oscpkt::Message& extMsg); std::unique_ptr socket; @@ -116,5 +124,6 @@ class OscSender{ std::unique_ptr pw; std::unique_ptr send_task; - void send_task_func(void* buf, int size); + private: + void doSendToSocket(const void* buf, size_t len); }; From 66b425a5a5b1da6f6c5e8cd6f4ef46ce4a3ce056 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 15 Aug 2023 16:23:48 +0000 Subject: [PATCH 046/188] Communication/OSC: fixed --- examples/Communication/OSC/render.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/Communication/OSC/render.cpp b/examples/Communication/OSC/render.cpp index 094a9ee15..2b9e1ff3a 100644 --- a/examples/Communication/OSC/render.cpp +++ b/examples/Communication/OSC/render.cpp @@ -51,7 +51,7 @@ void on_receive(oscpkt::Message* msg, const char* addr, void* arg) float floatArg; msg->match("/osc-test").popInt32(intArg).popFloat(floatArg).isOkNoMoreArgs(); printf("received a message with int %i and float %f\n", intArg, floatArg); - oscSender.newMessage("/osc-acknowledge").add(intArg).add(4.2f).add(std::string("OSC message received")).send(); + oscSender.newMessage("/osc-acknowledge").add(intArg).add(4.2f).add(std::string("OSC message received")).sendNonRt(); } } @@ -62,7 +62,7 @@ bool setup(BelaContext *context, void *userData) // the following code sends an OSC message to address /osc-setup // then waits 1 second for a reply on /osc-setup-reply - oscSender.newMessage("/osc-setup").send(); + oscSender.newMessage("/osc-setup").sendNonRt(); int count = 0; int timeoutCount = 10; printf("Waiting for handshake ....\n"); From 8f24bae6fc42a1582ef77d5f876365e51aa23e6d Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 15 Aug 2023 17:44:57 +0000 Subject: [PATCH 047/188] WriteFile: requestFlush() --- libraries/WriteFile/WriteFile.cpp | 8 ++++++++ libraries/WriteFile/WriteFile.h | 5 +++++ 2 files changed, 13 insertions(+) diff --git a/libraries/WriteFile/WriteFile.cpp b/libraries/WriteFile/WriteFile.cpp index 257a80871..9a3e96c8a 100644 --- a/libraries/WriteFile/WriteFile.cpp +++ b/libraries/WriteFile/WriteFile.cpp @@ -346,6 +346,10 @@ void WriteFile::writeOutput(bool flush){ // So we make sure we only write full lines writeLine(); } + if(shouldFlush) { + shouldFlush = false; + flush = true; + } if(fileType == kBinary){ int numBinaryElementsToWriteAtOnce = 4096; bool wasWritten = false; @@ -413,3 +417,7 @@ void WriteFile::run(){ } threadRunning = false; } + +void WriteFile::requestFlush() { + shouldFlush = true; +} diff --git a/libraries/WriteFile/WriteFile.h b/libraries/WriteFile/WriteFile.h index 71a7a3557..8acc4651d 100644 --- a/libraries/WriteFile/WriteFile.h +++ b/libraries/WriteFile/WriteFile.h @@ -39,6 +39,7 @@ class WriteFile { std::vector formatTokens; bool echo; bool cleaned = false; + volatile bool shouldFlush = false; static constexpr size_t sleepTimeMs = 5; void writeLine(); void writeHeader(); @@ -145,6 +146,10 @@ class WriteFile { * and 1 being buffer empty (writing to disk is fast enough). */ float getBufferStatus(); + /** + * Request that all of the data logged so far is flushed to disk. + */ + void requestFlush(); /** * Stop the logging, flush to disk and remove the file from the writing * thread. After this, you need a new call to setup(). From 29d6f7eed05200877b4b49bab189e1703c24e309 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 18 Aug 2023 23:14:26 +0000 Subject: [PATCH 048/188] NIT: WriteFile: moved headers to implementation --- libraries/WriteFile/WriteFile.cpp | 4 ++++ libraries/WriteFile/WriteFile.h | 6 +----- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/libraries/WriteFile/WriteFile.cpp b/libraries/WriteFile/WriteFile.cpp index 9a3e96c8a..d9a9772d2 100644 --- a/libraries/WriteFile/WriteFile.cpp +++ b/libraries/WriteFile/WriteFile.cpp @@ -13,6 +13,10 @@ #include #include #include +#include +#include +#include +#include //setupialise static members bool WriteFile::staticConstructed=false; diff --git a/libraries/WriteFile/WriteFile.h b/libraries/WriteFile/WriteFile.h index 8acc4651d..f5bb3596d 100644 --- a/libraries/WriteFile/WriteFile.h +++ b/libraries/WriteFile/WriteFile.h @@ -7,13 +7,9 @@ #ifndef WRITEFILE_H_ #define WRITEFILE_H_ -#include #include -#include -#include -#include -#include #include +#include typedef enum { kBinary, From 0d819eac4d455c2af33e02f3b567516b949af56c Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 22 Aug 2023 08:22:01 -0500 Subject: [PATCH 049/188] Scope: display ms/div or hz/div in a decent format. Also fixes a bug in hz/div viz and refactors --- IDE/frontend-dev/scope-src/ControlView.js | 51 +++++++++++++++-------- IDE/public/scope/js/bundle.js | 49 ++++++++++++++-------- 2 files changed, 64 insertions(+), 36 deletions(-) diff --git a/IDE/frontend-dev/scope-src/ControlView.js b/IDE/frontend-dev/scope-src/ControlView.js index 3ce2f6811..6f0045904 100644 --- a/IDE/frontend-dev/scope-src/ControlView.js +++ b/IDE/frontend-dev/scope-src/ControlView.js @@ -84,43 +84,58 @@ class ControlView extends View{ } } + msDiv() { + let time = (xTime * downSampling/upSampling); + if(time < 10) + time = time.toFixed(2); + else if (time < 100) + time = time.toFixed(1); + else + time = time.toFixed(0); + return time; + } + + hzDiv() { + let hz = (sampleRate/20 * upSampling/downSampling); + return hz.toFixed(0); + } + + updateUnitDisplay(data) { + let unitDisplay; + if (data.plotMode == 0){ + unitDisplay = this.msDiv(); + } else if (data.plotMode == 1){ + unitDisplay = this.hzDiv(); + } + $('.xUnit-display').html(unitDisplay); + } + plotMode(val, data){ this.emit('plotMode', val, data); if (val == 0){ if ($('#control-underlay').hasClass('')) $('#control-underlay').addClass('hidden'); if ($('#triggerControls').hasClass('hidden')) $('#triggerControls').removeClass('hidden'); if (!$('#FFTControls').hasClass('hidden')) $('#FFTControls').addClass('hidden'); - $('.xAxisUnits').html('

ms

'); - $('.xUnit-display').html('

'+ (xTime * downSampling/upSampling).toPrecision(2) +'

'); - $('#zoomUp').html('Zoom in'); - $('#zoomDown').html('Zoom out'); + $('.xAxisUnits').html("ms"); } else if (val == 1){ if ($('#control-underlay').hasClass('hidden')) $('#control-underlay').removeClass('hidden'); if (!$('#trigger-controls').hasClass('hidden')) $('#triggerControls').addClass('hidden'); if ($('#FFTControls').hasClass('hidden')) $('#FFTControls').removeClass('hidden'); - $('.xAxisUnits').html('Hz'); - $('.xUnit-display').html((sampleRate/20 * upSampling/downSampling)); - $('#zoomUp').html('Zoom out'); - $('#zoomDown').html('Zoom in'); + $('.xAxisUnits').html("Hz"); } + this.updateUnitDisplay(data); + $('#zoomUp').html('Zoom in'); + $('#zoomDown').html('Zoom out'); } _upSampling(value, data){ upSampling = value; - if (data.plotMode == 0){ - $('.xUnit-display').html('

'+ (xTime * downSampling/upSampling).toPrecision(2) +'

'); - } else if (data.plotMode == 1){ - $('.xUnit-display').html((data.sampleRate/20 * data.upSampling/data.downSampling)); - } + this.updateUnitDisplay(data); $('.zoom-display').html((100*upSampling/downSampling).toPrecision(4)+'%'); } _downSampling(value, data){ downSampling = value; - if (data.plotMode == 0){ - $('.xUnit-display').html('

'+ (xTime * downSampling/upSampling).toPrecision(2) +'

'); - } else if (data.plotMode == 1){ - $('.xUnit-display').html('

'+ (xTime * downSampling/upSampling).toPrecision(2) +'

'); - } + this.updateUnitDisplay(data); } _xTimeBase(value, data){ xTime = data.xTimeBase; diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index d03df67b8..6e770bf26 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -927,6 +927,30 @@ var ControlView = function (_View) { this.$elements.filterByData('key', key).val(data[key]); } } + }, { + key: 'msDiv', + value: function msDiv() { + var time = xTime * downSampling / upSampling; + if (time < 10) time = time.toFixed(2);else if (time < 100) time = time.toFixed(1);else time = time.toFixed(0); + return time; + } + }, { + key: 'hzDiv', + value: function hzDiv() { + var hz = sampleRate / 20 * upSampling / downSampling; + return hz.toFixed(0); + } + }, { + key: 'updateUnitDisplay', + value: function updateUnitDisplay(data) { + var unitDisplay = void 0; + if (data.plotMode == 0) { + unitDisplay = this.msDiv(); + } else if (data.plotMode == 1) { + unitDisplay = this.hzDiv(); + } + $('.xUnit-display').html(unitDisplay); + } }, { key: 'plotMode', value: function plotMode(val, data) { @@ -935,40 +959,29 @@ var ControlView = function (_View) { if ($('#control-underlay').hasClass('')) $('#control-underlay').addClass('hidden'); if ($('#triggerControls').hasClass('hidden')) $('#triggerControls').removeClass('hidden'); if (!$('#FFTControls').hasClass('hidden')) $('#FFTControls').addClass('hidden'); - $('.xAxisUnits').html('

ms

'); - $('.xUnit-display').html('

' + (xTime * downSampling / upSampling).toPrecision(2) + '

'); - $('#zoomUp').html('Zoom in'); - $('#zoomDown').html('Zoom out'); + $('.xAxisUnits').html("ms"); } else if (val == 1) { if ($('#control-underlay').hasClass('hidden')) $('#control-underlay').removeClass('hidden'); if (!$('#trigger-controls').hasClass('hidden')) $('#triggerControls').addClass('hidden'); if ($('#FFTControls').hasClass('hidden')) $('#FFTControls').removeClass('hidden'); - $('.xAxisUnits').html('Hz'); - $('.xUnit-display').html(sampleRate / 20 * upSampling / downSampling); - $('#zoomUp').html('Zoom out'); - $('#zoomDown').html('Zoom in'); + $('.xAxisUnits').html("Hz"); } + this.updateUnitDisplay(data); + $('#zoomUp').html('Zoom in'); + $('#zoomDown').html('Zoom out'); } }, { key: '_upSampling', value: function _upSampling(value, data) { upSampling = value; - if (data.plotMode == 0) { - $('.xUnit-display').html('

' + (xTime * downSampling / upSampling).toPrecision(2) + '

'); - } else if (data.plotMode == 1) { - $('.xUnit-display').html(data.sampleRate / 20 * data.upSampling / data.downSampling); - } + this.updateUnitDisplay(data); $('.zoom-display').html((100 * upSampling / downSampling).toPrecision(4) + '%'); } }, { key: '_downSampling', value: function _downSampling(value, data) { downSampling = value; - if (data.plotMode == 0) { - $('.xUnit-display').html('

' + (xTime * downSampling / upSampling).toPrecision(2) + '

'); - } else if (data.plotMode == 1) { - $('.xUnit-display').html('

' + (xTime * downSampling / upSampling).toPrecision(2) + '

'); - } + this.updateUnitDisplay(data); } }, { key: '_xTimeBase', From be8ef5406daa6c7bb64ea63a1da09369ca2cb3af Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 22 Aug 2023 08:33:47 -0500 Subject: [PATCH 050/188] Scope: Zoom In and Zoom Out work more naturally ("logarithmically") by duplicating / halving instead of adding/decreasing --- IDE/frontend-dev/scope-src/ControlView.js | 8 ++++---- IDE/public/scope/js/bundle.js | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/IDE/frontend-dev/scope-src/ControlView.js b/IDE/frontend-dev/scope-src/ControlView.js index 6f0045904..f5a41e337 100644 --- a/IDE/frontend-dev/scope-src/ControlView.js +++ b/IDE/frontend-dev/scope-src/ControlView.js @@ -46,19 +46,19 @@ class ControlView extends View{ buttonClicked($element, e){ if ($element.data().key === 'upSampling'){ if (downSampling > 1){ - downSampling -= 1; + downSampling /= 2; this.emit('settings-event', 'downSampling', downSampling); } else { - upSampling += 1; + upSampling *= 2; this.emit('settings-event', 'upSampling', upSampling); } // this._upSampling(); } else if ($element.data().key === 'downSampling'){ if (upSampling > 1){ - upSampling -= 1; + upSampling /= 2; this.emit('settings-event', 'upSampling', upSampling); } else { - downSampling += 1; + downSampling *= 2; this.emit('settings-event', 'downSampling', downSampling); } // this._downSampling(); diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index 6e770bf26..5ad3d8204 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -865,19 +865,19 @@ var ControlView = function (_View) { value: function buttonClicked($element, e) { if ($element.data().key === 'upSampling') { if (downSampling > 1) { - downSampling -= 1; + downSampling /= 2; this.emit('settings-event', 'downSampling', downSampling); } else { - upSampling += 1; + upSampling *= 2; this.emit('settings-event', 'upSampling', upSampling); } // this._upSampling(); } else if ($element.data().key === 'downSampling') { if (upSampling > 1) { - upSampling -= 1; + upSampling /= 2; this.emit('settings-event', 'upSampling', upSampling); } else { - downSampling += 1; + downSampling *= 2; this.emit('settings-event', 'downSampling', downSampling); } // this._downSampling(); From dfd5fa77b0f7c15247283f5f22c1b5fee99a0e68 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 22 Aug 2023 09:10:00 -0500 Subject: [PATCH 051/188] Scope: allow remoteHost= querystring to replace the default server:port (localhost:5432) --- IDE/frontend-dev/scope-src/scope-browser.js | 34 +++++++++++++------- IDE/public/scope/js/bundle.js | 35 +++++++++++++-------- IDE/public/scope/js/scope-worker.js | 31 +++++++++++------- 3 files changed, 63 insertions(+), 37 deletions(-) diff --git a/IDE/frontend-dev/scope-src/scope-browser.js b/IDE/frontend-dev/scope-src/scope-browser.js index 1d79f2a59..40782ad9b 100644 --- a/IDE/frontend-dev/scope-src/scope-browser.js +++ b/IDE/frontend-dev/scope-src/scope-browser.js @@ -1,7 +1,17 @@ 'use strict'; // worker +let remoteHost = location.hostname + ":5432"; +let qs = new URLSearchParams(location.search); +let qsRemoteHost = qs.get("remoteHost"); +if(qsRemoteHost) + remoteHost = qsRemoteHost +var wsRemote = "ws://" + remoteHost + "/"; var worker = new Worker("js/scope-worker.js"); +worker.postMessage({ + event: 'wsConnect', + remote: wsRemote, +}); // models var Model = require('./Model'); @@ -24,20 +34,12 @@ var sliderView = new (require('./SliderView'))('sliderView', [settings]); // main bela socket var belaSocket = io('/IDE'); -// scope websocket -var ws; - -var wsAddress = "ws://" + location.host + ":5432/scope_control" -ws = new WebSocket(wsAddress); var ws_onerror = function(e){ setTimeout(() => { - ws = new WebSocket(wsAddress); - ws.onerror = ws_onerror; - ws.onopen = ws_onopen; - ws.onmessage = ws_onmessage; + ws = new WebSocket(wsUrl); + setWsCbs(ws) }, 500); }; -ws.onerror = ws_onerror; var ws_onopen = function(){ ws.binaryType = 'arraybuffer'; @@ -45,7 +47,6 @@ var ws_onopen = function(){ ws.onclose = ws_onerror; ws.onerror = undefined; }; -ws.onopen = ws_onopen; var ws_onmessage = function(msg){ // console.log('recieved scope control message:', msg.data); @@ -85,7 +86,16 @@ var ws_onmessage = function(msg){ } } }; -ws.onmessage = ws_onmessage; +function setWsCbs(ws) { + ws.onerror = ws_onerror; + ws.onopen = ws_onopen; + ws.onmessage = ws_onmessage; +} + +// scope websocket +let wsUrl = wsRemote + "scope_control"; +var ws = new WebSocket(wsUrl); +setWsCbs(ws); var paused = false, oneShot = false; diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index 5ad3d8204..9687374ba 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -1369,7 +1369,16 @@ var _settings$setData; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +var remoteHost = location.hostname + ":5432"; +var qs = new URLSearchParams(location.search); +var qsRemoteHost = qs.get("remoteHost"); +if (qsRemoteHost) remoteHost = qsRemoteHost; +var wsRemote = "ws://" + remoteHost + "/"; var worker = new Worker("js/scope-worker.js"); +worker.postMessage({ + event: 'wsConnect', + remote: wsRemote +}); // models var Model = require('./Model'); @@ -1392,20 +1401,12 @@ var sliderView = new (require('./SliderView'))('sliderView', [settings]); // main bela socket var belaSocket = io('/IDE'); -// scope websocket -var ws; - -var wsAddress = "ws://" + location.host + ":5432/scope_control"; -ws = new WebSocket(wsAddress); var ws_onerror = function ws_onerror(e) { setTimeout(function () { - ws = new WebSocket(wsAddress); - ws.onerror = ws_onerror; - ws.onopen = ws_onopen; - ws.onmessage = ws_onmessage; + ws = new WebSocket(wsUrl); + setWsCbs(ws); }, 500); }; -ws.onerror = ws_onerror; var ws_onopen = function ws_onopen() { ws.binaryType = 'arraybuffer'; @@ -1413,7 +1414,6 @@ var ws_onopen = function ws_onopen() { ws.onclose = ws_onerror; ws.onerror = undefined; }; -ws.onopen = ws_onopen; var ws_onmessage = function ws_onmessage(msg) { // console.log('recieved scope control message:', msg.data); @@ -1450,7 +1450,16 @@ var ws_onmessage = function ws_onmessage(msg) { } } }; -ws.onmessage = ws_onmessage; +function setWsCbs(ws) { + ws.onerror = ws_onerror; + ws.onopen = ws_onopen; + ws.onmessage = ws_onmessage; +} + +// scope websocket +var wsUrl = wsRemote + "scope_control"; +var ws = new WebSocket(wsUrl); +setWsCbs(ws); var paused = false, oneShot = false; @@ -1848,7 +1857,7 @@ settings.setData((_settings$setData = { FFTXAxis: 0, FFTYAxis: 0, holdOff: 0 -}, _defineProperty(_settings$setData, 'numSliders', 0), _defineProperty(_settings$setData, 'interpolation', 0), _settings$setData)); +}, _defineProperty(_settings$setData, "numSliders", 0), _defineProperty(_settings$setData, "interpolation", 0), _settings$setData)); },{"./BackgroundView":2,"./ChannelView":3,"./ControlView":4,"./Model":5,"./SliderView":6}]},{},[8]) diff --git a/IDE/public/scope/js/scope-worker.js b/IDE/public/scope/js/scope-worker.js index 4ed9fe9ca..c64fe2e7d 100644 --- a/IDE/public/scope/js/scope-worker.js +++ b/IDE/public/scope/js/scope-worker.js @@ -1,25 +1,31 @@ var settings = {}, channelConfig = []; -var wsAddress = "ws://" + location.host + ":5432/scope_data"; -var ws = new WebSocket(wsAddress); -var ws_onerror = function(e){ +let wsUrl; +function setWsCbs(ws) { + ws.onerror = ws_onerror.bind(null,ws); + ws.onopen = ws_onopen.bind(null, ws); + ws.onmessage = ws_onmessage.bind(null, ws); +} +var ws_onerror = function(ws, e){ setTimeout(() => { - ws = new WebSocket(wsAddress); - ws.onerror = ws_onerror; - ws.onopen = ws_onopen; - ws.onmessage = ws_onmessage; + ws = new WebSocket(wsUrl); + setWsCbs(ws); }, 500); }; -ws.onerror = ws_onerror; -var ws_onopen = function(){ +function wsConnect(wsRemote) { + wsUrl = wsRemote + "scope_data" + let ws = new WebSocket(wsUrl) + setWsCbs(ws); +} + +var ws_onopen = function(ws){ ws.binaryType = 'arraybuffer'; console.log('scope data websocket open'); ws.onclose = ws_onerror; ws.onerror = undefined; }; -ws.onopen = ws_onopen; var zero = 0, triggerChannel = 0, xOffset = 0, triggerLevel = 0, numChannels = 0, upSampling = 0; var inFrameWidth = 0, outFrameWidth = 0, inArrayWidth = 0, outArrayWidth = 0, interpolation = 0; @@ -55,10 +61,12 @@ onmessage = function(e){ } else if (e.data.event === 'channelConfig'){ channelConfig = e.data.channelConfig; //console.log(channelConfig); + } else if (e.data.event === 'wsConnect') { + wsConnect(e.data.remote); } } -var ws_onmessage = function(e){ +var ws_onmessage = function(ws, e){ var inArray = new Float32Array(e.data); // console.log("worker: recieved buffer of length "+inArray.length, inArrayWidth); @@ -108,4 +116,3 @@ var ws_onmessage = function(e){ postMessage(outArray, [outArray.buffer]); }; -ws.onmessage = ws_onmessage; From f39be917f8ceec7a309ce4a561e384e155dddcee Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 22 Aug 2023 15:13:13 +0000 Subject: [PATCH 052/188] Scope: safely avoid division by zero --- libraries/Scope/Scope.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libraries/Scope/Scope.cpp b/libraries/Scope/Scope.cpp index b5f18e13a..ee313a5c0 100644 --- a/libraries/Scope/Scope.cpp +++ b/libraries/Scope/Scope.cpp @@ -104,6 +104,8 @@ void Scope::setPlotMode(){ // setup the input buffer frameWidth = pixelWidth/upSampling; + if(0 == frameWidth) + frameWidth = 1; // avoid divides by zero if(TIME_DOMAIN == plotMode) { channelWidth = frameWidth * FRAMES_STORED; } else { From 511bf75bc4b344f291fd449c6eccec2120a97429 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 22 Aug 2023 10:15:11 -0500 Subject: [PATCH 053/188] Scope: also set a zoom in limit in the frontend --- IDE/frontend-dev/scope-src/ControlView.js | 7 +++++-- IDE/public/scope/js/bundle.js | 7 +++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/IDE/frontend-dev/scope-src/ControlView.js b/IDE/frontend-dev/scope-src/ControlView.js index f5a41e337..a7c0abde1 100644 --- a/IDE/frontend-dev/scope-src/ControlView.js +++ b/IDE/frontend-dev/scope-src/ControlView.js @@ -49,8 +49,11 @@ class ControlView extends View{ downSampling /= 2; this.emit('settings-event', 'downSampling', downSampling); } else { - upSampling *= 2; - this.emit('settings-event', 'upSampling', upSampling); + if(upSampling < 64) { + // an arbitrary limit: higher than this and pileups start happening + upSampling *= 2; + this.emit('settings-event', 'upSampling', upSampling); + } } // this._upSampling(); } else if ($element.data().key === 'downSampling'){ diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index 9687374ba..a4be6ff0d 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -868,8 +868,11 @@ var ControlView = function (_View) { downSampling /= 2; this.emit('settings-event', 'downSampling', downSampling); } else { - upSampling *= 2; - this.emit('settings-event', 'upSampling', upSampling); + if (upSampling < 64) { + // an arbitrary limit: higher than this and pileups start happening + upSampling *= 2; + this.emit('settings-event', 'upSampling', upSampling); + } } // this._upSampling(); } else if ($element.data().key === 'downSampling') { From 89c4583e2d937ec882a458829df2e0ff66dd2b23 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 22 Aug 2023 17:23:58 +0000 Subject: [PATCH 054/188] Scope: prepend timestamp to outgoing buffer --- IDE/public/scope/js/scope-worker.js | 3 +- libraries/Scope/Scope.cpp | 51 +++++++++++++++++++---------- libraries/Scope/Scope.h | 8 ++++- 3 files changed, 42 insertions(+), 20 deletions(-) diff --git a/IDE/public/scope/js/scope-worker.js b/IDE/public/scope/js/scope-worker.js index c64fe2e7d..8bc00b8d6 100644 --- a/IDE/public/scope/js/scope-worker.js +++ b/IDE/public/scope/js/scope-worker.js @@ -68,7 +68,8 @@ onmessage = function(e){ var ws_onmessage = function(ws, e){ - var inArray = new Float32Array(e.data); + let timestamp = new Uint32Array(e.data.slice(0, 4))[0]; + var inArray = new Float32Array(e.data.slice(4)); // console.log("worker: recieved buffer of length "+inArray.length, inArrayWidth); // console.log(settings.frameHeight, settings.numChannels, settings.frameWidth, channelConfig); diff --git a/libraries/Scope/Scope.cpp b/libraries/Scope/Scope.cpp index ee313a5c0..1c12c756e 100644 --- a/libraries/Scope/Scope.cpp +++ b/libraries/Scope/Scope.cpp @@ -114,7 +114,7 @@ void Scope::setPlotMode(){ buffer.resize(numChannels*channelWidth); // setup the output buffer - outBuffer.resize(numChannels*frameWidth); + outBuffer.resize(numChannels * frameWidth + kTimestampSlots); // reset the trigger triggerPointer = 0; @@ -239,11 +239,37 @@ bool Scope::triggered(){ return false; } +void Scope::outBufferSetTimestamp(){ + memcpy(outBuffer.data(), ×tamp, sizeof(timestamp)); + outBufferSize = 0; +} + +void Scope::outBufferAppendData(size_t startptr, size_t endptr, size_t outChannelWidth){ + if(endptr > startptr) { + for(size_t i = 0; i < numChannels; ++i){ + std::copy(&buffer[channelWidth*i+startptr], &buffer[channelWidth*i+endptr], outBuffer.begin()+(i*outChannelWidth) + kTimestampSlots + outBufferSize); + } + outBufferSize += endptr - startptr; + } else { + for(size_t i = 0; i < numChannels; ++i){ + std::copy(&buffer[channelWidth*i+startptr], &buffer[channelWidth*(i+1)], outBuffer.begin()+(i*outChannelWidth) + kTimestampSlots + outBufferSize); + std::copy(&buffer[channelWidth*i], &buffer[channelWidth*i+endptr], outBuffer.begin()+((i+1)*outChannelWidth-endptr) + kTimestampSlots + outBufferSize); + } + outBufferSize += endptr + channelWidth - startptr; + } +} + +void Scope::outBufferSend(){ + size_t elems = kTimestampSlots + outBufferSize * numChannels; + size_t bytes = sizeof(outBuffer[0]) * elems; + ws_server->sendRt("scope_data", outBuffer.data(), bytes); +} + void Scope::triggerTimeDomain(){ // printf("do trigger %i, %i\n", readPointer, writePointer); // iterate over the samples between the read and write pointers and check for / deal with triggers while (readPointer != writePointer){ - + timestamp++; // if we are currently listening for a trigger if (triggerPrimed){ @@ -292,24 +318,13 @@ void Scope::triggerTimeDomain(){ // copy the previous to next frameWidth/2.0f samples into the outBuffer int startptr = (triggerPointer-(int)(frameWidth/2.0f) + channelWidth)%channelWidth; int endptr = (startptr + frameWidth)%channelWidth; - - if (endptr > startptr){ - for (int i=0; isendRt("scope_data", outBuffer.data(), outBuffer.size() * sizeof(float)); - + outBufferSend(); isUsingOutBuffer = false; } @@ -532,7 +547,7 @@ void Scope::setSetting(std::wstring setting, float value){ } else if (setting.compare(L"FFTYAxis") == 0){ FFTYAxis = (int)value; } else if (setting.compare(L"numChannels") == 0){ - numChannels = (int)value; + numChannels = value; } else if (setting.compare(L"sampleRate") == 0){ sampleRate = value; } diff --git a/libraries/Scope/Scope.h b/libraries/Scope/Scope.h index 8e46fd89d..b553507e2 100644 --- a/libraries/Scope/Scope.h +++ b/libraries/Scope/Scope.h @@ -102,13 +102,16 @@ class Scope{ void scope_control_connected(); void scope_control_data(const char* data); void parse_settings(std::shared_ptr value); + void outBufferSetTimestamp(); + void outBufferAppendData(size_t startptr, size_t endptr, size_t outChannelWidth); + void outBufferSend(); bool volatile isUsingOutBuffer; bool volatile isUsingBuffer; bool volatile isResizing; // settings - int numChannels; + size_t numChannels; float sampleRate; int pixelWidth; int frameWidth; @@ -132,6 +135,9 @@ class Scope{ // buffers std::vector buffer; std::vector outBuffer; + uint32_t timestamp = 0; + size_t outBufferSize; + static constexpr size_t kTimestampSlots = sizeof(timestamp) / sizeof(outBuffer[0]); // pointers int writePointer; From f76e5486599d1e739ef9630dada802d497f99fc3 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 22 Aug 2023 21:21:00 +0000 Subject: [PATCH 055/188] Scope: autoRoll when downSampling is above 8 --- IDE/public/scope/js/scope-worker.js | 30 +++++++++++++++++++++++++++-- libraries/Scope/Scope.cpp | 23 ++++++++++++++++++++-- libraries/Scope/Scope.h | 1 + 3 files changed, 50 insertions(+), 4 deletions(-) diff --git a/IDE/public/scope/js/scope-worker.js b/IDE/public/scope/js/scope-worker.js index 8bc00b8d6..fd77055a5 100644 --- a/IDE/public/scope/js/scope-worker.js +++ b/IDE/public/scope/js/scope-worker.js @@ -27,7 +27,7 @@ var ws_onopen = function(ws){ ws.onerror = undefined; }; -var zero = 0, triggerChannel = 0, xOffset = 0, triggerLevel = 0, numChannels = 0, upSampling = 0; +var zero = 0, triggerChannel = 0, xOffset = 0, triggerLevel = 0, numChannels = 0, upSampling = 0, downSampling = 1; var inFrameWidth = 0, outFrameWidth = 0, inArrayWidth = 0, outArrayWidth = 0, interpolation = 0; const plotModeTimeDomain = 0; @@ -49,6 +49,7 @@ onmessage = function(e){ numChannels = settings.numChannels; upSampling = settings.upSampling; + downSampling = settings.downSampling; inFrameWidth = Math.floor(settings.frameWidth/upSampling); outFrameWidth = settings.frameWidth; @@ -66,6 +67,14 @@ onmessage = function(e){ } } +let rollPtr = 0; +let globalArray = new Array(); +let counter = 0; + +function inToOut(c, val) { + return zero * (1 - (channelConfig[c].yOffset + val) * channelConfig[c].yAmplitude); +} + var ws_onmessage = function(ws, e){ let timestamp = new Uint32Array(e.data.slice(0, 4))[0]; @@ -73,8 +82,24 @@ var ws_onmessage = function(ws, e){ // console.log("worker: recieved buffer of length "+inArray.length, inArrayWidth); // console.log(settings.frameHeight, settings.numChannels, settings.frameWidth, channelConfig); + globalArray.length = outArrayWidth; var outArray = new Float32Array(outArrayWidth); + let roll = downSampling > 8; + if(roll) { + let frames = inArray.length / numChannels; + for(let n = 0; n < frames; ++n) { + for(let c = 0; c < numChannels; ++c) { + let inIndex = c * frames + n; + outIndex = c * outFrameWidth + rollPtr; + globalArray[outIndex] = inToOut(c, inArray[inIndex]); + } + rollPtr++; + rollPtr %= outFrameWidth; + } + for(let i = 0; i < outArray.length; ++i) + outArray[i] = globalArray[i]; + } else { if (inArray.length !== inArrayWidth) { console.log(inArray.length, inArrayWidth, inFrameWidth); console.log('worker: frame dropped'); @@ -91,7 +116,7 @@ var ws_onmessage = function(ws, e){ var second = inArray[inIndex + 1 < endOfInArray ? inIndex + 1 : endOfInArray]; var diff = interpolation ? u*(second-first)/upSampling : 0; outIndex = channel*outFrameWidth + frame*upSampling + u; - outArray[outIndex] = zero * (1 - (channelConfig[channel].yOffset + (inArray[inIndex]+diff)) * channelConfig[channel].yAmplitude); + outArray[outIndex] = inToOut(channel, inArray[inIndex] + diff); } } // the above will not always get to the end of outArray, depending on the ratio between upSampling and outFrameWidth @@ -110,6 +135,7 @@ var ws_onmessage = function(ws, e){ outArray[outIndex++] = fillValue; } } + } // for(var n = 0; n < upSampling; ++n){ // outArray[outArray.length - 1 - n] = outArray[outArray.length - upSampling - 1]; // } diff --git a/libraries/Scope/Scope.cpp b/libraries/Scope/Scope.cpp index 1c12c756e..e2936682b 100644 --- a/libraries/Scope/Scope.cpp +++ b/libraries/Scope/Scope.cpp @@ -268,10 +268,29 @@ void Scope::outBufferSend(){ void Scope::triggerTimeDomain(){ // printf("do trigger %i, %i\n", readPointer, writePointer); // iterate over the samples between the read and write pointers and check for / deal with triggers + // target approx 30 Hz + size_t numRollSamples = sampleRate / 30 / downSampling; + if(!numRollSamples) + numRollSamples = 1; while (readPointer != writePointer){ timestamp++; - // if we are currently listening for a trigger - if (triggerPrimed){ + bool autoRoll = true; + if(downSampling > 8 && autoRoll) + { + rollPtr++; + if(rollPtr >= numRollSamples) + { + rollPtr = 0; + isUsingOutBuffer = true; + isUsingBuffer = true; + outBufferSetTimestamp(); + outBufferAppendData((readPointer - numRollSamples + channelWidth) % channelWidth , readPointer % channelWidth, numRollSamples); + outBufferSend(); + isUsingBuffer = false; + isUsingOutBuffer = false; + } + } else if (triggerPrimed){ + //if we are currently listening for a trigger // if we crossed the trigger threshold if (triggered()){ diff --git a/libraries/Scope/Scope.h b/libraries/Scope/Scope.h index b553507e2..ad4e1b2ec 100644 --- a/libraries/Scope/Scope.h +++ b/libraries/Scope/Scope.h @@ -137,6 +137,7 @@ class Scope{ std::vector outBuffer; uint32_t timestamp = 0; size_t outBufferSize; + size_t rollPtr = 0; static constexpr size_t kTimestampSlots = sizeof(timestamp) / sizeof(outBuffer[0]); // pointers From bc8eb08767c07b8081952d2a3dc514ab3df3ad1b Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 22 Aug 2023 21:24:49 +0000 Subject: [PATCH 056/188] Scope: for high downSampling, schedule trigger task frequently enough --- libraries/Scope/Scope.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/Scope/Scope.cpp b/libraries/Scope/Scope.cpp index e2936682b..fa59db15d 100644 --- a/libraries/Scope/Scope.cpp +++ b/libraries/Scope/Scope.cpp @@ -203,7 +203,7 @@ void Scope::postlog(){ isUsingBuffer = false; writePointer = (writePointer+1)%channelWidth; - if (logCount++ > TRIGGER_LOG_COUNT){ + if (logCount++ > TRIGGER_LOG_COUNT || downSampling > TRIGGER_LOG_COUNT){ logCount = 0; scopeTriggerTask->schedule(); } From e44a629df72b5d0c4472434a524ab878c673cb5b Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 22 Aug 2023 17:46:31 -0500 Subject: [PATCH 057/188] Scope: toggle between real roll and simple non-triggering incremental drawing via hardcoded flag --- IDE/public/scope/js/scope-worker.js | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/IDE/public/scope/js/scope-worker.js b/IDE/public/scope/js/scope-worker.js index fd77055a5..07ceed6b2 100644 --- a/IDE/public/scope/js/scope-worker.js +++ b/IDE/public/scope/js/scope-worker.js @@ -82,23 +82,33 @@ var ws_onmessage = function(ws, e){ // console.log("worker: recieved buffer of length "+inArray.length, inArrayWidth); // console.log(settings.frameHeight, settings.numChannels, settings.frameWidth, channelConfig); - globalArray.length = outArrayWidth; + let roll = false; + let incDrawing = downSampling > 8; + globalArray.length = outArrayWidth * (roll ? 2 : 1); var outArray = new Float32Array(outArrayWidth); - let roll = downSampling > 8; - if(roll) { + if(incDrawing) { + let globalFrameWidth = outFrameWidth * (roll ? 2 : 1); let frames = inArray.length / numChannels; for(let n = 0; n < frames; ++n) { for(let c = 0; c < numChannels; ++c) { let inIndex = c * frames + n; - outIndex = c * outFrameWidth + rollPtr; + let outIndex = c * globalFrameWidth + rollPtr; globalArray[outIndex] = inToOut(c, inArray[inIndex]); } rollPtr++; - rollPtr %= outFrameWidth; + rollPtr %= globalFrameWidth; } - for(let i = 0; i < outArray.length; ++i) - outArray[i] = globalArray[i]; + if(roll) { + for(let n = 0; n < outFrameWidth; ++n) { + for(let c = 0; c < numChannels; ++c) { + let offset = (globalFrameWidth + n + rollPtr - outFrameWidth) % globalFrameWidth; + outArray[c * outFrameWidth + n] = globalArray[(c * globalFrameWidth + offset)]; + } + } + } else + for(let i = 0; i < outArray.length; ++i) + outArray[i] = globalArray[i]; } else { if (inArray.length !== inArrayWidth) { console.log(inArray.length, inArrayWidth, inFrameWidth); From 8b0aea1e1a09e791fdf9e1813f3e6f3729801459 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 22 Aug 2023 17:59:42 -0500 Subject: [PATCH 058/188] Scope: added control for X axis behaviour --- IDE/frontend-dev/scope-src/scope-browser.js | 1 + IDE/public/scope/index.html | 12 ++++++++++++ IDE/public/scope/js/bundle.js | 1 + IDE/public/scope/js/scope-worker.js | 7 ++++--- libraries/Scope/Scope.cpp | 6 ++++-- libraries/Scope/Scope.h | 6 ++++++ 6 files changed, 28 insertions(+), 5 deletions(-) diff --git a/IDE/frontend-dev/scope-src/scope-browser.js b/IDE/frontend-dev/scope-src/scope-browser.js index 40782ad9b..cb7d522a2 100644 --- a/IDE/frontend-dev/scope-src/scope-browser.js +++ b/IDE/frontend-dev/scope-src/scope-browser.js @@ -478,6 +478,7 @@ settings.setData({ triggerDir : 0, triggerLevel : 0, xOffset : 0, + xAxisBehaviour: 0, upSampling : 1, downSampling : 1, FFTLength : 1024, diff --git a/IDE/public/scope/index.html b/IDE/public/scope/index.html index b1270e8f4..a081aa1a5 100644 --- a/IDE/public/scope/index.html +++ b/IDE/public/scope/index.html @@ -70,6 +70,18 @@

X-Axis

+
+

Behaviour:

+
+
+ + + +
diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index a4be6ff0d..b88bb12c0 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -1854,6 +1854,7 @@ settings.setData((_settings$setData = { triggerDir: 0, triggerLevel: 0, xOffset: 0, + xAxisBehaviour: 0, upSampling: 1, downSampling: 1, FFTLength: 1024, diff --git a/IDE/public/scope/js/scope-worker.js b/IDE/public/scope/js/scope-worker.js index 07ceed6b2..26abcd451 100644 --- a/IDE/public/scope/js/scope-worker.js +++ b/IDE/public/scope/js/scope-worker.js @@ -27,7 +27,7 @@ var ws_onopen = function(ws){ ws.onerror = undefined; }; -var zero = 0, triggerChannel = 0, xOffset = 0, triggerLevel = 0, numChannels = 0, upSampling = 0, downSampling = 1; +var zero = 0, triggerChannel = 0, xOffset = 0, triggerLevel = 0, numChannels = 0, upSampling = 0, downSampling = 1, xAxisBehaviour = 0; var inFrameWidth = 0, outFrameWidth = 0, inArrayWidth = 0, outArrayWidth = 0, interpolation = 0; const plotModeTimeDomain = 0; @@ -50,6 +50,7 @@ onmessage = function(e){ numChannels = settings.numChannels; upSampling = settings.upSampling; downSampling = settings.downSampling; + xAxisBehaviour = settings.xAxisBehaviour; inFrameWidth = Math.floor(settings.frameWidth/upSampling); outFrameWidth = settings.frameWidth; @@ -82,8 +83,8 @@ var ws_onmessage = function(ws, e){ // console.log("worker: recieved buffer of length "+inArray.length, inArrayWidth); // console.log(settings.frameHeight, settings.numChannels, settings.frameWidth, channelConfig); - let roll = false; - let incDrawing = downSampling > 8; + let roll = 2 == xAxisBehaviour; + let incDrawing = downSampling > 1 && 0 != xAxisBehaviour; globalArray.length = outArrayWidth * (roll ? 2 : 1); var outArray = new Float32Array(outArrayWidth); diff --git a/libraries/Scope/Scope.cpp b/libraries/Scope/Scope.cpp index fa59db15d..98844b1eb 100644 --- a/libraries/Scope/Scope.cpp +++ b/libraries/Scope/Scope.cpp @@ -274,9 +274,9 @@ void Scope::triggerTimeDomain(){ numRollSamples = 1; while (readPointer != writePointer){ timestamp++; - bool autoRoll = true; - if(downSampling > 8 && autoRoll) + if(downSampling > 1 && X_NORMAL != xAxisBehaviour) { + // send "rolling" blocks without waiting for a trigger rollPtr++; if(rollPtr >= numRollSamples) { @@ -544,6 +544,8 @@ void Scope::setSetting(std::wstring setting, float value){ } else if (setting.compare(L"xOffset") == 0){ xOffset = (int)value; setXParams(); + } else if (setting.compare(L"xAxisBehaviour") == 0){ + xAxisBehaviour = (XAxisBehaviour)value; } else if (setting.compare(L"upSampling") == 0){ stop(); upSampling = (int)value; diff --git a/libraries/Scope/Scope.h b/libraries/Scope/Scope.h index ad4e1b2ec..301c39677 100644 --- a/libraries/Scope/Scope.h +++ b/libraries/Scope/Scope.h @@ -32,6 +32,11 @@ class Scope{ NEGATIVE, ///< Trigger when crossing the threshold and the signal is decreasing BOTH, ///< Trigger on any crossing of the threshold. } TriggerSlope; + typedef enum { + X_NORMAL, ///< X-axis normal + X_INCREMENTAL, ///< X-axis incremental + X_ROLLING, ///< X-axis rolling + } XAxisBehaviour; Scope(); Scope(unsigned int numChannels, float sampleRate); @@ -119,6 +124,7 @@ class Scope{ TriggerMode triggerMode; unsigned int triggerChannel; TriggerSlope triggerDir; + XAxisBehaviour xAxisBehaviour = X_NORMAL; float triggerLevel; int xOffset; int xOffsetSamples; From abd4bcc14faae0b2a0de7ea5ab2bbd0d2d764b8a Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 22 Aug 2023 18:29:03 -0500 Subject: [PATCH 059/188] Scope: for incremental drawing, fade out older values --- IDE/frontend-dev/scope-src/scope-browser.js | 19 +++++++++++++++++-- IDE/public/scope/js/bundle.js | 18 ++++++++++++++++-- IDE/public/scope/js/scope-worker.js | 5 ++++- 3 files changed, 37 insertions(+), 5 deletions(-) diff --git a/IDE/frontend-dev/scope-src/scope-browser.js b/IDE/frontend-dev/scope-src/scope-browser.js index cb7d522a2..f8b079bf0 100644 --- a/IDE/frontend-dev/scope-src/scope-browser.js +++ b/IDE/frontend-dev/scope-src/scope-browser.js @@ -332,12 +332,16 @@ function CPU(data){ channelView.on('channelConfig', (config) => channelConfig = config ); let frame, length, plot = false; + let oldDataSeparator = -1; worker.onmessage = function(e) { - frame = e.data; + oldDataSeparator = e.data.oldDataSeparator; + frame = e.data.outArray; length = Math.floor(frame.length/numChannels); // if scope is paused, don't set the plot flag plot = !paused; + if(plot) + requestAnimationFrame(plotLoop); // interpolate the trigger sample to get the sub-pixel x-offset if (settings.getKey('plotMode') == 0){ @@ -361,7 +365,6 @@ function CPU(data){ }; function plotLoop(){ - requestAnimationFrame(plotLoop); if (plot){ plot = false; ctx.clear(); @@ -382,8 +385,20 @@ function CPU(data){ let curr = constrain(frame[iLength], minY, maxY); let next = constrain(frame[iLength + 1], minY, maxY); ctx.moveTo(0, curr + xOff*(next - curr)); + let lastAlpha = 1; for (var j=1; (j-xOff)= 0) { + let dist = (length + oldDataSeparator - j - 1) % length; + let alpha = dist < length / 2 ? 1 : 1 - (dist - length / 2) / (length / 2); + // throttle lineStyle() calls as they are CPU-heavy + if(Math.abs(alpha - lastAlpha) > 0.1 || (lastAlpha != 1 && alpha == 1)) { + lastAlpha = alpha; + ctx.lineStyle(channelConfig[i].lineWeight, channelConfig[i].color, alpha); + } + } ctx.lineTo(j-xOff, curr); } } diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index b88bb12c0..47c296d0e 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -1668,7 +1668,6 @@ function CPU(data) { // plotting { var plotLoop = function plotLoop() { - requestAnimationFrame(plotLoop); if (plot) { plot = false; ctx.clear(); @@ -1686,8 +1685,20 @@ function CPU(data) { var curr = constrain(frame[iLength], minY, maxY); var next = constrain(frame[iLength + 1], minY, maxY); ctx.moveTo(0, curr + xOff * (next - curr)); + var lastAlpha = 1; for (var j = 1; j - xOff < length; j++) { var _curr = constrain(frame[j + iLength], minY, maxY); + // when drawing incrementally, alpha will be 1 when close to the most + // recent and then progressively fade out for older values + if (oldDataSeparator >= 0) { + var dist = (length + oldDataSeparator - j - 1) % length; + var alpha = dist < length / 2 ? 1 : 1 - (dist - length / 2) / (length / 2); + // throttle lineStyle() calls as they are CPU-heavy + if (Math.abs(alpha - lastAlpha) > 0.1 || lastAlpha != 1 && alpha == 1) { + lastAlpha = alpha; + ctx.lineStyle(channelConfig[i].lineWeight, channelConfig[i].color, alpha); + } + } ctx.lineTo(j - xOff, _curr); } } @@ -1762,12 +1773,15 @@ function CPU(data) { var frame = void 0, length = void 0, plot = false; + var oldDataSeparator = -1; worker.onmessage = function (e) { - frame = e.data; + oldDataSeparator = e.data.oldDataSeparator; + frame = e.data.outArray; length = Math.floor(frame.length / numChannels); // if scope is paused, don't set the plot flag plot = !paused; + if (plot) requestAnimationFrame(plotLoop); // interpolate the trigger sample to get the sub-pixel x-offset if (settings.getKey('plotMode') == 0) { diff --git a/IDE/public/scope/js/scope-worker.js b/IDE/public/scope/js/scope-worker.js index 26abcd451..6d36b06c7 100644 --- a/IDE/public/scope/js/scope-worker.js +++ b/IDE/public/scope/js/scope-worker.js @@ -151,6 +151,9 @@ var ws_onmessage = function(ws, e){ // outArray[outArray.length - 1 - n] = outArray[outArray.length - upSampling - 1]; // } - postMessage(outArray, [outArray.buffer]); + postMessage({ + outArray: outArray, + oldDataSeparator: 1 == xAxisBehaviour ? rollPtr : -1, + }, [outArray.buffer]); }; From 09884050a8a8b2a6b483825bce13572866087d81 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 22 Aug 2023 23:09:54 -0500 Subject: [PATCH 060/188] Scope: if passing controlOnly=1, do not try to establish data websocket --- IDE/frontend-dev/scope-src/scope-browser.js | 11 +++++++---- IDE/public/scope/js/bundle.js | 11 +++++++---- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/IDE/frontend-dev/scope-src/scope-browser.js b/IDE/frontend-dev/scope-src/scope-browser.js index f8b079bf0..b2fda3978 100644 --- a/IDE/frontend-dev/scope-src/scope-browser.js +++ b/IDE/frontend-dev/scope-src/scope-browser.js @@ -4,14 +4,17 @@ let remoteHost = location.hostname + ":5432"; let qs = new URLSearchParams(location.search); let qsRemoteHost = qs.get("remoteHost"); +let qsControlOnly = qs.get("controlOnly"); if(qsRemoteHost) remoteHost = qsRemoteHost var wsRemote = "ws://" + remoteHost + "/"; var worker = new Worker("js/scope-worker.js"); -worker.postMessage({ - event: 'wsConnect', - remote: wsRemote, -}); +if(!qsControlOnly) { + worker.postMessage({ + event: 'wsConnect', + remote: wsRemote, + }); +} // models var Model = require('./Model'); diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index 47c296d0e..4bd9b9f91 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -1375,13 +1375,16 @@ function _defineProperty(obj, key, value) { if (key in obj) { Object.definePrope var remoteHost = location.hostname + ":5432"; var qs = new URLSearchParams(location.search); var qsRemoteHost = qs.get("remoteHost"); +var qsControlOnly = qs.get("controlOnly"); if (qsRemoteHost) remoteHost = qsRemoteHost; var wsRemote = "ws://" + remoteHost + "/"; var worker = new Worker("js/scope-worker.js"); -worker.postMessage({ - event: 'wsConnect', - remote: wsRemote -}); +if (!qsControlOnly) { + worker.postMessage({ + event: 'wsConnect', + remote: wsRemote + }); +} // models var Model = require('./Model'); From 277bcaec9f9223aaab68194aad1ecebbdaa1b8f8 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Wed, 23 Aug 2023 13:46:31 -0500 Subject: [PATCH 061/188] Scope: pixi updated to v6.5.10 --- IDE/public/scope/js/pixi.js | 77475 +++++++++++++++++----------------- 1 file changed, 38140 insertions(+), 39335 deletions(-) diff --git a/IDE/public/scope/js/pixi.js b/IDE/public/scope/js/pixi.js index d7e4565b5..52fd42b73 100644 --- a/IDE/public/scope/js/pixi.js +++ b/IDE/public/scope/js/pixi.js @@ -1,40026 +1,38831 @@ /*! - * pixi.js - v4.5.4 - * Compiled Mon, 24 Jul 2017 18:13:16 UTC + * pixi.js - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC * * pixi.js is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.PIXI = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) - (v < 0); -} - -//Computes absolute value of integer -exports.abs = function(v) { - var mask = v >> (INT_BITS-1); - return (v ^ mask) - mask; -} - -//Computes minimum of integers x and y -exports.min = function(x, y) { - return y ^ ((x ^ y) & -(x < y)); -} - -//Computes maximum of integers x and y -exports.max = function(x, y) { - return x ^ ((x ^ y) & -(x < y)); -} - -//Checks if a number is a power of two -exports.isPow2 = function(v) { - return !(v & (v-1)) && (!!v); -} - -//Computes log base 2 of v -exports.log2 = function(v) { - var r, shift; - r = (v > 0xFFFF) << 4; v >>>= r; - shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; - shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; - shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; - return r | (v >> 1); -} - -//Computes log base 10 of v -exports.log10 = function(v) { - return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : - (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : - (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; -} - -//Counts number of bits -exports.popCount = function(v) { - v = v - ((v >>> 1) & 0x55555555); - v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); - return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; -} - -//Counts number of trailing zeros -function countTrailingZeros(v) { - var c = 32; - v &= -v; - if (v) c--; - if (v & 0x0000FFFF) c -= 16; - if (v & 0x00FF00FF) c -= 8; - if (v & 0x0F0F0F0F) c -= 4; - if (v & 0x33333333) c -= 2; - if (v & 0x55555555) c -= 1; - return c; -} -exports.countTrailingZeros = countTrailingZeros; - -//Rounds to next power of 2 -exports.nextPow2 = function(v) { - v += v === 0; - --v; - v |= v >>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v + 1; -} - -//Rounds down to previous power of 2 -exports.prevPow2 = function(v) { - v |= v >>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v - (v>>>1); -} - -//Computes parity of word -exports.parity = function(v) { - v ^= v >>> 16; - v ^= v >>> 8; - v ^= v >>> 4; - v &= 0xf; - return (0x6996 >>> v) & 1; -} - -var REVERSE_TABLE = new Array(256); - -(function(tab) { - for(var i=0; i<256; ++i) { - var v = i, r = i, s = 7; - for (v >>>= 1; v; v >>>= 1) { - r <<= 1; - r |= v & 1; - --s; - } - tab[i] = (r << s) & 0xff; + /** + * @this {Promise} + */ + function finallyConstructor(callback) { + var constructor = this.constructor; + return this.then( + function(value) { + // @ts-ignore + return constructor.resolve(callback()).then(function() { + return value; + }); + }, + function(reason) { + // @ts-ignore + return constructor.resolve(callback()).then(function() { + // @ts-ignore + return constructor.reject(reason); + }); + } + ); } -})(REVERSE_TABLE); - -//Reverse bits in a 32 bit word -exports.reverse = function(v) { - return (REVERSE_TABLE[ v & 0xff] << 24) | - (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | - (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | - REVERSE_TABLE[(v >>> 24) & 0xff]; -} - -//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes -exports.interleave2 = function(x, y) { - x &= 0xFFFF; - x = (x | (x << 8)) & 0x00FF00FF; - x = (x | (x << 4)) & 0x0F0F0F0F; - x = (x | (x << 2)) & 0x33333333; - x = (x | (x << 1)) & 0x55555555; - - y &= 0xFFFF; - y = (y | (y << 8)) & 0x00FF00FF; - y = (y | (y << 4)) & 0x0F0F0F0F; - y = (y | (y << 2)) & 0x33333333; - y = (y | (y << 1)) & 0x55555555; - - return x | (y << 1); -} - -//Extracts the nth interleaved component -exports.deinterleave2 = function(v, n) { - v = (v >>> n) & 0x55555555; - v = (v | (v >>> 1)) & 0x33333333; - v = (v | (v >>> 2)) & 0x0F0F0F0F; - v = (v | (v >>> 4)) & 0x00FF00FF; - v = (v | (v >>> 16)) & 0x000FFFF; - return (v << 16) >> 16; -} - - -//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes -exports.interleave3 = function(x, y, z) { - x &= 0x3FF; - x = (x | (x<<16)) & 4278190335; - x = (x | (x<<8)) & 251719695; - x = (x | (x<<4)) & 3272356035; - x = (x | (x<<2)) & 1227133513; - - y &= 0x3FF; - y = (y | (y<<16)) & 4278190335; - y = (y | (y<<8)) & 251719695; - y = (y | (y<<4)) & 3272356035; - y = (y | (y<<2)) & 1227133513; - x |= (y << 1); - - z &= 0x3FF; - z = (z | (z<<16)) & 4278190335; - z = (z | (z<<8)) & 251719695; - z = (z | (z<<4)) & 3272356035; - z = (z | (z<<2)) & 1227133513; - - return x | (z << 2); -} - -//Extracts nth interleaved component of a 3-tuple -exports.deinterleave3 = function(v, n) { - v = (v >>> n) & 1227133513; - v = (v | (v>>>2)) & 3272356035; - v = (v | (v>>>4)) & 251719695; - v = (v | (v>>>8)) & 4278190335; - v = (v | (v>>>16)) & 0x3FF; - return (v<<22)>>22; -} - -//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) -exports.nextCombination = function(v) { - var t = v | (v - 1); - return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); -} - - -},{}],2:[function(require,module,exports){ -'use strict'; - -module.exports = earcut; - -function earcut(data, holeIndices, dim) { - - dim = dim || 2; - - var hasHoles = holeIndices && holeIndices.length, - outerLen = hasHoles ? holeIndices[0] * dim : data.length, - outerNode = linkedList(data, 0, outerLen, dim, true), - triangles = []; - - if (!outerNode) return triangles; - - var minX, minY, maxX, maxY, x, y, size; - - if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); - - // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox - if (data.length > 80 * dim) { - minX = maxX = data[0]; - minY = maxY = data[1]; - - for (var i = dim; i < outerLen; i += dim) { - x = data[i]; - y = data[i + 1]; - if (x < minX) minX = x; - if (y < minY) minY = y; - if (x > maxX) maxX = x; - if (y > maxY) maxY = y; - } - - // minX, minY and size are later used to transform coords into integers for z-order calculation - size = Math.max(maxX - minX, maxY - minY); - } - - earcutLinked(outerNode, triangles, dim, minX, minY, size); - - return triangles; -} - -// create a circular doubly linked list from polygon points in the specified winding order -function linkedList(data, start, end, dim, clockwise) { - var i, last; - - if (clockwise === (signedArea(data, start, end, dim) > 0)) { - for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); - } else { - for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); - } - - if (last && equals(last, last.next)) { - removeNode(last); - last = last.next; - } - - return last; -} - -// eliminate colinear or duplicate points -function filterPoints(start, end) { - if (!start) return start; - if (!end) end = start; - - var p = start, - again; - do { - again = false; - - if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { - removeNode(p); - p = end = p.prev; - if (p === p.next) return null; - again = true; - } else { - p = p.next; + function allSettled(arr) { + var P = this; + return new P(function(resolve, reject) { + if (!(arr && typeof arr.length !== 'undefined')) { + return reject( + new TypeError( + typeof arr + + ' ' + + arr + + ' is not iterable(cannot read property Symbol(Symbol.iterator))' + ) + ); + } + var args = Array.prototype.slice.call(arr); + if (args.length === 0) { return resolve([]); } + var remaining = args.length; + + function res(i, val) { + if (val && (typeof val === 'object' || typeof val === 'function')) { + var then = val.then; + if (typeof then === 'function') { + then.call( + val, + function(val) { + res(i, val); + }, + function(e) { + args[i] = { status: 'rejected', reason: e }; + if (--remaining === 0) { + resolve(args); + } + } + ); + return; + } } - } while (again || p !== end); - - return end; -} - -// main ear slicing loop which triangulates a polygon (given as a linked list) -function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { - if (!ear) return; - - // interlink polygon nodes in z-order - if (!pass && size) indexCurve(ear, minX, minY, size); - - var stop = ear, - prev, next; - - // iterate through ears, slicing them one by one - while (ear.prev !== ear.next) { - prev = ear.prev; - next = ear.next; - - if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) { - // cut off the triangle - triangles.push(prev.i / dim); - triangles.push(ear.i / dim); - triangles.push(next.i / dim); - - removeNode(ear); - - // skipping the next vertice leads to less sliver triangles - ear = next.next; - stop = next.next; - - continue; + args[i] = { status: 'fulfilled', value: val }; + if (--remaining === 0) { + resolve(args); } + } - ear = next; - - // if we looped through the whole remaining polygon and can't find any more ears - if (ear === stop) { - // try filtering points and slicing again - if (!pass) { - earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1); - - // if this didn't work, try curing all small self-intersections locally - } else if (pass === 1) { - ear = cureLocalIntersections(ear, triangles, dim); - earcutLinked(ear, triangles, dim, minX, minY, size, 2); + for (var i = 0; i < args.length; i++) { + res(i, args[i]); + } + }); + } - // as a last resort, try splitting the remaining polygon into two - } else if (pass === 2) { - splitEarcut(ear, triangles, dim, minX, minY, size); - } + // Store setTimeout reference so promise-polyfill will be unaffected by + // other code modifying setTimeout (like sinon.useFakeTimers()) + var setTimeoutFunc = setTimeout; - break; - } - } -} + function isArray(x) { + return Boolean(x && typeof x.length !== 'undefined'); + } -// check whether a polygon node forms a valid ear with adjacent nodes -function isEar(ear) { - var a = ear.prev, - b = ear, - c = ear.next; + function noop() {} - if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + // Polyfill for Function.prototype.bind + function bind(fn, thisArg) { + return function() { + fn.apply(thisArg, arguments); + }; + } - // now make sure we don't have other points inside the potential ear - var p = ear.next.next; + /** + * @constructor + * @param {Function} fn + */ + function Promise$1(fn) { + if (!(this instanceof Promise$1)) + { throw new TypeError('Promises must be constructed via new'); } + if (typeof fn !== 'function') { throw new TypeError('not a function'); } + /** @type {!number} */ + this._state = 0; + /** @type {!boolean} */ + this._handled = false; + /** @type {Promise|undefined} */ + this._value = undefined; + /** @type {!Array} */ + this._deferreds = []; + + doResolve(fn, this); + } - while (p !== ear.prev) { - if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && - area(p.prev, p, p.next) >= 0) return false; - p = p.next; + function handle(self, deferred) { + while (self._state === 3) { + self = self._value; } - - return true; -} - -function isEarHashed(ear, minX, minY, size) { - var a = ear.prev, - b = ear, - c = ear.next; - - if (area(a, b, c) >= 0) return false; // reflex, can't be an ear - - // triangle bbox; min & max are calculated like this for speed - var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), - minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), - maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), - maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); - - // z-order range for the current triangle bbox; - var minZ = zOrder(minTX, minTY, minX, minY, size), - maxZ = zOrder(maxTX, maxTY, minX, minY, size); - - // first look for points inside the triangle in increasing z-order - var p = ear.nextZ; - - while (p && p.z <= maxZ) { - if (p !== ear.prev && p !== ear.next && - pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && - area(p.prev, p, p.next) >= 0) return false; - p = p.nextZ; + if (self._state === 0) { + self._deferreds.push(deferred); + return; } + self._handled = true; + Promise$1._immediateFn(function() { + var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected; + if (cb === null) { + (self._state === 1 ? resolve$1 : reject)(deferred.promise, self._value); + return; + } + var ret; + try { + ret = cb(self._value); + } catch (e) { + reject(deferred.promise, e); + return; + } + resolve$1(deferred.promise, ret); + }); + } - // then look for points in decreasing z-order - p = ear.prevZ; - - while (p && p.z >= minZ) { - if (p !== ear.prev && p !== ear.next && - pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && - area(p.prev, p, p.next) >= 0) return false; - p = p.prevZ; + function resolve$1(self, newValue) { + try { + // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure + if (newValue === self) + { throw new TypeError('A promise cannot be resolved with itself.'); } + if ( + newValue && + (typeof newValue === 'object' || typeof newValue === 'function') + ) { + var then = newValue.then; + if (newValue instanceof Promise$1) { + self._state = 3; + self._value = newValue; + finale(self); + return; + } else if (typeof then === 'function') { + doResolve(bind(then, newValue), self); + return; + } + } + self._state = 1; + self._value = newValue; + finale(self); + } catch (e) { + reject(self, e); } + } - return true; -} - -// go through all polygon nodes and cure small local self-intersections -function cureLocalIntersections(start, triangles, dim) { - var p = start; - do { - var a = p.prev, - b = p.next.next; - - if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { - - triangles.push(a.i / dim); - triangles.push(p.i / dim); - triangles.push(b.i / dim); - - // remove two nodes involved - removeNode(p); - removeNode(p.next); + function reject(self, newValue) { + self._state = 2; + self._value = newValue; + finale(self); + } - p = start = b; - } - p = p.next; - } while (p !== start); - - return p; -} - -// try splitting polygon into two and triangulate them independently -function splitEarcut(start, triangles, dim, minX, minY, size) { - // look for a valid diagonal that divides the polygon into two - var a = start; - do { - var b = a.next.next; - while (b !== a.prev) { - if (a.i !== b.i && isValidDiagonal(a, b)) { - // split the polygon in two by the diagonal - var c = splitPolygon(a, b); - - // filter colinear points around the cuts - a = filterPoints(a, a.next); - c = filterPoints(c, c.next); - - // run earcut on each half - earcutLinked(a, triangles, dim, minX, minY, size); - earcutLinked(c, triangles, dim, minX, minY, size); - return; - } - b = b.next; + function finale(self) { + if (self._state === 2 && self._deferreds.length === 0) { + Promise$1._immediateFn(function() { + if (!self._handled) { + Promise$1._unhandledRejectionFn(self._value); } - a = a.next; - } while (a !== start); -} - -// link every hole into the outer loop, producing a single-ring polygon without holes -function eliminateHoles(data, holeIndices, outerNode, dim) { - var queue = [], - i, len, start, end, list; - - for (i = 0, len = holeIndices.length; i < len; i++) { - start = holeIndices[i] * dim; - end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; - list = linkedList(data, start, end, dim, false); - if (list === list.next) list.steiner = true; - queue.push(getLeftmost(list)); + }); } - queue.sort(compareX); - - // process holes from left to right - for (i = 0; i < queue.length; i++) { - eliminateHole(queue[i], outerNode); - outerNode = filterPoints(outerNode, outerNode.next); + for (var i = 0, len = self._deferreds.length; i < len; i++) { + handle(self, self._deferreds[i]); } + self._deferreds = null; + } - return outerNode; -} - -function compareX(a, b) { - return a.x - b.x; -} + /** + * @constructor + */ + function Handler(onFulfilled, onRejected, promise) { + this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; + this.onRejected = typeof onRejected === 'function' ? onRejected : null; + this.promise = promise; + } -// find a bridge between vertices that connects hole with an outer ring and and link it -function eliminateHole(hole, outerNode) { - outerNode = findHoleBridge(hole, outerNode); - if (outerNode) { - var b = splitPolygon(outerNode, hole); - filterPoints(b, b.next); - } -} - -// David Eberly's algorithm for finding a bridge between hole and outer polygon -function findHoleBridge(hole, outerNode) { - var p = outerNode, - hx = hole.x, - hy = hole.y, - qx = -Infinity, - m; - - // find a segment intersected by a ray from the hole's leftmost point to the left; - // segment's endpoint with lesser x will be potential connection point - do { - if (hy <= p.y && hy >= p.next.y) { - var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); - if (x <= hx && x > qx) { - qx = x; - if (x === hx) { - if (hy === p.y) return p; - if (hy === p.next.y) return p.next; - } - m = p.x < p.next.x ? p : p.next; - } + /** + * Take a potentially misbehaving resolver function and make sure + * onFulfilled and onRejected are only called once. + * + * Makes no guarantees about asynchrony. + */ + function doResolve(fn, self) { + var done = false; + try { + fn( + function(value) { + if (done) { return; } + done = true; + resolve$1(self, value); + }, + function(reason) { + if (done) { return; } + done = true; + reject(self, reason); } - p = p.next; - } while (p !== outerNode); - - if (!m) return null; - - if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint - - // look for points inside the triangle of hole point, segment intersection and endpoint; - // if there are no points found, we have a valid connection; - // otherwise choose the point of the minimum angle with the ray as connection point - - var stop = m, - mx = m.x, - my = m.y, - tanMin = Infinity, - tan; - - p = m.next; - - while (p !== stop) { - if (hx >= p.x && p.x >= mx && - pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + ); + } catch (ex) { + if (done) { return; } + done = true; + reject(self, ex); + } + } - tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + Promise$1.prototype['catch'] = function(onRejected) { + return this.then(null, onRejected); + }; - if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { - m = p; - tanMin = tan; - } - } + Promise$1.prototype.then = function(onFulfilled, onRejected) { + // @ts-ignore + var prom = new this.constructor(noop); - p = p.next; - } + handle(this, new Handler(onFulfilled, onRejected, prom)); + return prom; + }; - return m; -} - -// interlink polygon nodes in z-order -function indexCurve(start, minX, minY, size) { - var p = start; - do { - if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size); - p.prevZ = p.prev; - p.nextZ = p.next; - p = p.next; - } while (p !== start); - - p.prevZ.nextZ = null; - p.prevZ = null; - - sortLinked(p); -} - -// Simon Tatham's linked list merge sort algorithm -// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html -function sortLinked(list) { - var i, p, q, e, tail, numMerges, pSize, qSize, - inSize = 1; - - do { - p = list; - list = null; - tail = null; - numMerges = 0; - - while (p) { - numMerges++; - q = p; - pSize = 0; - for (i = 0; i < inSize; i++) { - pSize++; - q = q.nextZ; - if (!q) break; - } + Promise$1.prototype['finally'] = finallyConstructor; - qSize = inSize; - - while (pSize > 0 || (qSize > 0 && q)) { - - if (pSize === 0) { - e = q; - q = q.nextZ; - qSize--; - } else if (qSize === 0 || !q) { - e = p; - p = p.nextZ; - pSize--; - } else if (p.z <= q.z) { - e = p; - p = p.nextZ; - pSize--; - } else { - e = q; - q = q.nextZ; - qSize--; - } + Promise$1.all = function(arr) { + return new Promise$1(function(resolve, reject) { + if (!isArray(arr)) { + return reject(new TypeError('Promise.all accepts an array')); + } - if (tail) tail.nextZ = e; - else list = e; + var args = Array.prototype.slice.call(arr); + if (args.length === 0) { return resolve([]); } + var remaining = args.length; - e.prevZ = tail; - tail = e; + function res(i, val) { + try { + if (val && (typeof val === 'object' || typeof val === 'function')) { + var then = val.then; + if (typeof then === 'function') { + then.call( + val, + function(val) { + res(i, val); + }, + reject + ); + return; } - - p = q; + } + args[i] = val; + if (--remaining === 0) { + resolve(args); + } + } catch (ex) { + reject(ex); } + } - tail.nextZ = null; - inSize *= 2; - - } while (numMerges > 1); - - return list; -} - -// z-order of a point given coords and size of the data bounding box -function zOrder(x, y, minX, minY, size) { - // coords are transformed into non-negative 15-bit integer range - x = 32767 * (x - minX) / size; - y = 32767 * (y - minY) / size; - - x = (x | (x << 8)) & 0x00FF00FF; - x = (x | (x << 4)) & 0x0F0F0F0F; - x = (x | (x << 2)) & 0x33333333; - x = (x | (x << 1)) & 0x55555555; - - y = (y | (y << 8)) & 0x00FF00FF; - y = (y | (y << 4)) & 0x0F0F0F0F; - y = (y | (y << 2)) & 0x33333333; - y = (y | (y << 1)) & 0x55555555; - - return x | (y << 1); -} - -// find the leftmost node of a polygon ring -function getLeftmost(start) { - var p = start, - leftmost = start; - do { - if (p.x < leftmost.x) leftmost = p; - p = p.next; - } while (p !== start); - - return leftmost; -} - -// check if a point lies within a convex triangle -function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { - return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && - (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && - (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; -} - -// check if a diagonal between two polygon nodes is valid (lies in polygon interior) -function isValidDiagonal(a, b) { - return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && - locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); -} - -// signed area of a triangle -function area(p, q, r) { - return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); -} - -// check if two points are equal -function equals(p1, p2) { - return p1.x === p2.x && p1.y === p2.y; -} - -// check if two segments intersect -function intersects(p1, q1, p2, q2) { - if ((equals(p1, q1) && equals(p2, q2)) || - (equals(p1, q2) && equals(p2, q1))) return true; - return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && - area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; -} - -// check if a polygon diagonal intersects any polygon segments -function intersectsPolygon(a, b) { - var p = a; - do { - if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && - intersects(p, p.next, a, b)) return true; - p = p.next; - } while (p !== a); - - return false; -} - -// check if a polygon diagonal is locally inside the polygon -function locallyInside(a, b) { - return area(a.prev, a, a.next) < 0 ? - area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : - area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; -} - -// check if the middle point of a polygon diagonal is inside the polygon -function middleInside(a, b) { - var p = a, - inside = false, - px = (a.x + b.x) / 2, - py = (a.y + b.y) / 2; - do { - if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) - inside = !inside; - p = p.next; - } while (p !== a); - - return inside; -} - -// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; -// if one belongs to the outer ring and another to a hole, it merges it into a single ring -function splitPolygon(a, b) { - var a2 = new Node(a.i, a.x, a.y), - b2 = new Node(b.i, b.x, b.y), - an = a.next, - bp = b.prev; - - a.next = b; - b.prev = a; - - a2.next = an; - an.prev = a2; - - b2.next = a2; - a2.prev = b2; - - bp.next = b2; - b2.prev = bp; - - return b2; -} - -// create a node and optionally link it with previous one (in a circular doubly linked list) -function insertNode(i, x, y, last) { - var p = new Node(i, x, y); - - if (!last) { - p.prev = p; - p.next = p; + for (var i = 0; i < args.length; i++) { + res(i, args[i]); + } + }); + }; - } else { - p.next = last.next; - p.prev = last; - last.next.prev = p; - last.next = p; - } - return p; -} - -function removeNode(p) { - p.next.prev = p.prev; - p.prev.next = p.next; - - if (p.prevZ) p.prevZ.nextZ = p.nextZ; - if (p.nextZ) p.nextZ.prevZ = p.prevZ; -} - -function Node(i, x, y) { - // vertice index in coordinates array - this.i = i; - - // vertex coordinates - this.x = x; - this.y = y; - - // previous and next vertice nodes in a polygon ring - this.prev = null; - this.next = null; - - // z-order curve value - this.z = null; - - // previous and next nodes in z-order - this.prevZ = null; - this.nextZ = null; - - // indicates whether this is a steiner point - this.steiner = false; -} - -// return a percentage difference between the polygon area and its triangulation area; -// used to verify correctness of triangulation -earcut.deviation = function (data, holeIndices, dim, triangles) { - var hasHoles = holeIndices && holeIndices.length; - var outerLen = hasHoles ? holeIndices[0] * dim : data.length; - - var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); - if (hasHoles) { - for (var i = 0, len = holeIndices.length; i < len; i++) { - var start = holeIndices[i] * dim; - var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; - polygonArea -= Math.abs(signedArea(data, start, end, dim)); - } - } + Promise$1.allSettled = allSettled; - var trianglesArea = 0; - for (i = 0; i < triangles.length; i += 3) { - var a = triangles[i] * dim; - var b = triangles[i + 1] * dim; - var c = triangles[i + 2] * dim; - trianglesArea += Math.abs( - (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - - (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + Promise$1.resolve = function(value) { + if (value && typeof value === 'object' && value.constructor === Promise$1) { + return value; } - return polygonArea === 0 && trianglesArea === 0 ? 0 : - Math.abs((trianglesArea - polygonArea) / polygonArea); -}; + return new Promise$1(function(resolve) { + resolve(value); + }); + }; -function signedArea(data, start, end, dim) { - var sum = 0; - for (var i = start, j = end - dim; i < end; i += dim) { - sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); - j = i; - } - return sum; -} - -// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts -earcut.flatten = function (data) { - var dim = data[0][0].length, - result = {vertices: [], holes: [], dimensions: dim}, - holeIndex = 0; - - for (var i = 0; i < data.length; i++) { - for (var j = 0; j < data[i].length; j++) { - for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); - } - if (i > 0) { - holeIndex += data[i - 1].length; - result.holes.push(holeIndex); - } - } - return result; -}; + Promise$1.reject = function(value) { + return new Promise$1(function(resolve, reject) { + reject(value); + }); + }; -},{}],3:[function(require,module,exports){ -'use strict'; + Promise$1.race = function(arr) { + return new Promise$1(function(resolve, reject) { + if (!isArray(arr)) { + return reject(new TypeError('Promise.race accepts an array')); + } -var has = Object.prototype.hasOwnProperty - , prefix = '~'; + for (var i = 0, len = arr.length; i < len; i++) { + Promise$1.resolve(arr[i]).then(resolve, reject); + } + }); + }; -/** - * Constructor to create a storage for our `EE` objects. - * An `Events` instance is a plain object whose properties are event names. - * - * @constructor - * @api private - */ -function Events() {} - -// -// We try to not inherit from `Object.prototype`. In some engines creating an -// instance in this way is faster than calling `Object.create(null)` directly. -// If `Object.create(null)` is not supported we prefix the event names with a -// character to make sure that the built-in object properties are not -// overridden or used as an attack vector. -// -if (Object.create) { - Events.prototype = Object.create(null); + // Use polyfill for setImmediate for performance gains + Promise$1._immediateFn = + // @ts-ignore + (typeof setImmediate === 'function' && + function(fn) { + // @ts-ignore + setImmediate(fn); + }) || + function(fn) { + setTimeoutFunc(fn, 0); + }; - // - // This hack is needed because the `__proto__` property is still inherited in - // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. - // - if (!new Events().__proto__) prefix = false; -} + Promise$1._unhandledRejectionFn = function _unhandledRejectionFn(err) { + if (typeof console !== 'undefined' && console) { + console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console + } + }; -/** - * Representation of a single event listener. - * - * @param {Function} fn The listener function. - * @param {Mixed} context The context to invoke the listener with. - * @param {Boolean} [once=false] Specify if the listener is a one-time listener. - * @constructor - * @api private - */ -function EE(fn, context, once) { - this.fn = fn; - this.context = context; - this.once = once || false; -} - -/** - * Minimal `EventEmitter` interface that is molded against the Node.js - * `EventEmitter` interface. - * - * @constructor - * @api public - */ -function EventEmitter() { - this._events = new Events(); - this._eventsCount = 0; -} - -/** - * Return an array listing the events for which the emitter has registered - * listeners. - * - * @returns {Array} - * @api public - */ -EventEmitter.prototype.eventNames = function eventNames() { - var names = [] - , events - , name; + /* + object-assign + (c) Sindre Sorhus + @license MIT + */ - if (this._eventsCount === 0) return names; + 'use strict'; + /* eslint-disable no-unused-vars */ + var getOwnPropertySymbols = Object.getOwnPropertySymbols; + var hasOwnProperty$1 = Object.prototype.hasOwnProperty; + var propIsEnumerable = Object.prototype.propertyIsEnumerable; - for (name in (events = this._events)) { - if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); - } + function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } - if (Object.getOwnPropertySymbols) { - return names.concat(Object.getOwnPropertySymbols(events)); + return Object(val); } - return names; -}; - -/** - * Return the listeners registered for a given event. - * - * @param {String|Symbol} event The event name. - * @param {Boolean} exists Only check if there are listeners. - * @returns {Array|Boolean} - * @api public - */ -EventEmitter.prototype.listeners = function listeners(event, exists) { - var evt = prefix ? prefix + event : event - , available = this._events[evt]; - - if (exists) return !!available; - if (!available) return []; - if (available.fn) return [available.fn]; - - for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { - ee[i] = available[i].fn; + function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } } - return ee; -}; - -/** - * Calls each of the listeners registered for a given event. - * - * @param {String|Symbol} event The event name. - * @returns {Boolean} `true` if the event had listeners, else `false`. - * @api public - */ -EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { - var evt = prefix ? prefix + event : event; - - if (!this._events[evt]) return false; - - var listeners = this._events[evt] - , len = arguments.length - , args - , i; - - if (listeners.fn) { - if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); - - switch (len) { - case 1: return listeners.fn.call(listeners.context), true; - case 2: return listeners.fn.call(listeners.context, a1), true; - case 3: return listeners.fn.call(listeners.context, a1, a2), true; - case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; - case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; - case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; - } - - for (i = 1, args = new Array(len -1); i < len; i++) { - args[i - 1] = arguments[i]; - } - - listeners.fn.apply(listeners.context, args); - } else { - var length = listeners.length - , j; - - for (i = 0; i < length; i++) { - if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + var objectAssign = shouldUseNative() ? Object.assign : function (target, source) { + var arguments$1 = arguments; + + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments$1[s]); + + for (var key in from) { + if (hasOwnProperty$1.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; + }; - switch (len) { - case 1: listeners[i].fn.call(listeners[i].context); break; - case 2: listeners[i].fn.call(listeners[i].context, a1); break; - case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; - case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; - default: - if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { - args[j - 1] = arguments[j]; - } + /*! + * @pixi/polyfill - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/polyfill is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ - listeners[i].fn.apply(listeners[i].context, args); + if (typeof globalThis === 'undefined') { + if (typeof self !== 'undefined') { + // covers browsers + // @ts-expect-error not-writable ts(2540) error only on node + self.globalThis = self; + } + else if (typeof global !== 'undefined') { + // covers versions of Node < 12 + // @ts-expect-error not-writable ts(2540) error only on node + global.globalThis = global; } - } } - return true; -}; - -/** - * Add a listener for a given event. - * - * @param {String|Symbol} event The event name. - * @param {Function} fn The listener function. - * @param {Mixed} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @api public - */ -EventEmitter.prototype.on = function on(event, fn, context) { - var listener = new EE(fn, context || this) - , evt = prefix ? prefix + event : event; - - if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; - else if (!this._events[evt].fn) this._events[evt].push(listener); - else this._events[evt] = [this._events[evt], listener]; - - return this; -}; - -/** - * Add a one-time listener for a given event. - * - * @param {String|Symbol} event The event name. - * @param {Function} fn The listener function. - * @param {Mixed} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @api public - */ -EventEmitter.prototype.once = function once(event, fn, context) { - var listener = new EE(fn, context || this, true) - , evt = prefix ? prefix + event : event; - - if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; - else if (!this._events[evt].fn) this._events[evt].push(listener); - else this._events[evt] = [this._events[evt], listener]; - - return this; -}; - -/** - * Remove the listeners of a given event. - * - * @param {String|Symbol} event The event name. - * @param {Function} fn Only remove the listeners that match this function. - * @param {Mixed} context Only remove the listeners that have this context. - * @param {Boolean} once Only remove one-time listeners. - * @returns {EventEmitter} `this`. - * @api public - */ -EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { - var evt = prefix ? prefix + event : event; - - if (!this._events[evt]) return this; - if (!fn) { - if (--this._eventsCount === 0) this._events = new Events(); - else delete this._events[evt]; - return this; + // Support for IE 9 - 11 which does not include Promises + if (!globalThis.Promise) { + globalThis.Promise = Promise$1; } - var listeners = this._events[evt]; + // References: + if (!Object.assign) { + Object.assign = objectAssign; + } - if (listeners.fn) { - if ( - listeners.fn === fn - && (!once || listeners.once) - && (!context || listeners.context === context) - ) { - if (--this._eventsCount === 0) this._events = new Events(); - else delete this._events[evt]; - } - } else { - for (var i = 0, events = [], length = listeners.length; i < length; i++) { - if ( - listeners[i].fn !== fn - || (once && !listeners[i].once) - || (context && listeners[i].context !== context) - ) { - events.push(listeners[i]); + // References: + // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ + // https://gist.github.com/1579671 + // http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision + // https://gist.github.com/timhall/4078614 + // https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + // Expected to be used with Browserfiy + // Browserify automatically detects the use of `global` and passes the + // correct reference of `global`, `globalThis`, and finally `window` + var ONE_FRAME_TIME = 16; + // Date.now + if (!(Date.now && Date.prototype.getTime)) { + Date.now = function now() { + return new Date().getTime(); + }; + } + // performance.now + if (!(globalThis.performance && globalThis.performance.now)) { + var startTime_1 = Date.now(); + if (!globalThis.performance) { + globalThis.performance = {}; } - } - - // - // Reset the array, or remove it completely if we have no more listeners. - // - if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; - else if (--this._eventsCount === 0) this._events = new Events(); - else delete this._events[evt]; + globalThis.performance.now = function () { return Date.now() - startTime_1; }; } - - return this; -}; - -/** - * Remove all listeners, or those of the specified event. - * - * @param {String|Symbol} [event] The event name. - * @returns {EventEmitter} `this`. - * @api public - */ -EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; - - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) { - if (--this._eventsCount === 0) this._events = new Events(); - else delete this._events[evt]; - } - } else { - this._events = new Events(); - this._eventsCount = 0; + // requestAnimationFrame + var lastTime = Date.now(); + var vendors = ['ms', 'moz', 'webkit', 'o']; + for (var x = 0; x < vendors.length && !globalThis.requestAnimationFrame; ++x) { + var p = vendors[x]; + globalThis.requestAnimationFrame = globalThis[p + "RequestAnimationFrame"]; + globalThis.cancelAnimationFrame = globalThis[p + "CancelAnimationFrame"] + || globalThis[p + "CancelRequestAnimationFrame"]; + } + if (!globalThis.requestAnimationFrame) { + globalThis.requestAnimationFrame = function (callback) { + if (typeof callback !== 'function') { + throw new TypeError(callback + "is not a function"); + } + var currentTime = Date.now(); + var delay = ONE_FRAME_TIME + lastTime - currentTime; + if (delay < 0) { + delay = 0; + } + lastTime = currentTime; + return globalThis.self.setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; + } + if (!globalThis.cancelAnimationFrame) { + globalThis.cancelAnimationFrame = function (id) { return clearTimeout(id); }; } - return this; -}; - -// -// Alias methods names because people roll like that. -// -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; -EventEmitter.prototype.addListener = EventEmitter.prototype.on; - -// -// This function doesn't apply anymore. -// -EventEmitter.prototype.setMaxListeners = function setMaxListeners() { - return this; -}; - -// -// Expose the prefix. -// -EventEmitter.prefixed = prefix; - -// -// Allow `EventEmitter` to be imported as module namespace. -// -EventEmitter.EventEmitter = EventEmitter; - -// -// Expose the module. -// -if ('undefined' !== typeof module) { - module.exports = EventEmitter; -} - -},{}],4:[function(require,module,exports){ -/** - * isMobile.js v0.4.1 - * - * A simple library to detect Apple phones and tablets, - * Android phones and tablets, other mobile devices (like blackberry, mini-opera and windows phone), - * and any kind of seven inch device, via user agent sniffing. - * - * @author: Kai Mallea (kmallea@gmail.com) - * - * @license: http://creativecommons.org/publicdomain/zero/1.0/ - */ -(function (global) { - - var apple_phone = /iPhone/i, - apple_ipod = /iPod/i, - apple_tablet = /iPad/i, - android_phone = /(?=.*\bAndroid\b)(?=.*\bMobile\b)/i, // Match 'Android' AND 'Mobile' - android_tablet = /Android/i, - amazon_phone = /(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i, - amazon_tablet = /(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i, - windows_phone = /Windows Phone/i, - windows_tablet = /(?=.*\bWindows\b)(?=.*\bARM\b)/i, // Match 'Windows' AND 'ARM' - other_blackberry = /BlackBerry/i, - other_blackberry_10 = /BB10/i, - other_opera = /Opera Mini/i, - other_chrome = /(CriOS|Chrome)(?=.*\bMobile\b)/i, - other_firefox = /(?=.*\bFirefox\b)(?=.*\bMobile\b)/i, // Match 'Firefox' AND 'Mobile' - seven_inch = new RegExp( - '(?:' + // Non-capturing group - - 'Nexus 7' + // Nexus 7 - - '|' + // OR - - 'BNTV250' + // B&N Nook Tablet 7 inch - - '|' + // OR - - 'Kindle Fire' + // Kindle Fire - - '|' + // OR - - 'Silk' + // Kindle Fire, Silk Accelerated - - '|' + // OR - - 'GT-P1000' + // Galaxy Tab 7 inch - - ')', // End non-capturing group - - 'i'); // Case-insensitive matching - - var match = function(regex, userAgent) { - return regex.test(userAgent); - }; - - var IsMobileClass = function(userAgent) { - var ua = userAgent || navigator.userAgent; - - // Facebook mobile app's integrated browser adds a bunch of strings that - // match everything. Strip it out if it exists. - var tmp = ua.split('[FBAN'); - if (typeof tmp[1] !== 'undefined') { - ua = tmp[0]; - } - - // Twitter mobile app's integrated browser on iPad adds a "Twitter for - // iPhone" string. Same probable happens on other tablet platforms. - // This will confuse detection so strip it out if it exists. - tmp = ua.split('Twitter'); - if (typeof tmp[1] !== 'undefined') { - ua = tmp[0]; - } - - this.apple = { - phone: match(apple_phone, ua), - ipod: match(apple_ipod, ua), - tablet: !match(apple_phone, ua) && match(apple_tablet, ua), - device: match(apple_phone, ua) || match(apple_ipod, ua) || match(apple_tablet, ua) - }; - this.amazon = { - phone: match(amazon_phone, ua), - tablet: !match(amazon_phone, ua) && match(amazon_tablet, ua), - device: match(amazon_phone, ua) || match(amazon_tablet, ua) - }; - this.android = { - phone: match(amazon_phone, ua) || match(android_phone, ua), - tablet: !match(amazon_phone, ua) && !match(android_phone, ua) && (match(amazon_tablet, ua) || match(android_tablet, ua)), - device: match(amazon_phone, ua) || match(amazon_tablet, ua) || match(android_phone, ua) || match(android_tablet, ua) - }; - this.windows = { - phone: match(windows_phone, ua), - tablet: match(windows_tablet, ua), - device: match(windows_phone, ua) || match(windows_tablet, ua) - }; - this.other = { - blackberry: match(other_blackberry, ua), - blackberry10: match(other_blackberry_10, ua), - opera: match(other_opera, ua), - firefox: match(other_firefox, ua), - chrome: match(other_chrome, ua), - device: match(other_blackberry, ua) || match(other_blackberry_10, ua) || match(other_opera, ua) || match(other_firefox, ua) || match(other_chrome, ua) - }; - this.seven_inch = match(seven_inch, ua); - this.any = this.apple.device || this.android.device || this.windows.device || this.other.device || this.seven_inch; - - // excludes 'other' devices and ipods, targeting touchscreen phones - this.phone = this.apple.phone || this.android.phone || this.windows.phone; - - // excludes 7 inch devices, classifying as phone or tablet is left to the user - this.tablet = this.apple.tablet || this.android.tablet || this.windows.tablet; - - if (typeof window === 'undefined') { - return this; - } - }; - - var instantiate = function() { - var IM = new IsMobileClass(); - IM.Class = IsMobileClass; - return IM; - }; - - if (typeof module !== 'undefined' && module.exports && typeof window === 'undefined') { - //node - module.exports = IsMobileClass; - } else if (typeof module !== 'undefined' && module.exports && typeof window !== 'undefined') { - //browserify - module.exports = instantiate(); - } else if (typeof define === 'function' && define.amd) { - //AMD - define('isMobile', [], global.isMobile = instantiate()); - } else { - global.isMobile = instantiate(); - } + // References: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + if (!Math.sign) { + Math.sign = function mathSign(x) { + x = Number(x); + if (x === 0 || isNaN(x)) { + return x; + } + return x > 0 ? 1 : -1; + }; + } -})(this); - -},{}],5:[function(require,module,exports){ -/* -object-assign -(c) Sindre Sorhus -@license MIT -*/ - -'use strict'; -/* eslint-disable no-unused-vars */ -var getOwnPropertySymbols = Object.getOwnPropertySymbols; -var hasOwnProperty = Object.prototype.hasOwnProperty; -var propIsEnumerable = Object.prototype.propertyIsEnumerable; - -function toObject(val) { - if (val === null || val === undefined) { - throw new TypeError('Object.assign cannot be called with null or undefined'); - } - - return Object(val); -} - -function shouldUseNative() { - try { - if (!Object.assign) { - return false; - } - - // Detect buggy property enumeration order in older V8 versions. - - // https://bugs.chromium.org/p/v8/issues/detail?id=4118 - var test1 = new String('abc'); // eslint-disable-line no-new-wrappers - test1[5] = 'de'; - if (Object.getOwnPropertyNames(test1)[0] === '5') { - return false; - } - - // https://bugs.chromium.org/p/v8/issues/detail?id=3056 - var test2 = {}; - for (var i = 0; i < 10; i++) { - test2['_' + String.fromCharCode(i)] = i; - } - var order2 = Object.getOwnPropertyNames(test2).map(function (n) { - return test2[n]; - }); - if (order2.join('') !== '0123456789') { - return false; - } - - // https://bugs.chromium.org/p/v8/issues/detail?id=3056 - var test3 = {}; - 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { - test3[letter] = letter; - }); - if (Object.keys(Object.assign({}, test3)).join('') !== - 'abcdefghijklmnopqrst') { - return false; - } - - return true; - } catch (err) { - // We don't expect any of the above to throw, but better to be safe. - return false; - } -} - -module.exports = shouldUseNative() ? Object.assign : function (target, source) { - var from; - var to = toObject(target); - var symbols; - - for (var s = 1; s < arguments.length; s++) { - from = Object(arguments[s]); - - for (var key in from) { - if (hasOwnProperty.call(from, key)) { - to[key] = from[key]; - } - } - - if (getOwnPropertySymbols) { - symbols = getOwnPropertySymbols(from); - for (var i = 0; i < symbols.length; i++) { - if (propIsEnumerable.call(from, symbols[i])) { - to[symbols[i]] = from[symbols[i]]; - } - } - } - } - - return to; -}; - -},{}],6:[function(require,module,exports){ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; + // References: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger + if (!Number.isInteger) { + Number.isInteger = function numberIsInteger(value) { + return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; + }; + } -module.exports = Buffer; + if (!globalThis.ArrayBuffer) { + globalThis.ArrayBuffer = Array; + } + if (!globalThis.Float32Array) { + globalThis.Float32Array = Array; + } + if (!globalThis.Uint32Array) { + globalThis.Uint32Array = Array; + } + if (!globalThis.Uint16Array) { + globalThis.Uint16Array = Array; + } + if (!globalThis.Uint8Array) { + globalThis.Uint8Array = Array; + } + if (!globalThis.Int32Array) { + globalThis.Int32Array = Array; + } -},{}],7:[function(require,module,exports){ - -var Texture = require('./GLTexture'); + /*! + * @pixi/constants - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/constants is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * Different types of environments for WebGL. + * @static + * @memberof PIXI + * @name ENV + * @enum {number} + * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering prefer this environment. + * @property {number} WEBGL - Version 1 of WebGL + * @property {number} WEBGL2 - Version 2 of WebGL + */ + exports.ENV = void 0; + (function (ENV) { + ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; + ENV[ENV["WEBGL"] = 1] = "WEBGL"; + ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; + })(exports.ENV || (exports.ENV = {})); + /** + * Constant to identify the Renderer Type. + * @static + * @memberof PIXI + * @name RENDERER_TYPE + * @enum {number} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ + exports.RENDERER_TYPE = void 0; + (function (RENDERER_TYPE) { + RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; + RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; + })(exports.RENDERER_TYPE || (exports.RENDERER_TYPE = {})); + /** + * Bitwise OR of masks that indicate the buffers to be cleared. + * @static + * @memberof PIXI + * @name BUFFER_BITS + * @enum {number} + * @property {number} COLOR - Indicates the buffers currently enabled for color writing. + * @property {number} DEPTH - Indicates the depth buffer. + * @property {number} STENCIL - Indicates the stencil buffer. + */ + exports.BUFFER_BITS = void 0; + (function (BUFFER_BITS) { + BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; + BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; + BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; + })(exports.BUFFER_BITS || (exports.BUFFER_BITS = {})); + /** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * @memberof PIXI + * @name BLEND_MODES + * @enum {number} + * @property {number} NORMAL - + * @property {number} ADD - + * @property {number} MULTIPLY - + * @property {number} SCREEN - + * @property {number} OVERLAY - + * @property {number} DARKEN - + * @property {number} LIGHTEN - + * @property {number} COLOR_DODGE - + * @property {number} COLOR_BURN - + * @property {number} HARD_LIGHT - + * @property {number} SOFT_LIGHT - + * @property {number} DIFFERENCE - + * @property {number} EXCLUSION - + * @property {number} HUE - + * @property {number} SATURATION - + * @property {number} COLOR - + * @property {number} LUMINOSITY - + * @property {number} NORMAL_NPM - + * @property {number} ADD_NPM - + * @property {number} SCREEN_NPM - + * @property {number} NONE - + * @property {number} SRC_IN - + * @property {number} SRC_OUT - + * @property {number} SRC_ATOP - + * @property {number} DST_OVER - + * @property {number} DST_IN - + * @property {number} DST_OUT - + * @property {number} DST_ATOP - + * @property {number} SUBTRACT - + * @property {number} SRC_OVER - + * @property {number} ERASE - + * @property {number} XOR - + */ + exports.BLEND_MODES = void 0; + (function (BLEND_MODES) { + BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; + BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; + BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; + BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; + BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; + BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; + BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; + BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; + BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; + BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; + BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; + BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; + BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; + BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; + BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; + BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; + BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; + BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; + BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; + BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; + BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; + BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; + BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; + BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; + BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; + BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; + BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; + BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; + BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; + BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; + BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; + BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; + })(exports.BLEND_MODES || (exports.BLEND_MODES = {})); + /** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * @memberof PIXI + * @static + * @name DRAW_MODES + * @enum {number} + * @property {number} POINTS - + * @property {number} LINES - + * @property {number} LINE_LOOP - + * @property {number} LINE_STRIP - + * @property {number} TRIANGLES - + * @property {number} TRIANGLE_STRIP - + * @property {number} TRIANGLE_FAN - + */ + exports.DRAW_MODES = void 0; + (function (DRAW_MODES) { + DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; + DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; + DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; + DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; + DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; + })(exports.DRAW_MODES || (exports.DRAW_MODES = {})); + /** + * Various GL texture/resources formats. + * @memberof PIXI + * @static + * @name FORMATS + * @enum {number} + * @property {number} [RGBA=6408] - + * @property {number} [RGB=6407] - + * @property {number} [RG=33319] - + * @property {number} [RED=6403] - + * @property {number} [RGBA_INTEGER=36249] - + * @property {number} [RGB_INTEGER=36248] - + * @property {number} [RG_INTEGER=33320] - + * @property {number} [RED_INTEGER=36244] - + * @property {number} [ALPHA=6406] - + * @property {number} [LUMINANCE=6409] - + * @property {number} [LUMINANCE_ALPHA=6410] - + * @property {number} [DEPTH_COMPONENT=6402] - + * @property {number} [DEPTH_STENCIL=34041] - + */ + exports.FORMATS = void 0; + (function (FORMATS) { + FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; + FORMATS[FORMATS["RGB"] = 6407] = "RGB"; + FORMATS[FORMATS["RG"] = 33319] = "RG"; + FORMATS[FORMATS["RED"] = 6403] = "RED"; + FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER"; + FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER"; + FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER"; + FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER"; + FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; + FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; + FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; + FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; + FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; + })(exports.FORMATS || (exports.FORMATS = {})); + /** + * Various GL target types. + * @memberof PIXI + * @static + * @name TARGETS + * @enum {number} + * @property {number} [TEXTURE_2D=3553] - + * @property {number} [TEXTURE_CUBE_MAP=34067] - + * @property {number} [TEXTURE_2D_ARRAY=35866] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_X=34069] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_X=34070] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Y=34071] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Y=34072] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Z=34073] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Z=34074] - + */ + exports.TARGETS = void 0; + (function (TARGETS) { + TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; + TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; + })(exports.TARGETS || (exports.TARGETS = {})); + /** + * Various GL data format types. + * @memberof PIXI + * @static + * @name TYPES + * @enum {number} + * @property {number} [UNSIGNED_BYTE=5121] - + * @property {number} [UNSIGNED_SHORT=5123] - + * @property {number} [UNSIGNED_SHORT_5_6_5=33635] - + * @property {number} [UNSIGNED_SHORT_4_4_4_4=32819] - + * @property {number} [UNSIGNED_SHORT_5_5_5_1=32820] - + * @property {number} [UNSIGNED_INT=5125] - + * @property {number} [UNSIGNED_INT_10F_11F_11F_REV=35899] - + * @property {number} [UNSIGNED_INT_2_10_10_10_REV=33640] - + * @property {number} [UNSIGNED_INT_24_8=34042] - + * @property {number} [UNSIGNED_INT_5_9_9_9_REV=35902] - + * @property {number} [BYTE=5120] - + * @property {number} [SHORT=5122] - + * @property {number} [INT=5124] - + * @property {number} [FLOAT=5126] - + * @property {number} [FLOAT_32_UNSIGNED_INT_24_8_REV=36269] - + * @property {number} [HALF_FLOAT=36193] - + */ + exports.TYPES = void 0; + (function (TYPES) { + TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; + TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; + TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; + TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; + TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV"; + TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV"; + TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8"; + TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV"; + TYPES[TYPES["BYTE"] = 5120] = "BYTE"; + TYPES[TYPES["SHORT"] = 5122] = "SHORT"; + TYPES[TYPES["INT"] = 5124] = "INT"; + TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; + TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV"; + TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; + })(exports.TYPES || (exports.TYPES = {})); + /** + * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively. + * WebGL1 works only with FLOAT. + * @memberof PIXI + * @static + * @name SAMPLER_TYPES + * @enum {number} + * @property {number} [FLOAT=0] - + * @property {number} [INT=1] - + * @property {number} [UINT=2] - + */ + exports.SAMPLER_TYPES = void 0; + (function (SAMPLER_TYPES) { + SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT"; + SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT"; + SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT"; + })(exports.SAMPLER_TYPES || (exports.SAMPLER_TYPES = {})); + /** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * @memberof PIXI + * @static + * @name SCALE_MODES + * @enum {number} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ + exports.SCALE_MODES = void 0; + (function (SCALE_MODES) { + SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; + SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; + })(exports.SCALE_MODES || (exports.SCALE_MODES = {})); + /** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as WebGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * @name WRAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ + exports.WRAP_MODES = void 0; + (function (WRAP_MODES) { + WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; + WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; + WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; + })(exports.WRAP_MODES || (exports.WRAP_MODES = {})); + /** + * Mipmap filtering modes that are supported by pixi. + * + * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering. + * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`, + * or its `POW2` and texture dimensions are powers of 2. + * Due to platform restriction, `ON` option will work like `POW2` for webgl-1. + * + * This property only affects WebGL. + * @name MIPMAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} OFF - No mipmaps + * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2 + * @property {number} ON - Always generate mipmaps + * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource + * that supports buffering each level-of-detail. + */ + exports.MIPMAP_MODES = void 0; + (function (MIPMAP_MODES) { + MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; + MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; + MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; + MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL"; + })(exports.MIPMAP_MODES || (exports.MIPMAP_MODES = {})); + /** + * How to treat textures with premultiplied alpha + * @name ALPHA_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that. + * Option for compressed and data textures that are created from typed arrays. + * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload. + * Default option, used for all loaded images. + * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied + * Example: spine atlases with `_pma` suffix. + * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA. + * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD. + * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA. + */ + exports.ALPHA_MODES = void 0; + (function (ALPHA_MODES) { + ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; + ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; + ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; + ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA"; + })(exports.ALPHA_MODES || (exports.ALPHA_MODES = {})); + /** + * Configure whether filter textures are cleared after binding. + * + * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect + * this and skip clearing as an optimization. + * @name CLEAR_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture. + * @property {number} CLEAR - Always clear the filter texture. + * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending. + * @property {number} NO - Alias for BLEND, same as `false` in earlier versions + * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions + * @property {number} AUTO - Alias for BLIT + */ + exports.CLEAR_MODES = void 0; + (function (CLEAR_MODES) { + CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; + CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; + CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; + CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; + CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; + CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; + })(exports.CLEAR_MODES || (exports.CLEAR_MODES = {})); + /** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * @name GC_MODES + * @enum {number} + * @static + * @memberof PIXI + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ + exports.GC_MODES = void 0; + (function (GC_MODES) { + GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; + GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; + })(exports.GC_MODES || (exports.GC_MODES = {})); + /** + * Constants that specify float precision in shaders. + * @name PRECISION + * @memberof PIXI + * @constant + * @static + * @enum {string} + * @property {string} [LOW='lowp'] - + * @property {string} [MEDIUM='mediump'] - + * @property {string} [HIGH='highp'] - + */ + exports.PRECISION = void 0; + (function (PRECISION) { + PRECISION["LOW"] = "lowp"; + PRECISION["MEDIUM"] = "mediump"; + PRECISION["HIGH"] = "highp"; + })(exports.PRECISION || (exports.PRECISION = {})); + /** + * Constants for mask implementations. + * We use `type` suffix because it leads to very different behaviours + * @name MASK_TYPES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - Mask is ignored + * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap + * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil + * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture + * @property {number} COLOR - Color mask (RGBA) + */ + exports.MASK_TYPES = void 0; + (function (MASK_TYPES) { + MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; + MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; + MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; + MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; + MASK_TYPES[MASK_TYPES["COLOR"] = 4] = "COLOR"; + })(exports.MASK_TYPES || (exports.MASK_TYPES = {})); + /** + * Bitwise OR of masks that indicate the color channels that are rendered to. + * @static + * @memberof PIXI + * @name COLOR_MASK_BITS + * @enum {number} + * @property {number} RED - Red channel. + * @property {number} GREEN - Green channel + * @property {number} BLUE - Blue channel. + * @property {number} ALPHA - Alpha channel. + */ + exports.COLOR_MASK_BITS = void 0; + (function (COLOR_MASK_BITS) { + COLOR_MASK_BITS[COLOR_MASK_BITS["RED"] = 1] = "RED"; + COLOR_MASK_BITS[COLOR_MASK_BITS["GREEN"] = 2] = "GREEN"; + COLOR_MASK_BITS[COLOR_MASK_BITS["BLUE"] = 4] = "BLUE"; + COLOR_MASK_BITS[COLOR_MASK_BITS["ALPHA"] = 8] = "ALPHA"; + })(exports.COLOR_MASK_BITS || (exports.COLOR_MASK_BITS = {})); + /** + * Constants for multi-sampling antialiasing. + * @see PIXI.Framebuffer#multisample + * @name MSAA_QUALITY + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - No multisampling for this renderTexture + * @property {number} LOW - Try 2 samples + * @property {number} MEDIUM - Try 4 samples + * @property {number} HIGH - Try 8 samples + */ + exports.MSAA_QUALITY = void 0; + (function (MSAA_QUALITY) { + MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; + MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; + MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; + MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; + })(exports.MSAA_QUALITY || (exports.MSAA_QUALITY = {})); + /** + * Constants for various buffer types in Pixi + * @see PIXI.BUFFER_TYPE + * @name BUFFER_TYPE + * @memberof PIXI + * @static + * @enum {number} + * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer + * @property {number} ARRAY_BUFFER - buffer type for using attribute data + * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects + */ + exports.BUFFER_TYPE = void 0; + (function (BUFFER_TYPE) { + BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER"; + BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER"; + // NOT YET SUPPORTED + BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER"; + })(exports.BUFFER_TYPE || (exports.BUFFER_TYPE = {})); + + /*! + * @pixi/settings - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/settings is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ -/** - * Helper class to create a webGL Framebuffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param width {Number} the width of the drawing area of the frame buffer - * @param height {Number} the height of the drawing area of the frame buffer - */ -var Framebuffer = function(gl, width, height) -{ - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The frame buffer - * - * @member {WebGLFramebuffer} - */ - this.framebuffer = gl.createFramebuffer(); - - /** - * The stencil buffer - * - * @member {WebGLRenderbuffer} - */ - this.stencil = null; - - /** - * The stencil buffer - * - * @member {PIXI.glCore.GLTexture} - */ - this.texture = null; - - /** - * The width of the drawing area of the buffer - * - * @member {Number} - */ - this.width = width || 100; - /** - * The height of the drawing area of the buffer - * - * @member {Number} - */ - this.height = height || 100; -}; - -/** - * Adds a texture to the frame buffer - * @param texture {PIXI.glCore.GLTexture} - */ -Framebuffer.prototype.enableTexture = function(texture) -{ - var gl = this.gl; + var BrowserAdapter = { + /** + * Creates a canvas element of the given size. + * This canvas is created using the browser's native canvas element. + * @param width - width of the canvas + * @param height - height of the canvas + */ + createCanvas: function (width, height) { + var canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + return canvas; + }, + getWebGLRenderingContext: function () { return WebGLRenderingContext; }, + getNavigator: function () { return navigator; }, + getBaseUrl: function () { var _a; return ((_a = document.baseURI) !== null && _a !== void 0 ? _a : window.location.href); }, + fetch: function (url, options) { return fetch(url, options); }, + }; - this.texture = texture || new Texture(gl); + var appleIphone = /iPhone/i; + var appleIpod = /iPod/i; + var appleTablet = /iPad/i; + var appleUniversal = /\biOS-universal(?:.+)Mac\b/i; + var androidPhone = /\bAndroid(?:.+)Mobile\b/i; + var androidTablet = /Android/i; + var amazonPhone = /(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i; + var amazonTablet = /Silk/i; + var windowsPhone = /Windows Phone/i; + var windowsTablet = /\bWindows(?:.+)ARM\b/i; + var otherBlackBerry = /BlackBerry/i; + var otherBlackBerry10 = /BB10/i; + var otherOpera = /Opera Mini/i; + var otherChrome = /\b(CriOS|Chrome)(?:.+)Mobile/i; + var otherFirefox = /Mobile(?:.+)Firefox\b/i; + var isAppleTabletOnIos13 = function (navigator) { + return (typeof navigator !== 'undefined' && + navigator.platform === 'MacIntel' && + typeof navigator.maxTouchPoints === 'number' && + navigator.maxTouchPoints > 1 && + typeof MSStream === 'undefined'); + }; + function createMatch(userAgent) { + return function (regex) { return regex.test(userAgent); }; + } + function isMobile$1(param) { + var nav = { + userAgent: '', + platform: '', + maxTouchPoints: 0 + }; + if (!param && typeof navigator !== 'undefined') { + nav = { + userAgent: navigator.userAgent, + platform: navigator.platform, + maxTouchPoints: navigator.maxTouchPoints || 0 + }; + } + else if (typeof param === 'string') { + nav.userAgent = param; + } + else if (param && param.userAgent) { + nav = { + userAgent: param.userAgent, + platform: param.platform, + maxTouchPoints: param.maxTouchPoints || 0 + }; + } + var userAgent = nav.userAgent; + var tmp = userAgent.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + userAgent = tmp[0]; + } + tmp = userAgent.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + userAgent = tmp[0]; + } + var match = createMatch(userAgent); + var result = { + apple: { + phone: match(appleIphone) && !match(windowsPhone), + ipod: match(appleIpod), + tablet: !match(appleIphone) && + (match(appleTablet) || isAppleTabletOnIos13(nav)) && + !match(windowsPhone), + universal: match(appleUniversal), + device: (match(appleIphone) || + match(appleIpod) || + match(appleTablet) || + match(appleUniversal) || + isAppleTabletOnIos13(nav)) && + !match(windowsPhone) + }, + amazon: { + phone: match(amazonPhone), + tablet: !match(amazonPhone) && match(amazonTablet), + device: match(amazonPhone) || match(amazonTablet) + }, + android: { + phone: (!match(windowsPhone) && match(amazonPhone)) || + (!match(windowsPhone) && match(androidPhone)), + tablet: !match(windowsPhone) && + !match(amazonPhone) && + !match(androidPhone) && + (match(amazonTablet) || match(androidTablet)), + device: (!match(windowsPhone) && + (match(amazonPhone) || + match(amazonTablet) || + match(androidPhone) || + match(androidTablet))) || + match(/\bokhttp\b/i) + }, + windows: { + phone: match(windowsPhone), + tablet: match(windowsTablet), + device: match(windowsPhone) || match(windowsTablet) + }, + other: { + blackberry: match(otherBlackBerry), + blackberry10: match(otherBlackBerry10), + opera: match(otherOpera), + firefox: match(otherFirefox), + chrome: match(otherChrome), + device: match(otherBlackBerry) || + match(otherBlackBerry10) || + match(otherOpera) || + match(otherFirefox) || + match(otherChrome) + }, + any: false, + phone: false, + tablet: false + }; + result.any = + result.apple.device || + result.android.device || + result.windows.device || + result.other.device; + result.phone = + result.apple.phone || result.android.phone || result.windows.phone; + result.tablet = + result.apple.tablet || result.android.tablet || result.windows.tablet; + return result; + } - this.texture.bind(); + var isMobile = isMobile$1(globalThis.navigator); - //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + /** + * Uploading the same buffer multiple times in a single frame can cause performance issues. + * Apparent on iOS so only check for that at the moment + * This check may become more complex if this issue pops up elsewhere. + * @private + * @returns {boolean} `true` if the same buffer may be uploaded more than once. + */ + function canUploadSameBuffer() { + return !isMobile.apple.device; + } - this.bind(); + /** + * The maximum recommended texture units to use. + * In theory the bigger the better, and for desktop we'll use as many as we can. + * But some mobile devices slow down if there is to many branches in the shader. + * So in practice there seems to be a sweet spot size that varies depending on the device. + * + * In v4, all mobile devices were limited to 4 texture units because for this. + * In v5, we allow all texture units to be used on modern Apple or Android devices. + * @private + * @param {number} max + * @returns {number} The maximum recommended texture units to use. + */ + function maxRecommendedTextures(max) { + var allowMax = true; + if (isMobile.tablet || isMobile.phone) { + if (isMobile.apple.device) { + var match = (navigator.userAgent).match(/OS (\d+)_(\d+)?/); + if (match) { + var majorVersion = parseInt(match[1], 10); + // Limit texture units on devices below iOS 11, which will be older hardware + if (majorVersion < 11) { + allowMax = false; + } + } + } + if (isMobile.android.device) { + var match = (navigator.userAgent).match(/Android\s([0-9.]*)/); + if (match) { + var majorVersion = parseInt(match[1], 10); + // Limit texture units on devices below Android 7 (Nougat), which will be older hardware + if (majorVersion < 7) { + allowMax = false; + } + } + } + } + return allowMax ? max : 4; + } - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); -}; + /** + * User's customizable globals for overriding the default PIXI settings, such + * as a renderer's default resolution, framerate, float precision, etc. + * @example + * // Use the native window resolution as the default resolution + * // will support high-density displays when rendering + * PIXI.settings.RESOLUTION = window.devicePixelRatio; + * + * // Disable interpolation when scaling, will make texture be pixelated + * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; + * @namespace PIXI.settings + */ + var settings = { + /** + * This adapter is used to call methods that are platform dependent. + * For example `document.createElement` only runs on the web but fails in node environments. + * This allows us to support more platforms by abstracting away specific implementations per platform. + * + * By default the adapter is set to work in the browser. However you can create your own + * by implementing the `IAdapter` interface. See `IAdapter` for more information. + * @name ADAPTER + * @memberof PIXI.settings + * @type {PIXI.IAdapter} + * @default PIXI.BrowserAdapter + */ + ADAPTER: BrowserAdapter, + /** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * @static + * @name MIPMAP_TEXTURES + * @memberof PIXI.settings + * @type {PIXI.MIPMAP_MODES} + * @default PIXI.MIPMAP_MODES.POW2 + */ + MIPMAP_TEXTURES: exports.MIPMAP_MODES.POW2, + /** + * Default anisotropic filtering level of textures. + * Usually from 0 to 16 + * @static + * @name ANISOTROPIC_LEVEL + * @memberof PIXI.settings + * @type {number} + * @default 0 + */ + ANISOTROPIC_LEVEL: 0, + /** + * Default resolution / device pixel ratio of the renderer. + * @static + * @name RESOLUTION + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + RESOLUTION: 1, + /** + * Default filter resolution. + * @static + * @name FILTER_RESOLUTION + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + FILTER_RESOLUTION: 1, + /** + * Default filter samples. + * @static + * @name FILTER_MULTISAMPLE + * @memberof PIXI.settings + * @type {PIXI.MSAA_QUALITY} + * @default PIXI.MSAA_QUALITY.NONE + */ + FILTER_MULTISAMPLE: exports.MSAA_QUALITY.NONE, + /** + * The maximum textures that this device supports. + * @static + * @name SPRITE_MAX_TEXTURES + * @memberof PIXI.settings + * @type {number} + * @default 32 + */ + SPRITE_MAX_TEXTURES: maxRecommendedTextures(32), + // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 + // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + /** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * @static + * @name SPRITE_BATCH_SIZE + * @memberof PIXI.settings + * @type {number} + * @default 4096 + */ + SPRITE_BATCH_SIZE: 4096, + /** + * The default render options if none are supplied to {@link PIXI.Renderer} + * or {@link PIXI.CanvasRenderer}. + * @static + * @name RENDER_OPTIONS + * @memberof PIXI.settings + * @type {object} + * @property {boolean} [antialias=false] - {@link PIXI.IRendererOptions.antialias} + * @property {boolean} [autoDensity=false] - {@link PIXI.IRendererOptions.autoDensity} + * @property {number} [backgroundAlpha=1] - {@link PIXI.IRendererOptions.backgroundAlpha} + * @property {number} [backgroundColor=0x000000] - {@link PIXI.IRendererOptions.backgroundColor} + * @property {boolean} [clearBeforeRender=true] - {@link PIXI.IRendererOptions.clearBeforeRender} + * @property {number} [height=600] - {@link PIXI.IRendererOptions.height} + * @property {boolean} [preserveDrawingBuffer=false] - {@link PIXI.IRendererOptions.preserveDrawingBuffer} + * @property {boolean|'notMultiplied'} [useContextAlpha=true] - {@link PIXI.IRendererOptions.useContextAlpha} + * @property {HTMLCanvasElement} [view=null] - {@link PIXI.IRendererOptions.view} + * @property {number} [width=800] - {@link PIXI.IRendererOptions.width} + */ + RENDER_OPTIONS: { + view: null, + width: 800, + height: 600, + autoDensity: false, + backgroundColor: 0x000000, + backgroundAlpha: 1, + useContextAlpha: true, + clearBeforeRender: true, + antialias: false, + preserveDrawingBuffer: false, + }, + /** + * Default Garbage Collection mode. + * @static + * @name GC_MODE + * @memberof PIXI.settings + * @type {PIXI.GC_MODES} + * @default PIXI.GC_MODES.AUTO + */ + GC_MODE: exports.GC_MODES.AUTO, + /** + * Default Garbage Collection max idle. + * @static + * @name GC_MAX_IDLE + * @memberof PIXI.settings + * @type {number} + * @default 3600 + */ + GC_MAX_IDLE: 60 * 60, + /** + * Default Garbage Collection maximum check count. + * @static + * @name GC_MAX_CHECK_COUNT + * @memberof PIXI.settings + * @type {number} + * @default 600 + */ + GC_MAX_CHECK_COUNT: 60 * 10, + /** + * Default wrap modes that are supported by pixi. + * @static + * @name WRAP_MODE + * @memberof PIXI.settings + * @type {PIXI.WRAP_MODES} + * @default PIXI.WRAP_MODES.CLAMP + */ + WRAP_MODE: exports.WRAP_MODES.CLAMP, + /** + * Default scale mode for textures. + * @static + * @name SCALE_MODE + * @memberof PIXI.settings + * @type {PIXI.SCALE_MODES} + * @default PIXI.SCALE_MODES.LINEAR + */ + SCALE_MODE: exports.SCALE_MODES.LINEAR, + /** + * Default specify float precision in vertex shader. + * @static + * @name PRECISION_VERTEX + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.HIGH + */ + PRECISION_VERTEX: exports.PRECISION.HIGH, + /** + * Default specify float precision in fragment shader. + * iOS is best set at highp due to https://github.com/pixijs/pixi.js/issues/3742 + * @static + * @name PRECISION_FRAGMENT + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.MEDIUM + */ + PRECISION_FRAGMENT: isMobile.apple.device ? exports.PRECISION.HIGH : exports.PRECISION.MEDIUM, + /** + * Can we upload the same buffer in a single frame? + * @static + * @name CAN_UPLOAD_SAME_BUFFER + * @memberof PIXI.settings + * @type {boolean} + */ + CAN_UPLOAD_SAME_BUFFER: canUploadSameBuffer(), + /** + * Enables bitmap creation before image load. This feature is experimental. + * @static + * @name CREATE_IMAGE_BITMAP + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + CREATE_IMAGE_BITMAP: false, + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Advantages can include sharper image quality (like text) and faster rendering on canvas. + * The main disadvantage is movement of objects may appear less smooth. + * @static + * @constant + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + ROUND_PIXELS: false, + }; -/** - * Initialises the stencil buffer - */ -Framebuffer.prototype.enableStencil = function() -{ - if(this.stencil)return; + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - var gl = this.gl; + function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; + } - this.stencil = gl.createRenderbuffer(); + function createCommonjsModule(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function (path, base) { + return commonjsRequire(path, (base === undefined || base === null) ? module.path : base); + } + }, fn(module, module.exports), module.exports; + } - gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + function getDefaultExportFromNamespaceIfPresent (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n; + } - // TODO.. this is depth AND stencil? - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width , this.height ); + function getDefaultExportFromNamespaceIfNotNamed (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n; + } + function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var a = Object.defineProperty({}, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; + } -}; + function commonjsRequire () { + throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); + } -/** - * Erases the drawing area and fills it with a colour - * @param r {Number} the red value of the clearing colour - * @param g {Number} the green value of the clearing colour - * @param b {Number} the blue value of the clearing colour - * @param a {Number} the alpha value of the clearing colour - */ -Framebuffer.prototype.clear = function( r, g, b, a ) -{ - this.bind(); + var eventemitter3 = createCommonjsModule(function (module) { + 'use strict'; - var gl = this.gl; + var has = Object.prototype.hasOwnProperty + , prefix = '~'; - gl.clearColor(r, g, b, a); - gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); -}; + /** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ + function Events() {} -/** - * Binds the frame buffer to the WebGL context - */ -Framebuffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer ); -}; - -/** - * Unbinds the frame buffer to the WebGL context - */ -Framebuffer.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindFramebuffer(gl.FRAMEBUFFER, null ); -}; -/** - * Resizes the drawing area of the buffer to the given width and height - * @param width {Number} the new width - * @param height {Number} the new height - */ -Framebuffer.prototype.resize = function(width, height) -{ - var gl = this.gl; + // + // We try to not inherit from `Object.prototype`. In some engines creating an + // instance in this way is faster than calling `Object.create(null)` directly. + // If `Object.create(null)` is not supported we prefix the event names with a + // character to make sure that the built-in object properties are not + // overridden or used as an attack vector. + // + if (Object.create) { + Events.prototype = Object.create(null); - this.width = width; - this.height = height; + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) { prefix = false; } + } - if ( this.texture ) - { - this.texture.uploadData(null, width, height); - } + /** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ + function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; + } - if ( this.stencil ) - { - // update the stencil buffer width and height - gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + /** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ + function addListener(emitter, event, fn, context, once) { + if (typeof fn !== 'function') { + throw new TypeError('The listener must be a function'); } -}; -/** - * Destroys this buffer - */ -Framebuffer.prototype.destroy = function() -{ - var gl = this.gl; - - //TODO - if(this.texture) - { - this.texture.destroy(); - } + var listener = new EE(fn, context || emitter, once) + , evt = prefix ? prefix + event : event; - gl.deleteFramebuffer(this.framebuffer); + if (!emitter._events[evt]) { emitter._events[evt] = listener, emitter._eventsCount++; } + else if (!emitter._events[evt].fn) { emitter._events[evt].push(listener); } + else { emitter._events[evt] = [emitter._events[evt], listener]; } - this.gl = null; + return emitter; + } - this.stencil = null; - this.texture = null; -}; + /** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ + function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) { emitter._events = new Events(); } + else { delete emitter._events[evt]; } + } -/** - * Creates a frame buffer with a texture containing the given data - * @static - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param width {Number} the width of the drawing area of the frame buffer - * @param height {Number} the height of the drawing area of the frame buffer - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - */ -Framebuffer.createRGBA = function(gl, width, height, data) -{ - var texture = Texture.fromData(gl, null, width, height); - texture.enableNearestScaling(); - texture.enableWrapClamp(); - - //now create the framebuffer object and attach the texture to it. - var fbo = new Framebuffer(gl, width, height); - fbo.enableTexture(texture); - - //fbo.enableStencil(); // get this back on soon! - - fbo.unbind(); - - return fbo; -}; - -/** - * Creates a frame buffer with a texture containing the given data - * @static - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param width {Number} the width of the drawing area of the frame buffer - * @param height {Number} the height of the drawing area of the frame buffer - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - */ -Framebuffer.createFloat32 = function(gl, width, height, data) -{ - // create a new texture.. - var texture = new Texture.fromData(gl, data, width, height); - texture.enableNearestScaling(); - texture.enableWrapClamp(); + /** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ + function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; + } - //now create the framebuffer object and attach the texture to it. - var fbo = new Framebuffer(gl, width, height); - fbo.enableTexture(texture); + /** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ + EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; - fbo.unbind(); + if (this._eventsCount === 0) { return names; } - return fbo; -}; + for (name in (events = this._events)) { + if (has.call(events, name)) { names.push(prefix ? name.slice(1) : name); } + } -module.exports = Framebuffer; + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } -},{"./GLTexture":9}],8:[function(require,module,exports){ + return names; + }; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); + /** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ + EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; -/** - * Helper class to create a webGL Shader - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} - * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. - * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. - * @param precision {precision]} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} - */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) -{ - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } - - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); - - this.uniformData = extractUniforms(gl, this.program); - - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); - -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; - -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + if (!handlers) { return []; } + if (handlers.fn) { return [handlers.fn]; } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } + return ee; + }; -module.exports = Shader; + /** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ + EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; -},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18,"./shader/setPrecision":22}],9:[function(require,module,exports){ + if (!listeners) { return 0; } + if (listeners.fn) { return 1; } + return listeners.length; + }; -/** - * Helper class to create a WebGL Texture - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL context - * @param width {number} the width of the texture - * @param height {number} the height of the texture - * @param format {number} the pixel format of the texture. defaults to gl.RGBA - * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE - */ -var Texture = function(gl, width, height, format, type) -{ - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); - - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; - - - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; - - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; - - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; - - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; - - -}; - -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + /** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ + EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var arguments$1 = arguments; - var gl = this.gl; + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) { return false; } - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + var listeners = this._events[evt] + , len = arguments.length + , args + , i; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (listeners.fn) { + if (listeners.once) { this.removeListener(event, listeners.fn, undefined, true); } - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments$1[i]; + } -}; + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; -var FLOATING_POINT_AVAILABLE = false; + for (i = 0; i < length; i++) { + if (listeners[i].once) { this.removeListener(event, listeners[i].fn, undefined, true); } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); - - var gl = this.gl; - - - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); - - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } - - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } - - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); - - - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } - - this.width = width; - this.height = height; - - -// texSubImage2D -}; - -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) { for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments$1[j]; + } } - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + listeners[i].fn.apply(listeners[i].context, args); + } + } + } - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + return true; + }; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; - -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; - - this.bind(); - - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; - -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + /** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); + }; - this.bind(); + /** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); + }; - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + /** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + if (!this._events[evt]) { return this; } + if (!fn) { + clearEvent(this, evt); + return this; + } - this.bind(); + var listeners = this._events[evt]; - this.mipmap = true; + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } - gl.generateMipmap(gl.TEXTURE_2D); -}; + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) { this._events[evt] = events.length === 1 ? events[0] : events; } + else { clearEvent(this, evt); } + } -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; - -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; - -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + return this; + }; - this.bind(); + /** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) { clearEvent(this, evt); } + } else { + this._events = new Events(); + this._eventsCount = 0; + } -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return this; + }; - this.bind(); + // + // Alias methods names because people roll like that. + // + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + EventEmitter.prototype.addListener = EventEmitter.prototype.on; - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + // + // Expose the prefix. + // + EventEmitter.prefixed = prefix; -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; + // + // Allow `EventEmitter` to be imported as module namespace. + // + EventEmitter.EventEmitter = EventEmitter; - this.bind(); + // + // Expose the module. + // + if ('undefined' !== 'object') { + module.exports = EventEmitter; + } + }); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; + 'use strict'; + var earcut_1 = earcut; + var _default = earcut; -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); + function earcut(data, holeIndices, dim) { - return texture; -}; + dim = dim || 2; + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; -module.exports = Texture; + if (!outerNode || outerNode.next === outerNode.prev) { return triangles; } -},{}],10:[function(require,module,exports){ + var minX, minY, maxX, maxY, x, y, invSize; -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); + if (hasHoles) { outerNode = eliminateHoles(data, holeIndices, outerNode, dim); } -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - } + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; - this.nativeState = state; + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) { minX = x; } + if (y < minY) { minY = y; } + if (x > maxX) { maxX = x; } + if (y > maxY) { maxY = y; } + } - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 32767 / invSize : 0; + } - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } + return triangles; + } - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; + // create a circular doubly linked list from polygon points in the specified winding order + function linkedList(data, start, end, dim, clockwise) { + var i, last; -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) { last = insertNode(i, data[i], data[i + 1], last); } + } else { + for (i = end - dim; i >= start; i -= dim) { last = insertNode(i, data[i], data[i + 1], last); } + } - this.activate(); - } + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } - return this; -}; + return last; + } -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } + // eliminate colinear or duplicate points + function filterPoints(start, end) { + if (!start) { return start; } + if (!end) { end = start; } - return this; -}; + var p = start, + again; + do { + again = false; -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) { break; } + again = true; - var gl = this.gl; - var lastBuffer = null; + } else { + p = p.next; + } + } while (again || p !== end); - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; + return end; + } - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } + // main ear slicing loop which triangulates a polygon (given as a linked list) + function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) { return; } - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - } + // interlink polygon nodes in z-order + if (!pass && invSize) { indexCurve(ear, minX, minY, invSize); } - setVertexAttribArrays(gl, this.attributes, this.nativeState); + var stop = ear, + prev, next; - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; - return this; -}; + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim | 0); + triangles.push(ear.i / dim | 0); + triangles.push(next.i / dim | 0); -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0 - }); + removeNode(ear); - this.dirty = true; + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; - return this; -}; + continue; + } -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; + ear = next; - this.dirty = true; + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); - return this; -}; + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(filterPoints(ear), triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } - this.attributes.length = 0; - this.indexBuffer = null; + break; + } + } + } - return this; -}; + // check whether a polygon node forms a valid ear with adjacent nodes + function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) { return false; } // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + var x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx), + y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy), + x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx), + y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy); + + var p = c.next; + while (p !== a) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && + area(p.prev, p, p.next) >= 0) { return false; } + p = p.next; + } -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start) -{ - var gl = this.gl; + return true; + } - if(this.indexBuffer) - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - else - { - // TODO need a better way to calculate size.. - gl.drawArrays(type, start, size || this.getSize()); - } + function isEarHashed(ear, minX, minY, invSize) { + var a = ear.prev, + b = ear, + c = ear.next; - return this; -}; + if (area(a, b, c) >= 0) { return false; } // reflex, can't be an ear -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } + var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; - this.nativeVaoExtension = null; - this.nativeVao = null; -}; + // triangle bbox; min & max are calculated like this for speed + var x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx), + y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy), + x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx), + y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy); -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; + // z-order range for the current triangle bbox; + var minZ = zOrder(x0, y0, minX, minY, invSize), + maxZ = zOrder(x1, y1, minX, minY, invSize); -},{"./setVertexAttribArrays":13}],11:[function(require,module,exports){ + var p = ear.prevZ, + n = ear.nextZ; -/** - * Helper class to create a webGL Context - * - * @class - * @memberof PIXI.glCore - * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from - * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available - * @return {WebGLRenderingContext} the WebGL context - */ -var createContext = function(canvas, options) -{ - var gl = canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); - - if (!gl) - { - // fail, not able to get a context - throw new Error('This browser does not support webGL. Try using the canvas renderer'); - } + // look for points inside the triangle in both directions + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) { return false; } + p = p.prevZ; - return gl; -}; - -module.exports = createContext; - -},{}],12:[function(require,module,exports){ -var gl = { - createContext: require('./createContext'), - setVertexAttribArrays: require('./setVertexAttribArrays'), - GLBuffer: require('./GLBuffer'), - GLFramebuffer: require('./GLFramebuffer'), - GLShader: require('./GLShader'), - GLTexture: require('./GLTexture'), - VertexArrayObject: require('./VertexArrayObject'), - shader: require('./shader') -}; - -// Export for Node-compatible environments -if (typeof module !== 'undefined' && module.exports) -{ - // Export the module - module.exports = gl; -} - -// Add to the browser window pixi.gl -if (typeof window !== 'undefined') -{ - // add the window object - window.PIXI = window.PIXI || {}; - window.PIXI.glCore = gl; -} - -},{"./GLBuffer":6,"./GLFramebuffer":7,"./GLShader":8,"./GLTexture":9,"./VertexArrayObject":10,"./createContext":11,"./setVertexAttribArrays":13,"./shader":19}],13:[function(require,module,exports){ -// var GL_MAP = {}; - -/** - * @param gl {WebGLRenderingContext} The current WebGL context - * @param attribs {*} - * @param state {*} - */ -var setVertexAttribArrays = function (gl, attribs, state) -{ - var i; - if(state) - { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; - - for (i = 0; i < tempAttribState.length; i++) - { - tempAttribState[i] = false; - } + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) { return false; } + n = n.nextZ; + } - // set the new attribs - for (i = 0; i < attribs.length; i++) - { - tempAttribState[attribs[i].attribute.location] = true; - } + // look for remaining points in decreasing z-order + while (p && p.z >= minZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) { return false; } + p = p.prevZ; + } + + // look for remaining points in increasing z-order + while (n && n.z <= maxZ) { + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) { return false; } + n = n.nextZ; + } - for (i = 0; i < attribState.length; i++) - { - if (attribState[i] !== tempAttribState[i]) - { - attribState[i] = tempAttribState[i]; + return true; + } - if (state.attribState[i]) - { - gl.enableVertexAttribArray(i); - } - else - { - gl.disableVertexAttribArray(i); - } - } - } + // go through all polygon nodes and cure small local self-intersections + function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; - } - else - { - for (i = 0; i < attribs.length; i++) - { - var attrib = attribs[i]; - gl.enableVertexAttribArray(attrib.attribute.location); - } - } -}; + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { -module.exports = setVertexAttribArrays; + triangles.push(a.i / dim | 0); + triangles.push(p.i / dim | 0); + triangles.push(b.i / dim | 0); -},{}],14:[function(require,module,exports){ + // remove two nodes involved + removeNode(p); + removeNode(p.next); -/** - * @class - * @memberof PIXI.glCore.shader - * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} - * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. - * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. - * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations - * @return {WebGLProgram} the shader program - */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) -{ - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - - var program = gl.createProgram(); - - gl.attachShader(program, glVertShader); - gl.attachShader(program, glFragShader); - - // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) - { - for(var i in attributeLocations) - { - gl.bindAttribLocation(program, attributeLocations[i], i); - } - } + p = start = b; + } + p = p.next; + } while (p !== start); + return filterPoints(p); + } - gl.linkProgram(program); + // try splitting polygon into two and triangulate them independently + function splitEarcut(start, triangles, dim, minX, minY, invSize) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, invSize, 0); + earcutLinked(c, triangles, dim, minX, minY, invSize, 0); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); + } - // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) - { - console.error('Pixi.js Error: Could not initialize shader.'); - console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); - console.error('gl.getError()', gl.getError()); + // link every hole into the outer loop, producing a single-ring polygon without holes + function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) { list.steiner = true; } + queue.push(getLeftmost(list)); + } - // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') - { - console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); - } + queue.sort(compareX); - gl.deleteProgram(program); - program = null; - } + // process holes from left to right + for (i = 0; i < queue.length; i++) { + outerNode = eliminateHole(queue[i], outerNode); + } - // clean up some shaders - gl.deleteShader(glVertShader); - gl.deleteShader(glFragShader); + return outerNode; + } - return program; -}; + function compareX(a, b) { + return a.x - b.x; + } -/** - * @private - * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} - * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER - * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. - * @return {WebGLShader} the shader - */ -var compileShader = function (gl, type, src) -{ - var shader = gl.createShader(type); + // find a bridge between vertices that connects hole with an outer ring and and link it + function eliminateHole(hole, outerNode) { + var bridge = findHoleBridge(hole, outerNode); + if (!bridge) { + return outerNode; + } - gl.shaderSource(shader, src); - gl.compileShader(shader); + var bridgeReverse = splitPolygon(bridge, hole); - if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) - { - console.log(gl.getShaderInfoLog(shader)); - return null; - } + // filter collinear points around the cuts + filterPoints(bridgeReverse, bridgeReverse.next); + return filterPoints(bridge, bridge.next); + } - return shader; -}; + // David Eberly's algorithm for finding a bridge between hole and outer polygon + function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + if (x === hx) { return m; } // hole touches outer segment; pick leftmost endpoint + } + } + p = p.next; + } while (p !== outerNode); -module.exports = compileProgram; + if (!m) { return null; } -},{}],15:[function(require,module,exports){ -/** - * @class - * @memberof PIXI.glCore.shader - * @param type {String} Type of value - * @param size {Number} - */ -var defaultValue = function(type, size) -{ - switch (type) - { - case 'float': - return 0; + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point - case 'vec2': - return new Float32Array(2 * size); + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; - case 'vec3': - return new Float32Array(3 * size); + p = m; - case 'vec4': - return new Float32Array(4 * size); - - case 'int': - case 'sampler2D': - return 0; + do { + if (hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { - case 'ivec2': - return new Int32Array(2 * size); + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential - case 'ivec3': - return new Int32Array(3 * size); + if (locallyInside(p, hole) && + (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) { + m = p; + tanMin = tan; + } + } - case 'ivec4': - return new Int32Array(4 * size); + p = p.next; + } while (p !== stop); - case 'bool': - return false; + return m; + } - case 'bvec2': + // whether sector in vertex m contains sector in vertex p in the same coordinates + function sectorContainsSector(m, p) { + return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; + } - return booleanArray( 2 * size); + // interlink polygon nodes in z-order + function indexCurve(start, minX, minY, invSize) { + var p = start; + do { + if (p.z === 0) { p.z = zOrder(p.x, p.y, minX, minY, invSize); } + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); - case 'bvec3': - return booleanArray(3 * size); + p.prevZ.nextZ = null; + p.prevZ = null; - case 'bvec4': - return booleanArray(4 * size); + sortLinked(p); + } - case 'mat2': - return new Float32Array([1, 0, - 0, 1]); + // Simon Tatham's linked list merge sort algorithm + // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html + function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) { break; } + } + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) { tail.nextZ = e; } + else { list = e; } + + e.prevZ = tail; + tail = e; + } + + p = q; + } - case 'mat3': - return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + tail.nextZ = null; + inSize *= 2; - case 'mat4': - return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); - } -}; + } while (numMerges > 1); -var booleanArray = function(size) -{ - var array = new Array(size); + return list; + } - for (var i = 0; i < array.length; i++) - { - array[i] = false; - } + // z-order of a point given coords and inverse of the longer side of data bbox + function zOrder(x, y, minX, minY, invSize) { + // coords are transformed into non-negative 15-bit integer range + x = (x - minX) * invSize | 0; + y = (y - minY) * invSize | 0; - return array; -}; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; -module.exports = defaultValue; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; -},{}],16:[function(require,module,exports){ + return x | (y << 1); + } -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); + // find the leftmost node of a polygon ring + function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) { leftmost = p; } + p = p.next; + } while (p !== start); -/** - * Extracts the attributes - * @class - * @memberof PIXI.glCore.shader - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param program {WebGLProgram} The shader program to get the attributes from - * @return attributes {Object} - */ -var extractAttributes = function(gl, program) -{ - var attributes = {}; - - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - - for (var i = 0; i < totalAttributes; i++) - { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); - - attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer - }; - } + return leftmost; + } - return attributes; -}; + // check if a point lies within a convex triangle + function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) >= (ax - px) * (cy - py) && + (ax - px) * (by - py) >= (bx - px) * (ay - py) && + (bx - px) * (cy - py) >= (cx - px) * (by - py); + } -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; + // check if a diagonal between two polygon nodes is valid (lies in polygon interior) + function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges + (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible + (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors + equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case + } -module.exports = extractAttributes; + // signed area of a triangle + function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); + } -},{"./mapSize":20,"./mapType":21}],17:[function(require,module,exports){ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); + // check if two points are equal + function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; + } -/** - * Extracts the uniforms - * @class - * @memberof PIXI.glCore.shader - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param program {WebGLProgram} The shader program to get the uniforms from - * @return uniforms {Object} - */ -var extractUniforms = function(gl, program) -{ - var uniforms = {}; - - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - - for (var i = 0; i < totalUniforms; i++) - { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); - - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; - } + // check if two segments intersect + function intersects(p1, q1, p2, q2) { + var o1 = sign$1(area(p1, q1, p2)); + var o2 = sign$1(area(p1, q1, q2)); + var o3 = sign$1(area(p2, q2, p1)); + var o4 = sign$1(area(p2, q2, q1)); - return uniforms; -}; + if (o1 !== o2 && o3 !== o4) { return true; } // general case -module.exports = extractUniforms; + if (o1 === 0 && onSegment(p1, p2, q1)) { return true; } // p1, q1 and p2 are collinear and p2 lies on p1q1 + if (o2 === 0 && onSegment(p1, q2, q1)) { return true; } // p1, q1 and q2 are collinear and q2 lies on p1q1 + if (o3 === 0 && onSegment(p2, p1, q2)) { return true; } // p2, q2 and p1 are collinear and p1 lies on p2q2 + if (o4 === 0 && onSegment(p2, q1, q2)) { return true; } // p2, q2 and q1 are collinear and q1 lies on p2q2 -},{"./defaultValue":15,"./mapType":21}],18:[function(require,module,exports){ -/** - * Extracts the attributes - * @class - * @memberof PIXI.glCore.shader - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param uniforms {Array} @mat ? - * @return attributes {Object} - */ -var generateUniformAccessObject = function(gl, uniformData) -{ - // this is the object we will be sending back. - // an object hierachy will be created for structs - var uniforms = {data:{}}; + return false; + } - uniforms.gl = gl; + // for collinear points p, q, r, check if point q lies on segment pr + function onSegment(p, q, r) { + return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); + } - var uniformKeys= Object.keys(uniformData); + function sign$1(num) { + return num > 0 ? 1 : num < 0 ? -1 : 0; + } - for (var i = 0; i < uniformKeys.length; i++) - { - var fullName = uniformKeys[i]; + // check if a polygon diagonal intersects any polygon segments + function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) { return true; } + p = p.next; + } while (p !== a); - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + return false; + } + // check if a polygon diagonal is locally inside the polygon + function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; + } - var uniformGroup = getUniformGroup(nameTokens, uniforms); + // check if the middle point of a polygon diagonal is inside the polygon + function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && + (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + { inside = !inside; } + p = p.next; + } while (p !== a); + + return inside; + } - var uniform = uniformData[fullName]; - uniformGroup.data[name] = uniform; + // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; + // if one belongs to the outer ring and another to a hole, it merges it into a single ring + function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; - uniformGroup.gl = gl; + a.next = b; + b.prev = a; - Object.defineProperty(uniformGroup, name, { - get: generateGetter(name), - set: generateSetter(name, uniform) - }); - } + a2.next = an; + an.prev = a2; - return uniforms; -}; + b2.next = a2; + a2.prev = b2; -var generateGetter = function(name) -{ - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + bp.next = b2; + b2.prev = bp; -var generateSetter = function(name, uniform) -{ - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + return b2; + } - if(uniform.size === 1) - { - setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; - } - else - { - setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; - } + // create a node and optionally link it with previous one (in a circular doubly linked list) + function insertNode(i, x, y, last) { + var p = new Node(i, x, y); - if(setTemplate) - { - template += "\nthis.gl." + setTemplate + ";"; - } + if (!last) { + p.prev = p; + p.next = p; - return new Function('value', template); // jshint ignore:line -}; + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; + } -var getUniformGroup = function(nameTokens, uniform) -{ - var cur = uniform; + function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; - for (var i = 0; i < nameTokens.length - 1; i++) - { - var o = cur[nameTokens[i]] || {data:{}}; - cur[nameTokens[i]] = o; - cur = o; - } + if (p.prevZ) { p.prevZ.nextZ = p.nextZ; } + if (p.nextZ) { p.nextZ.prevZ = p.prevZ; } + } - return cur; -}; + function Node(i, x, y) { + // vertex index in coordinates array + this.i = i; -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); + // vertex coordinates + this.x = x; + this.y = y; -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); + // previous and next vertex nodes in a polygon ring + this.prev = null; + this.next = null; + // z-order curve value + this.z = 0; -var GLSL_TO_SINGLE_SETTERS = { + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; - 'float': 'uniform1f(location, value)', + // indicates whether this is a steiner point + this.steiner = false; + } - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', + // return a percentage difference between the polygon area and its triangulation area; + // used to verify correctness of triangulation + earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); + }; - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', + function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; + } - 'sampler2D':'uniform1i(location, value)' -}; + // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts + earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; -var GLSL_TO_ARRAY_SETTERS = { + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) { result.vertices.push(data[i][j][d]); } + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; + }; + earcut_1.default = _default; + + var punycode = createCommonjsModule(function (module, exports) { + /*! https://mths.be/punycode v1.3.2 by @mathias */ + ;(function(root) { + + /** Detect free variables */ + var freeExports = 'object' == 'object' && exports && + !exports.nodeType && exports; + var freeModule = 'object' == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * http://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.3.2', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof undefined == 'function' && + typeof undefined.amd == 'object' && + undefined.amd + ) { + undefined('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { // in Rhino or a web browser + root.punycode = punycode; + } + + }(commonjsGlobal)); + }); - 'float': 'uniform1fv(location, value)', + 'use strict'; - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', + var util = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } + }; - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + // If obj.hasOwnProperty has been overridden, then calling + // obj.hasOwnProperty(prop) will break. + // See: https://github.com/joyent/node/issues/1707 + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', + var decode = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; - 'sampler2D':'uniform1iv(location, value)' -}; + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } -module.exports = generateUniformAccessObject; + var regexp = /\+/g; + qs = qs.split(sep); -},{}],19:[function(require,module,exports){ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; -},{"./compileProgram":14,"./defaultValue":15,"./extractAttributes":16,"./extractUniforms":17,"./generateUniformAccessObject":18,"./mapSize":20,"./mapType":21,"./setPrecision":22}],20:[function(require,module,exports){ -/** - * @class - * @memberof PIXI.glCore.shader - * @param type {String} - * @return {Number} - */ -var mapSize = function(type) -{ - return GLSL_TO_SIZE[type]; -}; + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (Array.isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } - 'sampler2D': 1 -}; + return obj; + }; -module.exports = mapSize; + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. -},{}],21:[function(require,module,exports){ + 'use strict'; + var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; -var mapSize = function(gl, type) -{ - if(!GL_TABLE) - { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + case 'boolean': + return v ? 'true' : 'false'; - GL_TABLE = {}; + case 'number': + return isFinite(v) ? v : ''; - for(var i = 0; i < typeNames.length; ++i) - { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; - } + default: + return ''; } + }; - return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D' -}; - -module.exports = mapSize; - -},{}],22:[function(require,module,exports){ -/** - * Sets the float precision on the shader. If the precision is already present this function will do nothing - * @param {string} src the shader source - * @param {string} precision The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * - * @return {string} modified shader source - */ -var setPrecision = function(src, precision) -{ - if(src.substring(0, 9) !== 'precision') - { - return 'precision ' + precision + ' float;\n' + src; + var encode = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; } - return src; -}; - -module.exports = setPrecision; - -},{}],23:[function(require,module,exports){ -(function (process){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// resolves . and .. elements in a path array with directory names there -// must be no slashes, empty elements, or device names (c:\) in the array -// (so also no leading and trailing slashes - it does not distinguish -// relative and absolute paths) -function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; + if (typeof obj === 'object') { + return Object.keys(obj).map(function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (Array.isArray(obj[k])) { + return obj[k].map(function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + } + + if (!name) { return ''; } + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); + }; + + var querystring = createCommonjsModule(function (module, exports) { + 'use strict'; + + exports.decode = exports.parse = decode; + exports.encode = exports.stringify = encode; + }); + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + + + + var parse = urlParse; + var resolve = urlResolve; + var resolveObject = urlResolveObject; + var format = urlFormat; + + var Url_1 = Url; + + function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; } - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } + // Reference: RFC 3986, RFC 1808, RFC 2396 + + // define these here so at least they only have to be + // compiled once on the first module load. + var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }; + + function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) { return url; } + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; } - return parts; -} - -// Split a filename into [root, dir, basename, ext], unix version -// 'root' is just a slash, or nothing. -var splitPathRe = - /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; -var splitPath = function(filename) { - return splitPathRe.exec(filename).slice(1); -}; - -// path.resolve([from ...], to) -// posix version -exports.resolve = function() { - var resolvedPath = '', - resolvedAbsolute = false; - - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = (i >= 0) ? arguments[i] : process.cwd(); - - // Skip empty and invalid entries - if (typeof path !== 'string') { - throw new TypeError('Arguments to path.resolve must be strings'); - } else if (!path) { - continue; + Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } } - resolvedPath = path + '/' + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; - } + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } - // Normalize the path - resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { - return !!p; - }), !resolvedAbsolute).join('/'); + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + { hostEnd = hec; } + } - return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; -}; + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } -// path.normalize(path) -// posix version -exports.normalize = function(path) { - var isAbsolute = exports.isAbsolute(path), - trailingSlash = substr(path, -1) === '/'; + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } - // Normalize the path - path = normalizeArray(filter(path.split('/'), function(p) { - return !!p; - }), !isAbsolute).join('/'); + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + { hostEnd = hec; } + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + { hostEnd = rest.length; } + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) { continue; } + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } - if (!path && !isAbsolute) { - path = '.'; - } - if (path && trailingSlash) { - path += '/'; - } + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } - return (isAbsolute ? '/' : '') + path; -}; + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } -// posix version -exports.isAbsolute = function(path) { - return path.charAt(0) === '/'; -}; + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; -// posix version -exports.join = function() { - var paths = Array.prototype.slice.call(arguments, 0); - return exports.normalize(filter(paths, function(p, index) { - if (typeof p !== 'string') { - throw new TypeError('Arguments to path.join must be strings'); + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } } - return p; - }).join('/')); -}; + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + { continue; } + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } -// path.relative(from, to) -// posix version -exports.relative = function(from, to) { - from = exports.resolve(from).substr(1); - to = exports.resolve(to).substr(1); - function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') break; + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) { this.pathname = rest; } + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; } - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') break; + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; } - if (start > end) return []; - return arr.slice(start, end - start + 1); + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; + }; + + // format a parsed object into a url string + function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) { obj = urlParse(obj); } + if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); } + return obj.format(); } - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); + Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); } - } - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } + var search = this.search || (query && ('?' + query)) || ''; - outputParts = outputParts.concat(toParts.slice(samePartsLength)); + if (protocol && protocol.substr(-1) !== ':') { protocol += ':'; } - return outputParts.join('/'); -}; + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') { pathname = '/' + pathname; } + } else if (!host) { + host = ''; + } -exports.sep = '/'; -exports.delimiter = ':'; + if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; } + if (search && search.charAt(0) !== '?') { search = '?' + search; } -exports.dirname = function(path) { - var result = splitPath(path), - root = result[0], - dir = result[1]; + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } + return protocol + host + pathname + search + hash; + }; - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); + function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); } - return root + dir; -}; - + Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); + }; -exports.basename = function(path, ext) { - var f = splitPath(path)[2]; - // TODO: make this comparison case-insensitive on windows? - if (ext && f.substr(-1 * ext.length) === ext) { - f = f.substr(0, f.length - ext.length); + function urlResolveObject(source, relative) { + if (!source) { return relative; } + return urlParse(source, false, true).resolveObject(relative); } - return f; -}; - - -exports.extname = function(path) { - return splitPath(path)[3]; -}; -function filter (xs, f) { - if (xs.filter) return xs.filter(f); - var res = []; - for (var i = 0; i < xs.length; i++) { - if (f(xs[i], i, xs)) res.push(xs[i]); + Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; } - return res; -} - -// String.prototype.substr - negative index don't work in IE8 -var substr = 'ab'.substr(-1) === 'b' - ? function (str, start, len) { return str.substr(start, len) } - : function (str, start, len) { - if (start < 0) start = str.length + start; - return str.substr(start, len); + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; } -; -}).call(this,require('_process')) + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; -},{"_process":24}],24:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + { result[rkey] = relative[rkey]; } + } -var cachedSetTimeout; -var cachedClearTimeout; + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } + result.href = result.format(); + return result; } + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())){ ; } + if (!relative.host) { relative.host = ''; } + if (!relative.hostname) { relative.hostname = ''; } + if (relPath[0] !== '') { relPath.unshift(''); } + if (relPath.length < 2) { relPath.unshift(''); } + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; } -} -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') { srcPath[0] = result.host; } + else { srcPath.unshift(result.host); } + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') { relPath[0] = relative.host; } + else { relPath.unshift(relative.host); } + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) { srcPath = []; } + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],25:[function(require,module,exports){ -(function (global){ -/*! https://mths.be/punycode v1.4.1 by @mathias */ -;(function(root) { - - /** Detect free variables */ - var freeExports = typeof exports == 'object' && exports && - !exports.nodeType && exports; - var freeModule = typeof module == 'object' && module && - !module.nodeType && module; - var freeGlobal = typeof global == 'object' && global; - if ( - freeGlobal.global === freeGlobal || - freeGlobal.window === freeGlobal || - freeGlobal.self === freeGlobal - ) { - root = freeGlobal; - } - - /** - * The `punycode` object. - * @name punycode - * @type Object - */ - var punycode, - - /** Highest positive signed 32-bit float value */ - maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 - - /** Bootstring parameters */ - base = 36, - tMin = 1, - tMax = 26, - skew = 38, - damp = 700, - initialBias = 72, - initialN = 128, // 0x80 - delimiter = '-', // '\x2D' - - /** Regular expressions */ - regexPunycode = /^xn--/, - regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars - regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators - - /** Error messages */ - errors = { - 'overflow': 'Overflow: input needs wider integers to process', - 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', - 'invalid-input': 'Invalid input' - }, - - /** Convenience shortcuts */ - baseMinusTMin = base - tMin, - floor = Math.floor, - stringFromCharCode = String.fromCharCode, - - /** Temporary variable */ - key; - - /*--------------------------------------------------------------------------*/ - - /** - * A generic error utility function. - * @private - * @param {String} type The error type. - * @returns {Error} Throws a `RangeError` with the applicable error message. - */ - function error(type) { - throw new RangeError(errors[type]); - } - - /** - * A generic `Array#map` utility function. - * @private - * @param {Array} array The array to iterate over. - * @param {Function} callback The function that gets called for every array - * item. - * @returns {Array} A new array of values returned by the callback function. - */ - function map(array, fn) { - var length = array.length; - var result = []; - while (length--) { - result[length] = fn(array[length]); - } - return result; - } - - /** - * A simple `Array#map`-like wrapper to work with domain name strings or email - * addresses. - * @private - * @param {String} domain The domain name or email address. - * @param {Function} callback The function that gets called for every - * character. - * @returns {Array} A new string of characters returned by the callback - * function. - */ - function mapDomain(string, fn) { - var parts = string.split('@'); - var result = ''; - if (parts.length > 1) { - // In email addresses, only the domain name should be punycoded. Leave - // the local part (i.e. everything up to `@`) intact. - result = parts[0] + '@'; - string = parts[1]; - } - // Avoid `split(regex)` for IE8 compatibility. See #17. - string = string.replace(regexSeparators, '\x2E'); - var labels = string.split('.'); - var encoded = map(labels, fn).join('.'); - return result + encoded; - } - - /** - * Creates an array containing the numeric code points of each Unicode - * character in the string. While JavaScript uses UCS-2 internally, - * this function will convert a pair of surrogate halves (each of which - * UCS-2 exposes as separate characters) into a single code point, - * matching UTF-16. - * @see `punycode.ucs2.encode` - * @see - * @memberOf punycode.ucs2 - * @name decode - * @param {String} string The Unicode input string (UCS-2). - * @returns {Array} The new array of code points. - */ - function ucs2decode(string) { - var output = [], - counter = 0, - length = string.length, - value, - extra; - while (counter < length) { - value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // high surrogate, and there is a next character - extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { // low surrogate - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else { - // unmatched surrogate; only append this code unit, in case the next - // code unit is the high surrogate of a surrogate pair - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; - } - - /** - * Creates a string based on an array of numeric code points. - * @see `punycode.ucs2.decode` - * @memberOf punycode.ucs2 - * @name encode - * @param {Array} codePoints The array of numeric code points. - * @returns {String} The new Unicode string (UCS-2). - */ - function ucs2encode(array) { - return map(array, function(value) { - var output = ''; - if (value > 0xFFFF) { - value -= 0x10000; - output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); - value = 0xDC00 | value & 0x3FF; - } - output += stringFromCharCode(value); - return output; - }).join(''); - } - - /** - * Converts a basic code point into a digit/integer. - * @see `digitToBasic()` - * @private - * @param {Number} codePoint The basic numeric code point value. - * @returns {Number} The numeric value of a basic code point (for use in - * representing integers) in the range `0` to `base - 1`, or `base` if - * the code point does not represent a value. - */ - function basicToDigit(codePoint) { - if (codePoint - 48 < 10) { - return codePoint - 22; - } - if (codePoint - 65 < 26) { - return codePoint - 65; - } - if (codePoint - 97 < 26) { - return codePoint - 97; - } - return base; - } - - /** - * Converts a digit/integer into a basic code point. - * @see `basicToDigit()` - * @private - * @param {Number} digit The numeric value of a basic code point. - * @returns {Number} The basic code point whose value (when used for - * representing integers) is `digit`, which needs to be in the range - * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is - * used; else, the lowercase form is used. The behavior is undefined - * if `flag` is non-zero and `digit` has no uppercase form. - */ - function digitToBasic(digit, flag) { - // 0..25 map to ASCII a..z or A..Z - // 26..35 map to ASCII 0..9 - return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); - } - - /** - * Bias adaptation function as per section 3.4 of RFC 3492. - * https://tools.ietf.org/html/rfc3492#section-3.4 - * @private - */ - function adapt(delta, numPoints, firstTime) { - var k = 0; - delta = firstTime ? floor(delta / damp) : delta >> 1; - delta += floor(delta / numPoints); - for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { - delta = floor(delta / baseMinusTMin); - } - return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); - } - - /** - * Converts a Punycode string of ASCII-only symbols to a string of Unicode - * symbols. - * @memberOf punycode - * @param {String} input The Punycode string of ASCII-only symbols. - * @returns {String} The resulting string of Unicode symbols. - */ - function decode(input) { - // Don't use UCS-2 - var output = [], - inputLength = input.length, - out, - i = 0, - n = initialN, - bias = initialBias, - basic, - j, - index, - oldi, - w, - k, - digit, - t, - /** Cached calculation results */ - baseMinusT; - - // Handle the basic code points: let `basic` be the number of input code - // points before the last delimiter, or `0` if there is none, then copy - // the first basic code points to the output. - - basic = input.lastIndexOf(delimiter); - if (basic < 0) { - basic = 0; - } - - for (j = 0; j < basic; ++j) { - // if it's not a basic code point - if (input.charCodeAt(j) >= 0x80) { - error('not-basic'); - } - output.push(input.charCodeAt(j)); - } - - // Main decoding loop: start just after the last delimiter if any basic code - // points were copied; start at the beginning otherwise. - - for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { - - // `index` is the index of the next character to be consumed. - // Decode a generalized variable-length integer into `delta`, - // which gets added to `i`. The overflow checking is easier - // if we increase `i` as we go, then subtract off its starting - // value at the end to obtain `delta`. - for (oldi = i, w = 1, k = base; /* no condition */; k += base) { - - if (index >= inputLength) { - error('invalid-input'); - } - - digit = basicToDigit(input.charCodeAt(index++)); - - if (digit >= base || digit > floor((maxInt - i) / w)) { - error('overflow'); - } - - i += digit * w; - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - - if (digit < t) { - break; - } - - baseMinusT = base - t; - if (w > floor(maxInt / baseMinusT)) { - error('overflow'); - } - - w *= baseMinusT; - - } - - out = output.length + 1; - bias = adapt(i - oldi, out, oldi == 0); - - // `i` was supposed to wrap around from `out` to `0`, - // incrementing `n` each time, so we'll fix that now: - if (floor(i / out) > maxInt - n) { - error('overflow'); - } - - n += floor(i / out); - i %= out; - - // Insert `n` at position `i` of the output - output.splice(i++, 0, n); - - } - - return ucs2encode(output); - } - - /** - * Converts a string of Unicode symbols (e.g. a domain name label) to a - * Punycode string of ASCII-only symbols. - * @memberOf punycode - * @param {String} input The string of Unicode symbols. - * @returns {String} The resulting Punycode string of ASCII-only symbols. - */ - function encode(input) { - var n, - delta, - handledCPCount, - basicLength, - bias, - j, - m, - q, - k, - t, - currentValue, - output = [], - /** `inputLength` will hold the number of code points in `input`. */ - inputLength, - /** Cached calculation results */ - handledCPCountPlusOne, - baseMinusT, - qMinusT; - - // Convert the input in UCS-2 to Unicode - input = ucs2decode(input); - - // Cache the length - inputLength = input.length; - - // Initialize the state - n = initialN; - delta = 0; - bias = initialBias; - - // Handle the basic code points - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue < 0x80) { - output.push(stringFromCharCode(currentValue)); - } - } - - handledCPCount = basicLength = output.length; - - // `handledCPCount` is the number of code points that have been handled; - // `basicLength` is the number of basic code points. - - // Finish the basic string - if it is not empty - with a delimiter - if (basicLength) { - output.push(delimiter); - } - - // Main encoding loop: - while (handledCPCount < inputLength) { - - // All non-basic code points < n have been handled already. Find the next - // larger one: - for (m = maxInt, j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue >= n && currentValue < m) { - m = currentValue; - } - } - - // Increase `delta` enough to advance the decoder's state to , - // but guard against overflow - handledCPCountPlusOne = handledCPCount + 1; - if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { - error('overflow'); - } - - delta += (m - n) * handledCPCountPlusOne; - n = m; - - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - - if (currentValue < n && ++delta > maxInt) { - error('overflow'); - } - - if (currentValue == n) { - // Represent delta as a generalized variable-length integer - for (q = delta, k = base; /* no condition */; k += base) { - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - if (q < t) { - break; - } - qMinusT = q - t; - baseMinusT = base - t; - output.push( - stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) - ); - q = floor(qMinusT / baseMinusT); - } - - output.push(stringFromCharCode(digitToBasic(q, 0))); - bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); - delta = 0; - ++handledCPCount; - } - } - - ++delta; - ++n; - - } - return output.join(''); - } - - /** - * Converts a Punycode string representing a domain name or an email address - * to Unicode. Only the Punycoded parts of the input will be converted, i.e. - * it doesn't matter if you call it on a string that has already been - * converted to Unicode. - * @memberOf punycode - * @param {String} input The Punycoded domain name or email address to - * convert to Unicode. - * @returns {String} The Unicode representation of the given Punycode - * string. - */ - function toUnicode(input) { - return mapDomain(input, function(string) { - return regexPunycode.test(string) - ? decode(string.slice(4).toLowerCase()) - : string; - }); - } - - /** - * Converts a Unicode string representing a domain name or an email address to - * Punycode. Only the non-ASCII parts of the domain name will be converted, - * i.e. it doesn't matter if you call it with a domain that's already in - * ASCII. - * @memberOf punycode - * @param {String} input The domain name or email address to convert, as a - * Unicode string. - * @returns {String} The Punycode representation of the given domain name or - * email address. - */ - function toASCII(input) { - return mapDomain(input, function(string) { - return regexNonASCII.test(string) - ? 'xn--' + encode(string) - : string; - }); - } - - /*--------------------------------------------------------------------------*/ - - /** Define the public API */ - punycode = { - /** - * A string representing the current Punycode.js version number. - * @memberOf punycode - * @type String - */ - 'version': '1.4.1', - /** - * An object of methods to convert from JavaScript's internal character - * representation (UCS-2) to Unicode code points, and back. - * @see - * @memberOf punycode - * @type Object - */ - 'ucs2': { - 'decode': ucs2decode, - 'encode': ucs2encode - }, - 'decode': decode, - 'encode': encode, - 'toASCII': toASCII, - 'toUnicode': toUnicode - }; - - /** Expose `punycode` */ - // Some AMD build optimizers, like r.js, check for specific condition patterns - // like the following: - if ( - typeof define == 'function' && - typeof define.amd == 'object' && - define.amd - ) { - define('punycode', function() { - return punycode; - }); - } else if (freeExports && freeModule) { - if (module.exports == freeExports) { - // in Node.js, io.js, or RingoJS v0.8.0+ - freeModule.exports = punycode; - } else { - // in Narwhal or RingoJS v0.7.0- - for (key in punycode) { - punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); - } - } - } else { - // in Rhino or a web browser - root.punycode = punycode; - } - -}(this)); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{}],26:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -// If obj.hasOwnProperty has been overridden, then calling -// obj.hasOwnProperty(prop) will break. -// See: https://github.com/joyent/node/issues/1707 -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -module.exports = function(qs, sep, eq, options) { - sep = sep || '&'; - eq = eq || '='; - var obj = {}; - - if (typeof qs !== 'string' || qs.length === 0) { - return obj; - } - - var regexp = /\+/g; - qs = qs.split(sep); - - var maxKeys = 1000; - if (options && typeof options.maxKeys === 'number') { - maxKeys = options.maxKeys; - } - - var len = qs.length; - // maxKeys <= 0 means that we should not limit keys count - if (maxKeys > 0 && len > maxKeys) { - len = maxKeys; - } - for (var i = 0; i < len; ++i) { - var x = qs[i].replace(regexp, '%20'), - idx = x.indexOf(eq), - kstr, vstr, k, v; - - if (idx >= 0) { - kstr = x.substr(0, idx); - vstr = x.substr(idx + 1); - } else { - kstr = x; - vstr = ''; + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; } - k = decodeURIComponent(kstr); - v = decodeURIComponent(vstr); - - if (!hasOwnProperty(obj, k)) { - obj[k] = v; - } else if (isArray(obj[k])) { - obj[k].push(v); - } else { - obj[k] = [obj[k], v]; + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } } - } - - return obj; -}; - -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -},{}],27:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -var stringifyPrimitive = function(v) { - switch (typeof v) { - case 'string': - return v; - - case 'boolean': - return v ? 'true' : 'false'; - - case 'number': - return isFinite(v) ? v : ''; - - default: - return ''; - } -}; - -module.exports = function(obj, sep, eq, name) { - sep = sep || '&'; - eq = eq || '='; - if (obj === null) { - obj = undefined; - } - if (typeof obj === 'object') { - return map(objectKeys(obj), function(k) { - var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; - if (isArray(obj[k])) { - return map(obj[k], function(v) { - return ks + encodeURIComponent(stringifyPrimitive(v)); - }).join(sep); - } else { - return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); } - }).join(sep); - - } - - if (!name) return ''; - return encodeURIComponent(stringifyPrimitive(name)) + eq + - encodeURIComponent(stringifyPrimitive(obj)); -}; - -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -function map (xs, f) { - if (xs.map) return xs.map(f); - var res = []; - for (var i = 0; i < xs.length; i++) { - res.push(f(xs[i], i)); - } - return res; -} - -var objectKeys = Object.keys || function (obj) { - var res = []; - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); - } - return res; -}; - -},{}],28:[function(require,module,exports){ -'use strict'; - -exports.decode = exports.parse = require('./decode'); -exports.encode = exports.stringify = require('./encode'); - -},{"./decode":26,"./encode":27}],29:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -var punycode = require('punycode'); -var util = require('./util'); - -exports.parse = urlParse; -exports.resolve = urlResolve; -exports.resolveObject = urlResolveObject; -exports.format = urlFormat; - -exports.Url = Url; - -function Url() { - this.protocol = null; - this.slashes = null; - this.auth = null; - this.host = null; - this.port = null; - this.hostname = null; - this.hash = null; - this.search = null; - this.query = null; - this.pathname = null; - this.path = null; - this.href = null; -} - -// Reference: RFC 3986, RFC 1808, RFC 2396 - -// define these here so at least they only have to be -// compiled once on the first module load. -var protocolPattern = /^([a-z0-9.+-]+:)/i, - portPattern = /:[0-9]*$/, - - // Special case for a simple path URL - simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, - - // RFC 2396: characters reserved for delimiting URLs. - // We actually just auto-escape these. - delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], - - // RFC 2396: characters not allowed for various reasons. - unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), - - // Allowed by RFCs, but cause of XSS attacks. Always escape these. - autoEscape = ['\''].concat(unwise), - // Characters that are never ever allowed in a hostname. - // Note that any invalid chars are also handled, but these - // are the ones that are *expected* to be seen, so we fast-path - // them. - nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), - hostEndingChars = ['/', '?', '#'], - hostnameMaxLen = 255, - hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, - hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, - // protocols that can allow "unsafe" and "unwise" chars. - unsafeProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that never have a hostname. - hostlessProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that always contain a // bit. - slashedProtocol = { - 'http': true, - 'https': true, - 'ftp': true, - 'gopher': true, - 'file': true, - 'http:': true, - 'https:': true, - 'ftp:': true, - 'gopher:': true, - 'file:': true - }, - querystring = require('querystring'); - -function urlParse(url, parseQueryString, slashesDenoteHost) { - if (url && util.isObject(url) && url instanceof Url) return url; - - var u = new Url; - u.parse(url, parseQueryString, slashesDenoteHost); - return u; -} + } -Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { - if (!util.isString(url)) { - throw new TypeError("Parameter 'url' must be a string, not " + typeof url); - } + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } - // Copy chrome, IE, opera backslash-handling behavior. - // Back slashes before the query string get converted to forward slashes - // See: https://code.google.com/p/chromium/issues/detail?id=25916 - var queryIndex = url.indexOf('?'), - splitter = - (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', - uSplit = url.split(splitter), - slashRegex = /\\/g; - uSplit[0] = uSplit[0].replace(slashRegex, '/'); - url = uSplit.join(splitter); - - var rest = url; - - // trim before proceeding. - // This is to support parse stuff like " http://foo.com \n" - rest = rest.trim(); - - if (!slashesDenoteHost && url.split('#').length === 1) { - // Try fast path regexp - var simplePath = simplePathPattern.exec(rest); - if (simplePath) { - this.path = rest; - this.href = rest; - this.pathname = simplePath[1]; - if (simplePath[2]) { - this.search = simplePath[2]; - if (parseQueryString) { - this.query = querystring.parse(this.search.substr(1)); - } else { - this.query = this.search.substr(1); - } - } else if (parseQueryString) { - this.search = ''; - this.query = {}; - } - return this; + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); } - } - var proto = protocolPattern.exec(rest); - if (proto) { - proto = proto[0]; - var lowerProto = proto.toLowerCase(); - this.protocol = lowerProto; - rest = rest.substr(proto.length); - } + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); - // figure out if it's got a host - // user@server is *always* interpreted as a hostname, and url - // resolution will treat //foo/bar as host=foo,path=bar because that's - // how the browser resolves relative URLs. - if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { - var slashes = rest.substr(0, 2) === '//'; - if (slashes && !(proto && hostlessProtocol[proto])) { - rest = rest.substr(2); - this.slashes = true; + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } } - } - if (!hostlessProtocol[proto] && - (slashes || (proto && !slashedProtocol[proto]))) { + mustEndAbs = mustEndAbs || (result.host && srcPath.length); - // there's a hostname. - // the first instance of /, ?, ;, or # ends the host. - // - // If there is an @ in the hostname, then non-host chars *are* allowed - // to the left of the last @ sign, unless some host-ending character - // comes *before* the @-sign. - // URLs are obnoxious. - // - // ex: - // http://a@b@c/ => user:a@b host:c - // http://a@b?@c => user:a host:c path:/?@c - - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. - - // find the first instance of any hostEndingChars - var hostEnd = -1; - for (var i = 0; i < hostEndingChars.length; i++) { - var hec = rest.indexOf(hostEndingChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); } - // at this point, either we have an explicit point where the - // auth portion cannot go past, or the last @ char is the decider. - var auth, atSign; - if (hostEnd === -1) { - // atSign can be anywhere. - atSign = rest.lastIndexOf('@'); + if (!srcPath.length) { + result.pathname = null; + result.path = null; } else { - // atSign must be in auth portion. - // http://a@b/c@d => host:b auth:a path:/c@d - atSign = rest.lastIndexOf('@', hostEnd); + result.pathname = srcPath.join('/'); } - // Now we have a portion which is definitely the auth. - // Pull that off. - if (atSign !== -1) { - auth = rest.slice(0, atSign); - rest = rest.slice(atSign + 1); - this.auth = decodeURIComponent(auth); + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + }; - // the host is the remaining to the left of the first non-host char - hostEnd = -1; - for (var i = 0; i < nonHostChars.length; i++) { - var hec = rest.indexOf(nonHostChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; - } - // if we still have not hit it, then the entire thing is a host. - if (hostEnd === -1) - hostEnd = rest.length; - - this.host = rest.slice(0, hostEnd); - rest = rest.slice(hostEnd); - - // pull out port. - this.parseHost(); - - // we've indicated that there is a hostname, - // so even if it's empty, it has to be present. - this.hostname = this.hostname || ''; - - // if hostname begins with [ and ends with ] - // assume that it's an IPv6 address. - var ipv6Hostname = this.hostname[0] === '[' && - this.hostname[this.hostname.length - 1] === ']'; - - // validate a little. - if (!ipv6Hostname) { - var hostparts = this.hostname.split(/\./); - for (var i = 0, l = hostparts.length; i < l; i++) { - var part = hostparts[i]; - if (!part) continue; - if (!part.match(hostnamePartPattern)) { - var newpart = ''; - for (var j = 0, k = part.length; j < k; j++) { - if (part.charCodeAt(j) > 127) { - // we replace non-ASCII char with a temporary placeholder - // we need this to make sure size of hostname is not - // broken by replacing non-ASCII by nothing - newpart += 'x'; - } else { - newpart += part[j]; - } - } - // we test again with ASCII char only - if (!newpart.match(hostnamePartPattern)) { - var validParts = hostparts.slice(0, i); - var notHost = hostparts.slice(i + 1); - var bit = part.match(hostnamePartStart); - if (bit) { - validParts.push(bit[1]); - notHost.unshift(bit[2]); - } - if (notHost.length) { - rest = '/' + notHost.join('.') + rest; - } - this.hostname = validParts.join('.'); - break; - } - } + Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); } + host = host.substr(0, host.length - port.length); } + if (host) { this.hostname = host; } + }; - if (this.hostname.length > hostnameMaxLen) { - this.hostname = ''; - } else { - // hostnames are always lower case. - this.hostname = this.hostname.toLowerCase(); - } + var url$1 = { + parse: parse, + resolve: resolve, + resolveObject: resolveObject, + format: format, + Url: Url_1 + }; - if (!ipv6Hostname) { - // IDNA Support: Returns a punycoded representation of "domain". - // It only converts parts of the domain name that - // have non-ASCII characters, i.e. it doesn't matter if - // you call it with a domain that already is ASCII-only. - this.hostname = punycode.toASCII(this.hostname); - } + /*! + * @pixi/utils - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/utils is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ - var p = this.port ? ':' + this.port : ''; - var h = this.hostname || ''; - this.host = h + p; - this.href += this.host; + /** + * This file contains redeclared types for Node `url` and `querystring` modules. These modules + * don't provide their own typings but instead are a part of the full Node typings. The purpose of + * this file is to redeclare the required types to avoid having the whole Node types as a + * dependency. + */ + var url = { + parse: parse, + format: format, + resolve: resolve, + }; - // strip [ and ] from the hostname - // the host field still retains them, though - if (ipv6Hostname) { - this.hostname = this.hostname.substr(1, this.hostname.length - 2); - if (rest[0] !== '/') { - rest = '/' + rest; + function assertPath(path) { + if (typeof path !== 'string') { + throw new TypeError("Path must be a string. Received " + JSON.stringify(path)); } - } } - - // now rest is set to the post-host stuff. - // chop off any delim chars. - if (!unsafeProtocol[lowerProto]) { - - // First, make 100% sure that any "autoEscape" chars get - // escaped, even if encodeURIComponent doesn't think they - // need to be. - for (var i = 0, l = autoEscape.length; i < l; i++) { - var ae = autoEscape[i]; - if (rest.indexOf(ae) === -1) - continue; - var esc = encodeURIComponent(ae); - if (esc === ae) { - esc = escape(ae); - } - rest = rest.split(ae).join(esc); - } + function removeUrlParams(url) { + var re = url.split('?')[0]; + return re.split('#')[0]; } - - - // chop off from the tail first. - var hash = rest.indexOf('#'); - if (hash !== -1) { - // got a fragment string. - this.hash = rest.substr(hash); - rest = rest.slice(0, hash); + function escapeRegExp(string) { + return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string } - var qm = rest.indexOf('?'); - if (qm !== -1) { - this.search = rest.substr(qm); - this.query = rest.substr(qm + 1); - if (parseQueryString) { - this.query = querystring.parse(this.query); - } - rest = rest.slice(0, qm); - } else if (parseQueryString) { - // no query string, but parseQueryString still requested - this.search = ''; - this.query = {}; + function replaceAll(str, find, replace) { + return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); } - if (rest) this.pathname = rest; - if (slashedProtocol[lowerProto] && - this.hostname && !this.pathname) { - this.pathname = '/'; + // Resolves . and .. elements in a path with directory names + function normalizeStringPosix(path, allowAboveRoot) { + var res = ''; + var lastSegmentLength = 0; + var lastSlash = -1; + var dots = 0; + var code; + for (var i = 0; i <= path.length; ++i) { + if (i < path.length) { + code = path.charCodeAt(i); + } + else if (code === 47) { + break; + } + else { + code = 47; + } + if (code === 47) { + if (lastSlash === i - 1 || dots === 1) { ; } + else if (lastSlash !== i - 1 && dots === 2) { + if (res.length < 2 + || lastSegmentLength !== 2 + || res.charCodeAt(res.length - 1) !== 46 + || res.charCodeAt(res.length - 2) !== 46) { + if (res.length > 2) { + var lastSlashIndex = res.lastIndexOf('/'); + if (lastSlashIndex !== res.length - 1) { + if (lastSlashIndex === -1) { + res = ''; + lastSegmentLength = 0; + } + else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf('/'); + } + lastSlash = i; + dots = 0; + continue; + } + } + else if (res.length === 2 || res.length === 1) { + res = ''; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + if (res.length > 0) { + res += '/..'; + } + else { + res = '..'; + } + lastSegmentLength = 2; + } + } + else { + if (res.length > 0) { + res += "/" + path.slice(lastSlash + 1, i); + } + else { + res = path.slice(lastSlash + 1, i); + } + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } + else if (code === 46 && dots !== -1) { + ++dots; + } + else { + dots = -1; + } + } + return res; } + var path = { + /** + * Converts a path to posix format. + * @param path - The path to convert to posix + */ + toPosix: function (path) { return replaceAll(path, '\\', '/'); }, + /** + * Checks if the path is a URL + * @param path - The path to check + */ + isUrl: function (path) { return (/^https?:/).test(this.toPosix(path)); }, + /** + * Checks if the path is a data URL + * @param path - The path to check + */ + isDataUrl: function (path) { + // eslint-disable-next-line max-len + return (/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i) + .test(path); + }, + /** + * Checks if the path has a protocol e.g. http:// + * This will return true for windows file paths + * @param path - The path to check + */ + hasProtocol: function (path) { return (/^[^/:]+:\//).test(this.toPosix(path)); }, + /** + * Returns the protocol of the path e.g. http://, C:/, file:/// + * @param path - The path to get the protocol from + */ + getProtocol: function (path) { + assertPath(path); + path = this.toPosix(path); + var protocol = ''; + var isFile = (/^file:\/\/\//).exec(path); + var isHttp = (/^[^/:]+:\/\//).exec(path); + var isWindows = (/^[^/:]+:\//).exec(path); + if (isFile || isHttp || isWindows) { + var arr = (isFile === null || isFile === void 0 ? void 0 : isFile[0]) || (isHttp === null || isHttp === void 0 ? void 0 : isHttp[0]) || (isWindows === null || isWindows === void 0 ? void 0 : isWindows[0]); + protocol = arr; + path = path.slice(arr.length); + } + return protocol; + }, + /** + * Converts URL to an absolute path. + * When loading from a Web Worker, we must use absolute paths. + * If the URL is already absolute we return it as is + * If it's not, we convert it + * @param url - The URL to test + * @param customBaseUrl - The base URL to use + * @param customRootUrl - The root URL to use + */ + toAbsolute: function (url, customBaseUrl, customRootUrl) { + if (this.isDataUrl(url)) + { return url; } + var baseUrl = removeUrlParams(this.toPosix(customBaseUrl !== null && customBaseUrl !== void 0 ? customBaseUrl : settings.ADAPTER.getBaseUrl())); + var rootUrl = removeUrlParams(this.toPosix(customRootUrl !== null && customRootUrl !== void 0 ? customRootUrl : this.rootname(baseUrl))); + assertPath(url); + url = this.toPosix(url); + // root relative url + if (url.startsWith('/')) { + return path.join(rootUrl, url.slice(1)); + } + var absolutePath = this.isAbsolute(url) ? url : this.join(baseUrl, url); + return absolutePath; + }, + /** + * Normalizes the given path, resolving '..' and '.' segments + * @param path - The path to normalize + */ + normalize: function (path) { + path = this.toPosix(path); + assertPath(path); + if (path.length === 0) + { return '.'; } + var protocol = ''; + var isAbsolute = path.startsWith('/'); + if (this.hasProtocol(path)) { + protocol = this.rootname(path); + path = path.slice(protocol.length); + } + var trailingSeparator = path.endsWith('/'); + // Normalize the path + path = normalizeStringPosix(path, false); + if (path.length > 0 && trailingSeparator) + { path += '/'; } + if (isAbsolute) + { return "/" + path; } + return protocol + path; + }, + /** + * Determines if path is an absolute path. + * Absolute paths can be urls, data urls, or paths on disk + * @param path - The path to test + */ + isAbsolute: function (path) { + assertPath(path); + path = this.toPosix(path); + if (this.hasProtocol(path)) + { return true; } + return path.startsWith('/'); + }, + /** + * Joins all given path segments together using the platform-specific separator as a delimiter, + * then normalizes the resulting path + * @param segments - The segments of the path to join + */ + join: function () { + var arguments$1 = arguments; - //to support http.request - if (this.pathname || this.search) { - var p = this.pathname || ''; - var s = this.search || ''; - this.path = p + s; - } + var _a; + var segments = []; + for (var _i = 0; _i < arguments.length; _i++) { + segments[_i] = arguments$1[_i]; + } + if (segments.length === 0) { + return '.'; + } + var joined; + for (var i = 0; i < segments.length; ++i) { + var arg = segments[i]; + assertPath(arg); + if (arg.length > 0) { + if (joined === undefined) + { joined = arg; } + else { + var prevArg = (_a = segments[i - 1]) !== null && _a !== void 0 ? _a : ''; + if (this.extname(prevArg)) { + joined += "/../" + arg; + } + else { + joined += "/" + arg; + } + } + } + } + if (joined === undefined) { + return '.'; + } + return this.normalize(joined); + }, + /** + * Returns the directory name of a path + * @param path - The path to parse + */ + dirname: function (path) { + assertPath(path); + if (path.length === 0) + { return '.'; } + path = this.toPosix(path); + var code = path.charCodeAt(0); + var hasRoot = code === 47; + var end = -1; + var matchedSlash = true; + var proto = this.getProtocol(path); + var origpath = path; + path = path.slice(proto.length); + for (var i = path.length - 1; i >= 1; --i) { + code = path.charCodeAt(i); + if (code === 47) { + if (!matchedSlash) { + end = i; + break; + } + } + else { + // We saw the first non-path separator + matchedSlash = false; + } + } + // if end is -1 and its a url then we need to add the path back + // eslint-disable-next-line no-nested-ternary + if (end === -1) + { return hasRoot ? '/' : this.isUrl(origpath) ? proto + path : proto; } + if (hasRoot && end === 1) + { return '//'; } + return proto + path.slice(0, end); + }, + /** + * Returns the root of the path e.g. /, C:/, file:///, http://domain.com/ + * @param path - The path to parse + */ + rootname: function (path) { + assertPath(path); + path = this.toPosix(path); + var root = ''; + if (path.startsWith('/')) + { root = '/'; } + else { + root = this.getProtocol(path); + } + if (this.isUrl(path)) { + // need to find the first path separator + var index = path.indexOf('/', root.length); + if (index !== -1) { + root = path.slice(0, index); + } + else + { root = path; } + if (!root.endsWith('/')) + { root += '/'; } + } + return root; + }, + /** + * Returns the last portion of a path + * @param path - The path to test + * @param ext - Optional extension to remove + */ + basename: function (path, ext) { + assertPath(path); + if (ext) + { assertPath(ext); } + path = this.toPosix(path); + var start = 0; + var end = -1; + var matchedSlash = true; + var i; + if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { + if (ext.length === path.length && ext === path) + { return ''; } + var extIdx = ext.length - 1; + var firstNonSlashEnd = -1; + for (i = path.length - 1; i >= 0; --i) { + var code = path.charCodeAt(i); + if (code === 47) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } + else { + if (firstNonSlashEnd === -1) { + // We saw the first non-path separator, remember this index in case + // we need it if the extension ends up not matching + matchedSlash = false; + firstNonSlashEnd = i + 1; + } + if (extIdx >= 0) { + // Try to match the explicit extension + if (code === ext.charCodeAt(extIdx)) { + if (--extIdx === -1) { + // We matched the extension, so mark this as the end of our path + // component + end = i; + } + } + else { + // Extension does not match, so our result is the entire path + // component + extIdx = -1; + end = firstNonSlashEnd; + } + } + } + } + if (start === end) + { end = firstNonSlashEnd; } + else if (end === -1) + { end = path.length; } + return path.slice(start, end); + } + for (i = path.length - 1; i >= 0; --i) { + if (path.charCodeAt(i) === 47) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } + else if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // path component + matchedSlash = false; + end = i + 1; + } + } + if (end === -1) + { return ''; } + return path.slice(start, end); + }, + /** + * Returns the extension of the path, from the last occurrence of the . (period) character to end of string in the last + * portion of the path. If there is no . in the last portion of the path, or if there are no . characters other than + * the first character of the basename of path, an empty string is returned. + * @param path - The path to parse + */ + extname: function (path) { + assertPath(path); + path = this.toPosix(path); + var startDot = -1; + var startPart = 0; + var end = -1; + var matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + var preDotState = 0; + for (var i = path.length - 1; i >= 0; --i) { + var code = path.charCodeAt(i); + if (code === 47) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === 46) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) + { startDot = i; } + else if (preDotState !== 1) + { preDotState = 1; } + } + else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + if (startDot === -1 || end === -1 + // We saw a non-dot character immediately before the dot + || preDotState === 0 + // The (right-most) trimmed path component is exactly '..' + // eslint-disable-next-line no-mixed-operators + || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + return ''; + } + return path.slice(startDot, end); + }, + /** + * Parses a path into an object containing the 'root', `dir`, `base`, `ext`, and `name` properties. + * @param path - The path to parse + */ + parse: function (path) { + assertPath(path); + var ret = { root: '', dir: '', base: '', ext: '', name: '' }; + if (path.length === 0) + { return ret; } + path = this.toPosix(path); + var code = path.charCodeAt(0); + var isAbsolute = this.isAbsolute(path); + var start; + ret.root = this.rootname(path); + if (isAbsolute || this.hasProtocol(path)) { + start = 1; + } + else { + start = 0; + } + var startDot = -1; + var startPart = 0; + var end = -1; + var matchedSlash = true; + var i = path.length - 1; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + var preDotState = 0; + // Get non-dir info + for (; i >= start; --i) { + code = path.charCodeAt(i); + if (code === 47) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === 46) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) + { startDot = i; } + else if (preDotState !== 1) + { preDotState = 1; } + } + else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + if (startDot === -1 || end === -1 + // We saw a non-dot character immediately before the dot + || preDotState === 0 + // The (right-most) trimmed path component is exactly '..' + // eslint-disable-next-line no-mixed-operators + || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + if (end !== -1) { + if (startPart === 0 && isAbsolute) + { ret.base = ret.name = path.slice(1, end); } + else + { ret.base = ret.name = path.slice(startPart, end); } + } + } + else { + if (startPart === 0 && isAbsolute) { + ret.name = path.slice(1, startDot); + ret.base = path.slice(1, end); + } + else { + ret.name = path.slice(startPart, startDot); + ret.base = path.slice(startPart, end); + } + ret.ext = path.slice(startDot, end); + } + ret.dir = this.dirname(path); + return ret; + }, + sep: '/', + delimiter: ':' + }; - // finally, reconstruct the href based on what has been validated. - this.href = this.format(); - return this; -}; - -// format a parsed object into a url string -function urlFormat(obj) { - // ensure it's an object, and not a string url. - // If it's an obj, this is a no-op. - // this way, you can call url_format() on strings - // to clean up potentially wonky urls. - if (util.isString(obj)) obj = urlParse(obj); - if (!(obj instanceof Url)) return Url.prototype.format.call(obj); - return obj.format(); -} - -Url.prototype.format = function() { - var auth = this.auth || ''; - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ':'); - auth += '@'; - } + /** + * The prefix that denotes a URL is for a retina asset. + * @static + * @name RETINA_PREFIX + * @memberof PIXI.settings + * @type {RegExp} + * @default /@([0-9\.]+)x/ + * @example `@2x` + */ + settings.RETINA_PREFIX = /@([0-9\.]+)x/; + /** + * Should the `failIfMajorPerformanceCaveat` flag be enabled as a context option used in the `isWebGLSupported` function. + * If set to true, a WebGL renderer can fail to be created if the browser thinks there could be performance issues when + * using WebGL. + * + * In PixiJS v6 this has changed from true to false by default, to allow WebGL to work in as many scenarios as possible. + * However, some users may have a poor experience, for example, if a user has a gpu or driver version blacklisted by the + * browser. + * + * If your application requires high performance rendering, you may wish to set this to false. + * We recommend one of two options if you decide to set this flag to false: + * + * 1: Use the `pixi.js-legacy` package, which includes a Canvas renderer as a fallback in case high performance WebGL is + * not supported. + * + * 2: Call `isWebGLSupported` (which if found in the PIXI.utils package) in your code before attempting to create a PixiJS + * renderer, and show an error message to the user if the function returns false, explaining that their device & browser + * combination does not support high performance WebGL. + * This is a much better strategy than trying to create a PixiJS renderer and finding it then fails. + * @static + * @name FAIL_IF_MAJOR_PERFORMANCE_CAVEAT + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT = false; - var protocol = this.protocol || '', - pathname = this.pathname || '', - hash = this.hash || '', - host = false, - query = ''; - - if (this.host) { - host = auth + this.host; - } else if (this.hostname) { - host = auth + (this.hostname.indexOf(':') === -1 ? - this.hostname : - '[' + this.hostname + ']'); - if (this.port) { - host += ':' + this.port; - } + var saidHello = false; + var VERSION$1 = '6.5.10'; + /** + * Skips the hello message of renderers that are created after this is run. + * @function skipHello + * @memberof PIXI.utils + */ + function skipHello() { + saidHello = true; } - - if (this.query && - util.isObject(this.query) && - Object.keys(this.query).length) { - query = querystring.stringify(this.query); + /** + * Logs out the version and renderer information for this running instance of PIXI. + * If you don't want to see this message you can run `PIXI.utils.skipHello()` before + * creating your renderer. Keep in mind that doing that will forever make you a jerk face. + * @static + * @function sayHello + * @memberof PIXI.utils + * @param {string} type - The string renderer type to log. + */ + function sayHello(type) { + var _a; + if (saidHello) { + return; + } + if (settings.ADAPTER.getNavigator().userAgent.toLowerCase().indexOf('chrome') > -1) { + var args = [ + "\n %c %c %c PixiJS " + VERSION$1 + " - \u2730 " + type + " \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n", + 'background: #ff66a5; padding:5px 0;', + 'background: #ff66a5; padding:5px 0;', + 'color: #ff66a5; background: #030307; padding:5px 0;', + 'background: #ff66a5; padding:5px 0;', + 'background: #ffc3dc; padding:5px 0;', + 'background: #ff66a5; padding:5px 0;', + 'color: #ff2424; background: #fff; padding:5px 0;', + 'color: #ff2424; background: #fff; padding:5px 0;', + 'color: #ff2424; background: #fff; padding:5px 0;' ]; + (_a = globalThis.console).log.apply(_a, args); + } + else if (globalThis.console) { + globalThis.console.log("PixiJS " + VERSION$1 + " - " + type + " - http://www.pixijs.com/"); + } + saidHello = true; } - var search = this.search || (query && ('?' + query)) || ''; - - if (protocol && protocol.substr(-1) !== ':') protocol += ':'; - - // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. - // unless they had them to begin with. - if (this.slashes || - (!protocol || slashedProtocol[protocol]) && host !== false) { - host = '//' + (host || ''); - if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; - } else if (!host) { - host = ''; + var supported; + /** + * Helper for checking for WebGL support. + * @memberof PIXI.utils + * @function isWebGLSupported + * @returns {boolean} Is WebGL supported. + */ + function isWebGLSupported() { + if (typeof supported === 'undefined') { + supported = (function supported() { + var contextOptions = { + stencil: true, + failIfMajorPerformanceCaveat: settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT, + }; + try { + if (!settings.ADAPTER.getWebGLRenderingContext()) { + return false; + } + var canvas = settings.ADAPTER.createCanvas(); + var gl = (canvas.getContext('webgl', contextOptions) + || canvas.getContext('experimental-webgl', contextOptions)); + var success = !!(gl && gl.getContextAttributes().stencil); + if (gl) { + var loseContext = gl.getExtension('WEBGL_lose_context'); + if (loseContext) { + loseContext.loseContext(); + } + } + gl = null; + return success; + } + catch (e) { + return false; + } + })(); + } + return supported; } - if (hash && hash.charAt(0) !== '#') hash = '#' + hash; - if (search && search.charAt(0) !== '?') search = '?' + search; - - pathname = pathname.replace(/[?#]/g, function(match) { - return encodeURIComponent(match); - }); - search = search.replace('#', '%23'); - - return protocol + host + pathname + search + hash; -}; - -function urlResolve(source, relative) { - return urlParse(source, false, true).resolve(relative); -} - -Url.prototype.resolve = function(relative) { - return this.resolveObject(urlParse(relative, false, true)).format(); -}; - -function urlResolveObject(source, relative) { - if (!source) return relative; - return urlParse(source, false, true).resolveObject(relative); -} + var aliceblue = "#f0f8ff"; + var antiquewhite = "#faebd7"; + var aqua = "#00ffff"; + var aquamarine = "#7fffd4"; + var azure = "#f0ffff"; + var beige = "#f5f5dc"; + var bisque = "#ffe4c4"; + var black = "#000000"; + var blanchedalmond = "#ffebcd"; + var blue = "#0000ff"; + var blueviolet = "#8a2be2"; + var brown = "#a52a2a"; + var burlywood = "#deb887"; + var cadetblue = "#5f9ea0"; + var chartreuse = "#7fff00"; + var chocolate = "#d2691e"; + var coral = "#ff7f50"; + var cornflowerblue = "#6495ed"; + var cornsilk = "#fff8dc"; + var crimson = "#dc143c"; + var cyan = "#00ffff"; + var darkblue = "#00008b"; + var darkcyan = "#008b8b"; + var darkgoldenrod = "#b8860b"; + var darkgray = "#a9a9a9"; + var darkgreen = "#006400"; + var darkgrey = "#a9a9a9"; + var darkkhaki = "#bdb76b"; + var darkmagenta = "#8b008b"; + var darkolivegreen = "#556b2f"; + var darkorange = "#ff8c00"; + var darkorchid = "#9932cc"; + var darkred = "#8b0000"; + var darksalmon = "#e9967a"; + var darkseagreen = "#8fbc8f"; + var darkslateblue = "#483d8b"; + var darkslategray = "#2f4f4f"; + var darkslategrey = "#2f4f4f"; + var darkturquoise = "#00ced1"; + var darkviolet = "#9400d3"; + var deeppink = "#ff1493"; + var deepskyblue = "#00bfff"; + var dimgray = "#696969"; + var dimgrey = "#696969"; + var dodgerblue = "#1e90ff"; + var firebrick = "#b22222"; + var floralwhite = "#fffaf0"; + var forestgreen = "#228b22"; + var fuchsia = "#ff00ff"; + var gainsboro = "#dcdcdc"; + var ghostwhite = "#f8f8ff"; + var goldenrod = "#daa520"; + var gold = "#ffd700"; + var gray = "#808080"; + var green = "#008000"; + var greenyellow = "#adff2f"; + var grey = "#808080"; + var honeydew = "#f0fff0"; + var hotpink = "#ff69b4"; + var indianred = "#cd5c5c"; + var indigo = "#4b0082"; + var ivory = "#fffff0"; + var khaki = "#f0e68c"; + var lavenderblush = "#fff0f5"; + var lavender = "#e6e6fa"; + var lawngreen = "#7cfc00"; + var lemonchiffon = "#fffacd"; + var lightblue = "#add8e6"; + var lightcoral = "#f08080"; + var lightcyan = "#e0ffff"; + var lightgoldenrodyellow = "#fafad2"; + var lightgray = "#d3d3d3"; + var lightgreen = "#90ee90"; + var lightgrey = "#d3d3d3"; + var lightpink = "#ffb6c1"; + var lightsalmon = "#ffa07a"; + var lightseagreen = "#20b2aa"; + var lightskyblue = "#87cefa"; + var lightslategray = "#778899"; + var lightslategrey = "#778899"; + var lightsteelblue = "#b0c4de"; + var lightyellow = "#ffffe0"; + var lime = "#00ff00"; + var limegreen = "#32cd32"; + var linen = "#faf0e6"; + var magenta = "#ff00ff"; + var maroon = "#800000"; + var mediumaquamarine = "#66cdaa"; + var mediumblue = "#0000cd"; + var mediumorchid = "#ba55d3"; + var mediumpurple = "#9370db"; + var mediumseagreen = "#3cb371"; + var mediumslateblue = "#7b68ee"; + var mediumspringgreen = "#00fa9a"; + var mediumturquoise = "#48d1cc"; + var mediumvioletred = "#c71585"; + var midnightblue = "#191970"; + var mintcream = "#f5fffa"; + var mistyrose = "#ffe4e1"; + var moccasin = "#ffe4b5"; + var navajowhite = "#ffdead"; + var navy = "#000080"; + var oldlace = "#fdf5e6"; + var olive = "#808000"; + var olivedrab = "#6b8e23"; + var orange = "#ffa500"; + var orangered = "#ff4500"; + var orchid = "#da70d6"; + var palegoldenrod = "#eee8aa"; + var palegreen = "#98fb98"; + var paleturquoise = "#afeeee"; + var palevioletred = "#db7093"; + var papayawhip = "#ffefd5"; + var peachpuff = "#ffdab9"; + var peru = "#cd853f"; + var pink = "#ffc0cb"; + var plum = "#dda0dd"; + var powderblue = "#b0e0e6"; + var purple = "#800080"; + var rebeccapurple = "#663399"; + var red = "#ff0000"; + var rosybrown = "#bc8f8f"; + var royalblue = "#4169e1"; + var saddlebrown = "#8b4513"; + var salmon = "#fa8072"; + var sandybrown = "#f4a460"; + var seagreen = "#2e8b57"; + var seashell = "#fff5ee"; + var sienna = "#a0522d"; + var silver = "#c0c0c0"; + var skyblue = "#87ceeb"; + var slateblue = "#6a5acd"; + var slategray = "#708090"; + var slategrey = "#708090"; + var snow = "#fffafa"; + var springgreen = "#00ff7f"; + var steelblue = "#4682b4"; + var tan = "#d2b48c"; + var teal = "#008080"; + var thistle = "#d8bfd8"; + var tomato = "#ff6347"; + var turquoise = "#40e0d0"; + var violet = "#ee82ee"; + var wheat = "#f5deb3"; + var white = "#ffffff"; + var whitesmoke = "#f5f5f5"; + var yellow = "#ffff00"; + var yellowgreen = "#9acd32"; + var cssColorNames = { + aliceblue: aliceblue, + antiquewhite: antiquewhite, + aqua: aqua, + aquamarine: aquamarine, + azure: azure, + beige: beige, + bisque: bisque, + black: black, + blanchedalmond: blanchedalmond, + blue: blue, + blueviolet: blueviolet, + brown: brown, + burlywood: burlywood, + cadetblue: cadetblue, + chartreuse: chartreuse, + chocolate: chocolate, + coral: coral, + cornflowerblue: cornflowerblue, + cornsilk: cornsilk, + crimson: crimson, + cyan: cyan, + darkblue: darkblue, + darkcyan: darkcyan, + darkgoldenrod: darkgoldenrod, + darkgray: darkgray, + darkgreen: darkgreen, + darkgrey: darkgrey, + darkkhaki: darkkhaki, + darkmagenta: darkmagenta, + darkolivegreen: darkolivegreen, + darkorange: darkorange, + darkorchid: darkorchid, + darkred: darkred, + darksalmon: darksalmon, + darkseagreen: darkseagreen, + darkslateblue: darkslateblue, + darkslategray: darkslategray, + darkslategrey: darkslategrey, + darkturquoise: darkturquoise, + darkviolet: darkviolet, + deeppink: deeppink, + deepskyblue: deepskyblue, + dimgray: dimgray, + dimgrey: dimgrey, + dodgerblue: dodgerblue, + firebrick: firebrick, + floralwhite: floralwhite, + forestgreen: forestgreen, + fuchsia: fuchsia, + gainsboro: gainsboro, + ghostwhite: ghostwhite, + goldenrod: goldenrod, + gold: gold, + gray: gray, + green: green, + greenyellow: greenyellow, + grey: grey, + honeydew: honeydew, + hotpink: hotpink, + indianred: indianred, + indigo: indigo, + ivory: ivory, + khaki: khaki, + lavenderblush: lavenderblush, + lavender: lavender, + lawngreen: lawngreen, + lemonchiffon: lemonchiffon, + lightblue: lightblue, + lightcoral: lightcoral, + lightcyan: lightcyan, + lightgoldenrodyellow: lightgoldenrodyellow, + lightgray: lightgray, + lightgreen: lightgreen, + lightgrey: lightgrey, + lightpink: lightpink, + lightsalmon: lightsalmon, + lightseagreen: lightseagreen, + lightskyblue: lightskyblue, + lightslategray: lightslategray, + lightslategrey: lightslategrey, + lightsteelblue: lightsteelblue, + lightyellow: lightyellow, + lime: lime, + limegreen: limegreen, + linen: linen, + magenta: magenta, + maroon: maroon, + mediumaquamarine: mediumaquamarine, + mediumblue: mediumblue, + mediumorchid: mediumorchid, + mediumpurple: mediumpurple, + mediumseagreen: mediumseagreen, + mediumslateblue: mediumslateblue, + mediumspringgreen: mediumspringgreen, + mediumturquoise: mediumturquoise, + mediumvioletred: mediumvioletred, + midnightblue: midnightblue, + mintcream: mintcream, + mistyrose: mistyrose, + moccasin: moccasin, + navajowhite: navajowhite, + navy: navy, + oldlace: oldlace, + olive: olive, + olivedrab: olivedrab, + orange: orange, + orangered: orangered, + orchid: orchid, + palegoldenrod: palegoldenrod, + palegreen: palegreen, + paleturquoise: paleturquoise, + palevioletred: palevioletred, + papayawhip: papayawhip, + peachpuff: peachpuff, + peru: peru, + pink: pink, + plum: plum, + powderblue: powderblue, + purple: purple, + rebeccapurple: rebeccapurple, + red: red, + rosybrown: rosybrown, + royalblue: royalblue, + saddlebrown: saddlebrown, + salmon: salmon, + sandybrown: sandybrown, + seagreen: seagreen, + seashell: seashell, + sienna: sienna, + silver: silver, + skyblue: skyblue, + slateblue: slateblue, + slategray: slategray, + slategrey: slategrey, + snow: snow, + springgreen: springgreen, + steelblue: steelblue, + tan: tan, + teal: teal, + thistle: thistle, + tomato: tomato, + turquoise: turquoise, + violet: violet, + wheat: wheat, + white: white, + whitesmoke: whitesmoke, + yellow: yellow, + yellowgreen: yellowgreen + }; -Url.prototype.resolveObject = function(relative) { - if (util.isString(relative)) { - var rel = new Url(); - rel.parse(relative, false, true); - relative = rel; + /** + * Converts a hexadecimal color number to an [R, G, B] array of normalized floats (numbers from 0.0 to 1.0). + * @example + * PIXI.utils.hex2rgb(0xffffff); // returns [1, 1, 1] + * @memberof PIXI.utils + * @function hex2rgb + * @param {number} hex - The hexadecimal number to convert + * @param {number[]} [out=[]] - If supplied, this array will be used rather than returning a new one + * @returns {number[]} An array representing the [R, G, B] of the color where all values are floats. + */ + function hex2rgb(hex, out) { + if (out === void 0) { out = []; } + out[0] = ((hex >> 16) & 0xFF) / 255; + out[1] = ((hex >> 8) & 0xFF) / 255; + out[2] = (hex & 0xFF) / 255; + return out; } - - var result = new Url(); - var tkeys = Object.keys(this); - for (var tk = 0; tk < tkeys.length; tk++) { - var tkey = tkeys[tk]; - result[tkey] = this[tkey]; + /** + * Converts a hexadecimal color number to a string. + * @example + * PIXI.utils.hex2string(0xffffff); // returns "#ffffff" + * @memberof PIXI.utils + * @function hex2string + * @param {number} hex - Number in hex (e.g., `0xffffff`) + * @returns {string} The string color (e.g., `"#ffffff"`). + */ + function hex2string(hex) { + var hexString = hex.toString(16); + hexString = '000000'.substring(0, 6 - hexString.length) + hexString; + return "#" + hexString; } - - // hash is always overridden, no matter what. - // even href="" will remove it. - result.hash = relative.hash; - - // if the relative url is empty, then there's nothing left to do here. - if (relative.href === '') { - result.href = result.format(); - return result; + /** + * Converts a string to a hexadecimal color number. + * It can handle: + * hex strings starting with #: "#ffffff" + * hex strings starting with 0x: "0xffffff" + * hex strings without prefix: "ffffff" + * css colors: "black" + * @example + * PIXI.utils.string2hex("#ffffff"); // returns 0xffffff, which is 16777215 as an integer + * @memberof PIXI.utils + * @function string2hex + * @param {string} string - The string color (e.g., `"#ffffff"`) + * @returns {number} Number in hexadecimal. + */ + function string2hex(string) { + if (typeof string === 'string') { + string = cssColorNames[string.toLowerCase()] || string; + if (string[0] === '#') { + string = string.slice(1); + } + } + return parseInt(string, 16); } - - // hrefs like //foo/bar always cut to the protocol. - if (relative.slashes && !relative.protocol) { - // take everything except the protocol from relative - var rkeys = Object.keys(relative); - for (var rk = 0; rk < rkeys.length; rk++) { - var rkey = rkeys[rk]; - if (rkey !== 'protocol') - result[rkey] = relative[rkey]; - } - - //urlParse appends trailing / to urls like http://www.example.com - if (slashedProtocol[result.protocol] && - result.hostname && !result.pathname) { - result.path = result.pathname = '/'; - } - - result.href = result.format(); - return result; + /** + * Converts a color as an [R, G, B] array of normalized floats to a hexadecimal number. + * @example + * PIXI.utils.rgb2hex([1, 1, 1]); // returns 0xffffff, which is 16777215 as an integer + * @memberof PIXI.utils + * @function rgb2hex + * @param {number[]} rgb - Array of numbers where all values are normalized floats from 0.0 to 1.0. + * @returns {number} Number in hexadecimal. + */ + function rgb2hex(rgb) { + return (((rgb[0] * 255) << 16) + ((rgb[1] * 255) << 8) + (rgb[2] * 255 | 0)); } - if (relative.protocol && relative.protocol !== result.protocol) { - // if it's a known url protocol, then changing - // the protocol does weird things - // first, if it's not file:, then we MUST have a host, - // and if there was a path - // to begin with, then we MUST have a path. - // if it is file:, then the host is dropped, - // because that's known to be hostless. - // anything else is assumed to be absolute. - if (!slashedProtocol[relative.protocol]) { - var keys = Object.keys(relative); - for (var v = 0; v < keys.length; v++) { - var k = keys[v]; - result[k] = relative[k]; + /** + * Corrects PixiJS blend, takes premultiplied alpha into account + * @memberof PIXI.utils + * @function mapPremultipliedBlendModes + * @private + * @returns {Array} Mapped modes. + */ + function mapPremultipliedBlendModes() { + var pm = []; + var npm = []; + for (var i = 0; i < 32; i++) { + pm[i] = i; + npm[i] = i; } - result.href = result.format(); - return result; - } - - result.protocol = relative.protocol; - if (!relative.host && !hostlessProtocol[relative.protocol]) { - var relPath = (relative.pathname || '').split('/'); - while (relPath.length && !(relative.host = relPath.shift())); - if (!relative.host) relative.host = ''; - if (!relative.hostname) relative.hostname = ''; - if (relPath[0] !== '') relPath.unshift(''); - if (relPath.length < 2) relPath.unshift(''); - result.pathname = relPath.join('/'); - } else { - result.pathname = relative.pathname; - } - result.search = relative.search; - result.query = relative.query; - result.host = relative.host || ''; - result.auth = relative.auth; - result.hostname = relative.hostname || relative.host; - result.port = relative.port; - // to support http.request - if (result.pathname || result.search) { - var p = result.pathname || ''; - var s = result.search || ''; - result.path = p + s; - } - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; + pm[exports.BLEND_MODES.NORMAL_NPM] = exports.BLEND_MODES.NORMAL; + pm[exports.BLEND_MODES.ADD_NPM] = exports.BLEND_MODES.ADD; + pm[exports.BLEND_MODES.SCREEN_NPM] = exports.BLEND_MODES.SCREEN; + npm[exports.BLEND_MODES.NORMAL] = exports.BLEND_MODES.NORMAL_NPM; + npm[exports.BLEND_MODES.ADD] = exports.BLEND_MODES.ADD_NPM; + npm[exports.BLEND_MODES.SCREEN] = exports.BLEND_MODES.SCREEN_NPM; + var array = []; + array.push(npm); + array.push(pm); + return array; } - - var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), - isRelAbs = ( - relative.host || - relative.pathname && relative.pathname.charAt(0) === '/' - ), - mustEndAbs = (isRelAbs || isSourceAbs || - (result.host && relative.pathname)), - removeAllDots = mustEndAbs, - srcPath = result.pathname && result.pathname.split('/') || [], - relPath = relative.pathname && relative.pathname.split('/') || [], - psychotic = result.protocol && !slashedProtocol[result.protocol]; - - // if the url is a non-slashed url, then relative - // links like ../.. should be able - // to crawl up to the hostname, as well. This is strange. - // result.protocol has already been set by now. - // Later on, put the first path part into the host field. - if (psychotic) { - result.hostname = ''; - result.port = null; - if (result.host) { - if (srcPath[0] === '') srcPath[0] = result.host; - else srcPath.unshift(result.host); - } - result.host = ''; - if (relative.protocol) { - relative.hostname = null; - relative.port = null; - if (relative.host) { - if (relPath[0] === '') relPath[0] = relative.host; - else relPath.unshift(relative.host); - } - relative.host = null; - } - mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + /** + * maps premultiply flag and blendMode to adjusted blendMode + * @memberof PIXI.utils + * @constant premultiplyBlendMode + * @type {Array} + */ + var premultiplyBlendMode = mapPremultipliedBlendModes(); + /** + * changes blendMode according to texture format + * @memberof PIXI.utils + * @function correctBlendMode + * @param {number} blendMode - supposed blend mode + * @param {boolean} premultiplied - whether source is premultiplied + * @returns {number} true blend mode for this texture + */ + function correctBlendMode(blendMode, premultiplied) { + return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode]; } - - if (isRelAbs) { - // it's absolute. - result.host = (relative.host || relative.host === '') ? - relative.host : result.host; - result.hostname = (relative.hostname || relative.hostname === '') ? - relative.hostname : result.hostname; - result.search = relative.search; - result.query = relative.query; - srcPath = relPath; - // fall through to the dot-handling below. - } else if (relPath.length) { - // it's relative - // throw away the existing file, and take the new path instead. - if (!srcPath) srcPath = []; - srcPath.pop(); - srcPath = srcPath.concat(relPath); - result.search = relative.search; - result.query = relative.query; - } else if (!util.isNullOrUndefined(relative.search)) { - // just pull out the search. - // like href='?foo'. - // Put this after the other two cases because it simplifies the booleans - if (psychotic) { - result.hostname = result.host = srcPath.shift(); - //occationaly the auth can get stuck only in host - //this especially happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); + /** + * combines rgb and alpha to out array + * @memberof PIXI.utils + * @function premultiplyRgba + * @param {Float32Array|number[]} rgb - input rgb + * @param {number} alpha - alpha param + * @param {Float32Array} [out] - output + * @param {boolean} [premultiply=true] - do premultiply it + * @returns {Float32Array} vec4 rgba + */ + function premultiplyRgba(rgb, alpha, out, premultiply) { + out = out || new Float32Array(4); + if (premultiply || premultiply === undefined) { + out[0] = rgb[0] * alpha; + out[1] = rgb[1] * alpha; + out[2] = rgb[2] * alpha; } - } - result.search = relative.search; - result.query = relative.query; - //to support http.request - if (!util.isNull(result.pathname) || !util.isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.href = result.format(); - return result; + else { + out[0] = rgb[0]; + out[1] = rgb[1]; + out[2] = rgb[2]; + } + out[3] = alpha; + return out; } - - if (!srcPath.length) { - // no path at all. easy. - // we've already handled the other stuff above. - result.pathname = null; - //to support http.request - if (result.search) { - result.path = '/' + result.search; - } else { - result.path = null; - } - result.href = result.format(); - return result; + /** + * premultiplies tint + * @memberof PIXI.utils + * @function premultiplyTint + * @param {number} tint - integer RGB + * @param {number} alpha - floating point alpha (0.0-1.0) + * @returns {number} tint multiplied by alpha + */ + function premultiplyTint(tint, alpha) { + if (alpha === 1.0) { + return (alpha * 255 << 24) + tint; + } + if (alpha === 0.0) { + return 0; + } + var R = ((tint >> 16) & 0xFF); + var G = ((tint >> 8) & 0xFF); + var B = (tint & 0xFF); + R = ((R * alpha) + 0.5) | 0; + G = ((G * alpha) + 0.5) | 0; + B = ((B * alpha) + 0.5) | 0; + return (alpha * 255 << 24) + (R << 16) + (G << 8) + B; } - - // if a url ENDs in . or .., then it must get a trailing slash. - // however, if it ends in anything else non-slashy, - // then it must NOT get a trailing slash. - var last = srcPath.slice(-1)[0]; - var hasTrailingSlash = ( - (result.host || relative.host || srcPath.length > 1) && - (last === '.' || last === '..') || last === ''); - - // strip single dots, resolve double dots to parent dir - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = srcPath.length; i >= 0; i--) { - last = srcPath[i]; - if (last === '.') { - srcPath.splice(i, 1); - } else if (last === '..') { - srcPath.splice(i, 1); - up++; - } else if (up) { - srcPath.splice(i, 1); - up--; - } + /** + * converts integer tint and float alpha to vec4 form, premultiplies by default + * @memberof PIXI.utils + * @function premultiplyTintToRgba + * @param {number} tint - input tint + * @param {number} alpha - alpha param + * @param {Float32Array} [out] - output + * @param {boolean} [premultiply=true] - do premultiply it + * @returns {Float32Array} vec4 rgba + */ + function premultiplyTintToRgba(tint, alpha, out, premultiply) { + out = out || new Float32Array(4); + out[0] = ((tint >> 16) & 0xFF) / 255.0; + out[1] = ((tint >> 8) & 0xFF) / 255.0; + out[2] = (tint & 0xFF) / 255.0; + if (premultiply || premultiply === undefined) { + out[0] *= alpha; + out[1] *= alpha; + out[2] *= alpha; + } + out[3] = alpha; + return out; } - // if the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift('..'); - } + /** + * Generic Mask Stack data structure + * @memberof PIXI.utils + * @function createIndicesForQuads + * @param {number} size - Number of quads + * @param {Uint16Array|Uint32Array} [outBuffer] - Buffer for output, length has to be `6 * size` + * @returns {Uint16Array|Uint32Array} - Resulting index buffer + */ + function createIndicesForQuads(size, outBuffer) { + if (outBuffer === void 0) { outBuffer = null; } + // the total number of indices in our array, there are 6 points per quad. + var totalIndices = size * 6; + outBuffer = outBuffer || new Uint16Array(totalIndices); + if (outBuffer.length !== totalIndices) { + throw new Error("Out buffer length is incorrect, got " + outBuffer.length + " and expected " + totalIndices); + } + // fill the indices with the quads to draw + for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { + outBuffer[i + 0] = j + 0; + outBuffer[i + 1] = j + 1; + outBuffer[i + 2] = j + 2; + outBuffer[i + 3] = j + 0; + outBuffer[i + 4] = j + 2; + outBuffer[i + 5] = j + 3; + } + return outBuffer; } - if (mustEndAbs && srcPath[0] !== '' && - (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { - srcPath.unshift(''); + function getBufferType(array) { + if (array.BYTES_PER_ELEMENT === 4) { + if (array instanceof Float32Array) { + return 'Float32Array'; + } + else if (array instanceof Uint32Array) { + return 'Uint32Array'; + } + return 'Int32Array'; + } + else if (array.BYTES_PER_ELEMENT === 2) { + if (array instanceof Uint16Array) { + return 'Uint16Array'; + } + } + else if (array.BYTES_PER_ELEMENT === 1) { + if (array instanceof Uint8Array) { + return 'Uint8Array'; + } + } + // TODO map out the rest of the array elements! + return null; } - if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { - srcPath.push(''); + /* eslint-disable object-shorthand */ + var map$2 = { Float32Array: Float32Array, Uint32Array: Uint32Array, Int32Array: Int32Array, Uint8Array: Uint8Array }; + function interleaveTypedArrays$1(arrays, sizes) { + var outSize = 0; + var stride = 0; + var views = {}; + for (var i = 0; i < arrays.length; i++) { + stride += sizes[i]; + outSize += arrays[i].length; + } + var buffer = new ArrayBuffer(outSize * 4); + var out = null; + var littleOffset = 0; + for (var i = 0; i < arrays.length; i++) { + var size = sizes[i]; + var array = arrays[i]; + /* + @todo This is unsafe casting but consistent with how the code worked previously. Should it stay this way + or should and `getBufferTypeUnsafe` function be exposed that throws an Error if unsupported type is passed? + */ + var type = getBufferType(array); + if (!views[type]) { + views[type] = new map$2[type](buffer); + } + out = views[type]; + for (var j = 0; j < array.length; j++) { + var indexStart = ((j / size | 0) * stride) + littleOffset; + var index = j % size; + out[indexStart + index] = array[j]; + } + littleOffset += size; + } + return new Float32Array(buffer); } - var isAbsolute = srcPath[0] === '' || - (srcPath[0] && srcPath[0].charAt(0) === '/'); - - // put the host back - if (psychotic) { - result.hostname = result.host = isAbsolute ? '' : - srcPath.length ? srcPath.shift() : ''; - //occationaly the auth can get stuck only in host - //this especially happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } + // Taken from the bit-twiddle package + /** + * Rounds to next power of two. + * @function nextPow2 + * @memberof PIXI.utils + * @param {number} v - input value + * @returns {number} - next rounded power of two + */ + function nextPow2(v) { + v += v === 0 ? 1 : 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; + } + /** + * Checks if a number is a power of two. + * @function isPow2 + * @memberof PIXI.utils + * @param {number} v - input value + * @returns {boolean} `true` if value is power of two + */ + function isPow2(v) { + return !(v & (v - 1)) && (!!v); + } + /** + * Computes ceil of log base 2 + * @function log2 + * @memberof PIXI.utils + * @param {number} v - input value + * @returns {number} logarithm base 2 + */ + function log2(v) { + var r = (v > 0xFFFF ? 1 : 0) << 4; + v >>>= r; + var shift = (v > 0xFF ? 1 : 0) << 3; + v >>>= shift; + r |= shift; + shift = (v > 0xF ? 1 : 0) << 2; + v >>>= shift; + r |= shift; + shift = (v > 0x3 ? 1 : 0) << 1; + v >>>= shift; + r |= shift; + return r | (v >> 1); } - mustEndAbs = mustEndAbs || (result.host && srcPath.length); + /** + * Remove items from a javascript array without generating garbage + * @function removeItems + * @memberof PIXI.utils + * @param {Array} arr - Array to remove elements from + * @param {number} startIdx - starting index + * @param {number} removeCount - how many to remove + */ + function removeItems(arr, startIdx, removeCount) { + var length = arr.length; + var i; + if (startIdx >= length || removeCount === 0) { + return; + } + removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount); + var len = length - removeCount; + for (i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount]; + } + arr.length = len; + } - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(''); + /** + * Returns sign of number + * @memberof PIXI.utils + * @function sign + * @param {number} n - the number to check the sign of + * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive + */ + function sign(n) { + if (n === 0) + { return 0; } + return n < 0 ? -1 : 1; } - if (!srcPath.length) { - result.pathname = null; - result.path = null; - } else { - result.pathname = srcPath.join('/'); + var nextUid = 0; + /** + * Gets the next unique identifier + * @memberof PIXI.utils + * @function uid + * @returns {number} The next unique identifier to use. + */ + function uid() { + return ++nextUid; } - //to support request.http - if (!util.isNull(result.pathname) || !util.isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); + // A map of warning messages already fired + var warnings = {}; + /** + * Helper for warning developers about deprecated features & settings. + * A stack track for warnings is given; useful for tracking-down where + * deprecated methods/properties/classes are being used within the code. + * @memberof PIXI.utils + * @function deprecation + * @param {string} version - The version where the feature became deprecated + * @param {string} message - Message should include what is deprecated, where, and the new solution + * @param {number} [ignoreDepth=3] - The number of steps to ignore at the top of the error stack + * this is mostly to ignore internal deprecation calls. + */ + function deprecation(version, message, ignoreDepth) { + if (ignoreDepth === void 0) { ignoreDepth = 3; } + // Ignore duplicat + if (warnings[message]) { + return; + } + /* eslint-disable no-console */ + var stack = new Error().stack; + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version); + } + else { + // chop off the stack trace which includes PixiJS internal calls + stack = stack.split('\n').splice(ignoreDepth).join('\n'); + if (console.groupCollapsed) { + console.groupCollapsed('%cPixiJS Deprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', message + "\nDeprecated since v" + version); + console.warn(stack); + console.groupEnd(); + } + else { + console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version); + console.warn(stack); + } + } + /* eslint-enable no-console */ + warnings[message] = true; } - result.auth = relative.auth || result.auth; - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; -}; - -Url.prototype.parseHost = function() { - var host = this.host; - var port = portPattern.exec(host); - if (port) { - port = port[0]; - if (port !== ':') { - this.port = port.substr(1); - } - host = host.substr(0, host.length - port.length); + + /** + * @todo Describe property usage + * @static + * @name ProgramCache + * @memberof PIXI.utils + * @type {object} + */ + var ProgramCache = {}; + /** + * @todo Describe property usage + * @static + * @name TextureCache + * @memberof PIXI.utils + * @type {object} + */ + var TextureCache = Object.create(null); + /** + * @todo Describe property usage + * @static + * @name BaseTextureCache + * @memberof PIXI.utils + * @type {object} + */ + var BaseTextureCache = Object.create(null); + /** + * Destroys all texture in the cache + * @memberof PIXI.utils + * @function destroyTextureCache + */ + function destroyTextureCache() { + var key; + for (key in TextureCache) { + TextureCache[key].destroy(); + } + for (key in BaseTextureCache) { + BaseTextureCache[key].destroy(); + } } - if (host) this.hostname = host; -}; - -},{"./util":30,"punycode":25,"querystring":28}],30:[function(require,module,exports){ -'use strict'; - -module.exports = { - isString: function(arg) { - return typeof(arg) === 'string'; - }, - isObject: function(arg) { - return typeof(arg) === 'object' && arg !== null; - }, - isNull: function(arg) { - return arg === null; - }, - isNullOrUndefined: function(arg) { - return arg == null; + /** + * Removes all textures from cache, but does not destroy them + * @memberof PIXI.utils + * @function clearTextureCache + */ + function clearTextureCache() { + var key; + for (key in TextureCache) { + delete TextureCache[key]; + } + for (key in BaseTextureCache) { + delete BaseTextureCache[key]; + } } -}; -},{}],31:[function(require,module,exports){ -'use strict' - -/** - * Remove a range of items from an array - * - * @function removeItems - * @param {Array<*>} arr The target array - * @param {number} startIdx The index to begin removing from (inclusive) - * @param {number} removeCount How many items to remove - */ -module.exports = function removeItems(arr, startIdx, removeCount) -{ - var i, length = arr.length + /** + * Creates a Canvas element of the given size to be used as a target for rendering to. + * @class + * @memberof PIXI.utils + */ + var CanvasRenderTarget = /** @class */ (function () { + /** + * @param width - the width for the newly created canvas + * @param height - the height for the newly created canvas + * @param {number} [resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the canvas + */ + function CanvasRenderTarget(width, height, resolution) { + this.canvas = settings.ADAPTER.createCanvas(); + this.context = this.canvas.getContext('2d'); + this.resolution = resolution || settings.RESOLUTION; + this.resize(width, height); + } + /** + * Clears the canvas that was created by the CanvasRenderTarget class. + * @private + */ + CanvasRenderTarget.prototype.clear = function () { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + }; + /** + * Resizes the canvas to the specified width and height. + * @param desiredWidth - the desired width of the canvas + * @param desiredHeight - the desired height of the canvas + */ + CanvasRenderTarget.prototype.resize = function (desiredWidth, desiredHeight) { + this.canvas.width = Math.round(desiredWidth * this.resolution); + this.canvas.height = Math.round(desiredHeight * this.resolution); + }; + /** Destroys this canvas. */ + CanvasRenderTarget.prototype.destroy = function () { + this.context = null; + this.canvas = null; + }; + Object.defineProperty(CanvasRenderTarget.prototype, "width", { + /** + * The width of the canvas buffer in pixels. + * @member {number} + */ + get: function () { + return this.canvas.width; + }, + set: function (val) { + this.canvas.width = Math.round(val); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CanvasRenderTarget.prototype, "height", { + /** + * The height of the canvas buffer in pixels. + * @member {number} + */ + get: function () { + return this.canvas.height; + }, + set: function (val) { + this.canvas.height = Math.round(val); + }, + enumerable: false, + configurable: true + }); + return CanvasRenderTarget; + }()); - if (startIdx >= length || removeCount === 0) { - return + /** + * Trim transparent borders from a canvas + * @memberof PIXI.utils + * @function trimCanvas + * @param {HTMLCanvasElement} canvas - the canvas to trim + * @returns {object} Trim data + */ + function trimCanvas(canvas) { + // https://gist.github.com/remy/784508 + var width = canvas.width; + var height = canvas.height; + var context = canvas.getContext('2d', { + willReadFrequently: true, + }); + var imageData = context.getImageData(0, 0, width, height); + var pixels = imageData.data; + var len = pixels.length; + var bound = { + top: null, + left: null, + right: null, + bottom: null, + }; + var data = null; + var i; + var x; + var y; + for (i = 0; i < len; i += 4) { + if (pixels[i + 3] !== 0) { + x = (i / 4) % width; + y = ~~((i / 4) / width); + if (bound.top === null) { + bound.top = y; + } + if (bound.left === null) { + bound.left = x; + } + else if (x < bound.left) { + bound.left = x; + } + if (bound.right === null) { + bound.right = x + 1; + } + else if (bound.right < x) { + bound.right = x + 1; + } + if (bound.bottom === null) { + bound.bottom = y; + } + else if (bound.bottom < y) { + bound.bottom = y; + } + } + } + if (bound.top !== null) { + width = bound.right - bound.left; + height = bound.bottom - bound.top + 1; + data = context.getImageData(bound.left, bound.top, width, height); + } + return { + height: height, + width: width, + data: data, + }; } - removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount) - - var len = length - removeCount + /** + * Regexp for data URI. + * Based on: {@link https://github.com/ragingwind/data-uri-regex} + * @static + * @constant {RegExp|string} DATA_URI + * @memberof PIXI + * @example data:image/png;base64 + */ + var DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i; - for (i = startIdx; i < len; ++i) { - arr[i] = arr[i + removeCount] + /** + * @memberof PIXI.utils + * @interface DecomposedDataUri + */ + /** + * type, eg. `image` + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} mediaType + */ + /** + * Sub type, eg. `png` + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} subType + */ + /** + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} charset + */ + /** + * Data encoding, eg. `base64` + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} encoding + */ + /** + * The actual data + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} data + */ + /** + * Split a data URI into components. Returns undefined if + * parameter `dataUri` is not a valid data URI. + * @memberof PIXI.utils + * @function decomposeDataUri + * @param {string} dataUri - the data URI to check + * @returns {PIXI.utils.DecomposedDataUri|undefined} The decomposed data uri or undefined + */ + function decomposeDataUri(dataUri) { + var dataUriMatch = DATA_URI.exec(dataUri); + if (dataUriMatch) { + return { + mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, + subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, + charset: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, + encoding: dataUriMatch[4] ? dataUriMatch[4].toLowerCase() : undefined, + data: dataUriMatch[5], + }; + } + return undefined; } - arr.length = len -} - -},{}],32:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -var _miniSignals = require('mini-signals'); - -var _miniSignals2 = _interopRequireDefault(_miniSignals); - -var _parseUri = require('parse-uri'); + var tempAnchor$1; + /** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * Nipped from the resource loader! + * @ignore + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @returns {string} The crossOrigin value to use (or empty string for none). + */ + function determineCrossOrigin(url$1, loc) { + if (loc === void 0) { loc = globalThis.location; } + // data: and javascript: urls are considered same-origin + if (url$1.indexOf('data:') === 0) { + return ''; + } + // default is window.location + loc = loc || globalThis.location; + if (!tempAnchor$1) { + tempAnchor$1 = document.createElement('a'); + } + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor$1.href = url$1; + var parsedUrl = url.parse(tempAnchor$1.href); + var samePort = (!parsedUrl.port && loc.port === '') || (parsedUrl.port === loc.port); + // if cross origin + if (parsedUrl.hostname !== loc.hostname || !samePort || parsedUrl.protocol !== loc.protocol) { + return 'anonymous'; + } + return ''; + } -var _parseUri2 = _interopRequireDefault(_parseUri); + /** + * get the resolution / device pixel ratio of an asset by looking for the prefix + * used by spritesheets and image urls + * @memberof PIXI.utils + * @function getResolutionOfUrl + * @param {string} url - the image path + * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. + * @returns {number} resolution / device pixel ratio of an asset + */ + function getResolutionOfUrl(url, defaultValue) { + var resolution = settings.RETINA_PREFIX.exec(url); + if (resolution) { + return parseFloat(resolution[1]); + } + return defaultValue !== undefined ? defaultValue : 1; + } -var _async = require('./async'); + var utils = { + __proto__: null, + BaseTextureCache: BaseTextureCache, + CanvasRenderTarget: CanvasRenderTarget, + DATA_URI: DATA_URI, + ProgramCache: ProgramCache, + TextureCache: TextureCache, + clearTextureCache: clearTextureCache, + correctBlendMode: correctBlendMode, + createIndicesForQuads: createIndicesForQuads, + decomposeDataUri: decomposeDataUri, + deprecation: deprecation, + destroyTextureCache: destroyTextureCache, + determineCrossOrigin: determineCrossOrigin, + getBufferType: getBufferType, + getResolutionOfUrl: getResolutionOfUrl, + hex2rgb: hex2rgb, + hex2string: hex2string, + interleaveTypedArrays: interleaveTypedArrays$1, + isPow2: isPow2, + isWebGLSupported: isWebGLSupported, + log2: log2, + nextPow2: nextPow2, + path: path, + premultiplyBlendMode: premultiplyBlendMode, + premultiplyRgba: premultiplyRgba, + premultiplyTint: premultiplyTint, + premultiplyTintToRgba: premultiplyTintToRgba, + removeItems: removeItems, + rgb2hex: rgb2hex, + sayHello: sayHello, + sign: sign, + skipHello: skipHello, + string2hex: string2hex, + trimCanvas: trimCanvas, + uid: uid, + url: url, + isMobile: isMobile, + EventEmitter: eventemitter3, + earcut: earcut_1 + }; -var async = _interopRequireWildcard(_async); + /*! + * @pixi/math - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/math is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * Two Pi. + * @static + * @member {number} + * @memberof PIXI + */ + var PI_2 = Math.PI * 2; + /** + * Conversion factor for converting radians to degrees. + * @static + * @member {number} RAD_TO_DEG + * @memberof PIXI + */ + var RAD_TO_DEG = 180 / Math.PI; + /** + * Conversion factor for converting degrees to radians. + * @static + * @member {number} + * @memberof PIXI + */ + var DEG_TO_RAD = Math.PI / 180; + /** + * Constants that identify shapes, mainly to prevent `instanceof` calls. + * @static + * @memberof PIXI + * @enum {number} + * @property {number} POLY Polygon + * @property {number} RECT Rectangle + * @property {number} CIRC Circle + * @property {number} ELIP Ellipse + * @property {number} RREC Rounded Rectangle + */ + exports.SHAPES = void 0; + (function (SHAPES) { + SHAPES[SHAPES["POLY"] = 0] = "POLY"; + SHAPES[SHAPES["RECT"] = 1] = "RECT"; + SHAPES[SHAPES["CIRC"] = 2] = "CIRC"; + SHAPES[SHAPES["ELIP"] = 3] = "ELIP"; + SHAPES[SHAPES["RREC"] = 4] = "RREC"; + })(exports.SHAPES || (exports.SHAPES = {})); -var _Resource = require('./Resource'); + /** + * The Point object represents a location in a two-dimensional coordinate system, where `x` represents + * the position on the horizontal axis and `y` represents the position on the vertical axis + * @class + * @memberof PIXI + * @implements {IPoint} + */ + var Point = /** @class */ (function () { + /** + * Creates a new `Point` + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function Point(x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + /** Position of the point on the x axis */ + this.x = 0; + /** Position of the point on the y axis */ + this.y = 0; + this.x = x; + this.y = y; + } + /** + * Creates a clone of this point + * @returns A clone of this point + */ + Point.prototype.clone = function () { + return new Point(this.x, this.y); + }; + /** + * Copies `x` and `y` from the given point into this point + * @param p - The point to copy from + * @returns The point instance itself + */ + Point.prototype.copyFrom = function (p) { + this.set(p.x, p.y); + return this; + }; + /** + * Copies this point's x and y into the given point (`p`). + * @param p - The point to copy to. Can be any of type that is or extends `IPointData` + * @returns The point (`p`) with values updated + */ + Point.prototype.copyTo = function (p) { + p.set(this.x, this.y); + return p; + }; + /** + * Accepts another point (`p`) and returns `true` if the given point is equal to this point + * @param p - The point to check + * @returns Returns `true` if both `x` and `y` are equal + */ + Point.prototype.equals = function (p) { + return (p.x === this.x) && (p.y === this.y); + }; + /** + * Sets the point to a new `x` and `y` position. + * If `y` is omitted, both `x` and `y` will be set to `x`. + * @param {number} [x=0] - position of the point on the `x` axis + * @param {number} [y=x] - position of the point on the `y` axis + * @returns The point instance itself + */ + Point.prototype.set = function (x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = x; } + this.x = x; + this.y = y; + return this; + }; + Point.prototype.toString = function () { + return "[@pixi/math:Point x=" + this.x + " y=" + this.y + "]"; + }; + return Point; + }()); + + var tempPoints$1 = [new Point(), new Point(), new Point(), new Point()]; + /** + * Size object, contains width and height + * @memberof PIXI + * @typedef {object} ISize + * @property {number} width - Width component + * @property {number} height - Height component + */ + /** + * Rectangle object is an area defined by its position, as indicated by its top-left corner + * point (x, y) and by its width and its height. + * @memberof PIXI + */ + var Rectangle = /** @class */ (function () { + /** + * @param x - The X coordinate of the upper-left corner of the rectangle + * @param y - The Y coordinate of the upper-left corner of the rectangle + * @param width - The overall width of the rectangle + * @param height - The overall height of the rectangle + */ + function Rectangle(x, y, width, height) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (width === void 0) { width = 0; } + if (height === void 0) { height = 0; } + this.x = Number(x); + this.y = Number(y); + this.width = Number(width); + this.height = Number(height); + this.type = exports.SHAPES.RECT; + } + Object.defineProperty(Rectangle.prototype, "left", { + /** Returns the left edge of the rectangle. */ + get: function () { + return this.x; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "right", { + /** Returns the right edge of the rectangle. */ + get: function () { + return this.x + this.width; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "top", { + /** Returns the top edge of the rectangle. */ + get: function () { + return this.y; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "bottom", { + /** Returns the bottom edge of the rectangle. */ + get: function () { + return this.y + this.height; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Rectangle, "EMPTY", { + /** A constant empty rectangle. */ + get: function () { + return new Rectangle(0, 0, 0, 0); + }, + enumerable: false, + configurable: true + }); + /** + * Creates a clone of this Rectangle + * @returns a copy of the rectangle + */ + Rectangle.prototype.clone = function () { + return new Rectangle(this.x, this.y, this.width, this.height); + }; + /** + * Copies another rectangle to this one. + * @param rectangle - The rectangle to copy from. + * @returns Returns itself. + */ + Rectangle.prototype.copyFrom = function (rectangle) { + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + return this; + }; + /** + * Copies this rectangle to another one. + * @param rectangle - The rectangle to copy to. + * @returns Returns given parameter. + */ + Rectangle.prototype.copyTo = function (rectangle) { + rectangle.x = this.x; + rectangle.y = this.y; + rectangle.width = this.width; + rectangle.height = this.height; + return rectangle; + }; + /** + * Checks whether the x and y coordinates given are contained within this Rectangle + * @param x - The X coordinate of the point to test + * @param y - The Y coordinate of the point to test + * @returns Whether the x/y coordinates are within this Rectangle + */ + Rectangle.prototype.contains = function (x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x < this.x + this.width) { + if (y >= this.y && y < this.y + this.height) { + return true; + } + } + return false; + }; + /** + * Determines whether the `other` Rectangle transformed by `transform` intersects with `this` Rectangle object. + * Returns true only if the area of the intersection is >0, this means that Rectangles + * sharing a side are not overlapping. Another side effect is that an arealess rectangle + * (width or height equal to zero) can't intersect any other rectangle. + * @param {Rectangle} other - The Rectangle to intersect with `this`. + * @param {Matrix} transform - The transformation matrix of `other`. + * @returns {boolean} A value of `true` if the transformed `other` Rectangle intersects with `this`; otherwise `false`. + */ + Rectangle.prototype.intersects = function (other, transform) { + if (!transform) { + var x0_1 = this.x < other.x ? other.x : this.x; + var x1_1 = this.right > other.right ? other.right : this.right; + if (x1_1 <= x0_1) { + return false; + } + var y0_1 = this.y < other.y ? other.y : this.y; + var y1_1 = this.bottom > other.bottom ? other.bottom : this.bottom; + return y1_1 > y0_1; + } + var x0 = this.left; + var x1 = this.right; + var y0 = this.top; + var y1 = this.bottom; + if (x1 <= x0 || y1 <= y0) { + return false; + } + var lt = tempPoints$1[0].set(other.left, other.top); + var lb = tempPoints$1[1].set(other.left, other.bottom); + var rt = tempPoints$1[2].set(other.right, other.top); + var rb = tempPoints$1[3].set(other.right, other.bottom); + if (rt.x <= lt.x || lb.y <= lt.y) { + return false; + } + var s = Math.sign((transform.a * transform.d) - (transform.b * transform.c)); + if (s === 0) { + return false; + } + transform.apply(lt, lt); + transform.apply(lb, lb); + transform.apply(rt, rt); + transform.apply(rb, rb); + if (Math.max(lt.x, lb.x, rt.x, rb.x) <= x0 + || Math.min(lt.x, lb.x, rt.x, rb.x) >= x1 + || Math.max(lt.y, lb.y, rt.y, rb.y) <= y0 + || Math.min(lt.y, lb.y, rt.y, rb.y) >= y1) { + return false; + } + var nx = s * (lb.y - lt.y); + var ny = s * (lt.x - lb.x); + var n00 = (nx * x0) + (ny * y0); + var n10 = (nx * x1) + (ny * y0); + var n01 = (nx * x0) + (ny * y1); + var n11 = (nx * x1) + (ny * y1); + if (Math.max(n00, n10, n01, n11) <= (nx * lt.x) + (ny * lt.y) + || Math.min(n00, n10, n01, n11) >= (nx * rb.x) + (ny * rb.y)) { + return false; + } + var mx = s * (lt.y - rt.y); + var my = s * (rt.x - lt.x); + var m00 = (mx * x0) + (my * y0); + var m10 = (mx * x1) + (my * y0); + var m01 = (mx * x0) + (my * y1); + var m11 = (mx * x1) + (my * y1); + if (Math.max(m00, m10, m01, m11) <= (mx * lt.x) + (my * lt.y) + || Math.min(m00, m10, m01, m11) >= (mx * rb.x) + (my * rb.y)) { + return false; + } + return true; + }; + /** + * Pads the rectangle making it grow in all directions. + * If paddingY is omitted, both paddingX and paddingY will be set to paddingX. + * @param paddingX - The horizontal padding amount. + * @param paddingY - The vertical padding amount. + * @returns Returns itself. + */ + Rectangle.prototype.pad = function (paddingX, paddingY) { + if (paddingX === void 0) { paddingX = 0; } + if (paddingY === void 0) { paddingY = paddingX; } + this.x -= paddingX; + this.y -= paddingY; + this.width += paddingX * 2; + this.height += paddingY * 2; + return this; + }; + /** + * Fits this rectangle around the passed one. + * @param rectangle - The rectangle to fit. + * @returns Returns itself. + */ + Rectangle.prototype.fit = function (rectangle) { + var x1 = Math.max(this.x, rectangle.x); + var x2 = Math.min(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.max(this.y, rectangle.y); + var y2 = Math.min(this.y + this.height, rectangle.y + rectangle.height); + this.x = x1; + this.width = Math.max(x2 - x1, 0); + this.y = y1; + this.height = Math.max(y2 - y1, 0); + return this; + }; + /** + * Enlarges rectangle that way its corners lie on grid + * @param resolution - resolution + * @param eps - precision + * @returns Returns itself. + */ + Rectangle.prototype.ceil = function (resolution, eps) { + if (resolution === void 0) { resolution = 1; } + if (eps === void 0) { eps = 0.001; } + var x2 = Math.ceil((this.x + this.width - eps) * resolution) / resolution; + var y2 = Math.ceil((this.y + this.height - eps) * resolution) / resolution; + this.x = Math.floor((this.x + eps) * resolution) / resolution; + this.y = Math.floor((this.y + eps) * resolution) / resolution; + this.width = x2 - this.x; + this.height = y2 - this.y; + return this; + }; + /** + * Enlarges this rectangle to include the passed rectangle. + * @param rectangle - The rectangle to include. + * @returns Returns itself. + */ + Rectangle.prototype.enlarge = function (rectangle) { + var x1 = Math.min(this.x, rectangle.x); + var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.min(this.y, rectangle.y); + var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; + return this; + }; + Rectangle.prototype.toString = function () { + return "[@pixi/math:Rectangle x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + "]"; + }; + return Rectangle; + }()); -var _Resource2 = _interopRequireDefault(_Resource); + /** + * The Circle object is used to help draw graphics and can also be used to specify a hit area for displayObjects. + * @memberof PIXI + */ + var Circle = /** @class */ (function () { + /** + * @param x - The X coordinate of the center of this circle + * @param y - The Y coordinate of the center of this circle + * @param radius - The radius of the circle + */ + function Circle(x, y, radius) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (radius === void 0) { radius = 0; } + this.x = x; + this.y = y; + this.radius = radius; + this.type = exports.SHAPES.CIRC; + } + /** + * Creates a clone of this Circle instance + * @returns A copy of the Circle + */ + Circle.prototype.clone = function () { + return new Circle(this.x, this.y, this.radius); + }; + /** + * Checks whether the x and y coordinates given are contained within this circle + * @param x - The X coordinate of the point to test + * @param y - The Y coordinate of the point to test + * @returns Whether the x/y coordinates are within this Circle + */ + Circle.prototype.contains = function (x, y) { + if (this.radius <= 0) { + return false; + } + var r2 = this.radius * this.radius; + var dx = (this.x - x); + var dy = (this.y - y); + dx *= dx; + dy *= dy; + return (dx + dy <= r2); + }; + /** + * Returns the framing rectangle of the circle as a Rectangle object + * @returns The framing rectangle + */ + Circle.prototype.getBounds = function () { + return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); + }; + Circle.prototype.toString = function () { + return "[@pixi/math:Circle x=" + this.x + " y=" + this.y + " radius=" + this.radius + "]"; + }; + return Circle; + }()); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + /** + * The Ellipse object is used to help draw graphics and can also be used to specify a hit area for displayObjects. + * @memberof PIXI + */ + var Ellipse = /** @class */ (function () { + /** + * @param x - The X coordinate of the center of this ellipse + * @param y - The Y coordinate of the center of this ellipse + * @param halfWidth - The half width of this ellipse + * @param halfHeight - The half height of this ellipse + */ + function Ellipse(x, y, halfWidth, halfHeight) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (halfWidth === void 0) { halfWidth = 0; } + if (halfHeight === void 0) { halfHeight = 0; } + this.x = x; + this.y = y; + this.width = halfWidth; + this.height = halfHeight; + this.type = exports.SHAPES.ELIP; + } + /** + * Creates a clone of this Ellipse instance + * @returns {PIXI.Ellipse} A copy of the ellipse + */ + Ellipse.prototype.clone = function () { + return new Ellipse(this.x, this.y, this.width, this.height); + }; + /** + * Checks whether the x and y coordinates given are contained within this ellipse + * @param x - The X coordinate of the point to test + * @param y - The Y coordinate of the point to test + * @returns Whether the x/y coords are within this ellipse + */ + Ellipse.prototype.contains = function (x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + // normalize the coords to an ellipse with center 0,0 + var normx = ((x - this.x) / this.width); + var normy = ((y - this.y) / this.height); + normx *= normx; + normy *= normy; + return (normx + normy <= 1); + }; + /** + * Returns the framing rectangle of the ellipse as a Rectangle object + * @returns The framing rectangle + */ + Ellipse.prototype.getBounds = function () { + return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); + }; + Ellipse.prototype.toString = function () { + return "[@pixi/math:Ellipse x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + "]"; + }; + return Ellipse; + }()); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** + * A class to define a shape via user defined coordinates. + * @memberof PIXI + */ + var Polygon = /** @class */ (function () { + /** + * @param {PIXI.IPointData[]|number[]} points - This can be an array of Points + * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or + * the arguments passed can be all the points of the polygon e.g. + * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat + * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. + */ + function Polygon() { + var arguments$1 = arguments; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var points = []; + for (var _i = 0; _i < arguments.length; _i++) { + points[_i] = arguments$1[_i]; + } + var flat = Array.isArray(points[0]) ? points[0] : points; + // if this is an array of points, convert it to a flat array of numbers + if (typeof flat[0] !== 'number') { + var p = []; + for (var i = 0, il = flat.length; i < il; i++) { + p.push(flat[i].x, flat[i].y); + } + flat = p; + } + this.points = flat; + this.type = exports.SHAPES.POLY; + this.closeStroke = true; + } + /** + * Creates a clone of this polygon. + * @returns - A copy of the polygon. + */ + Polygon.prototype.clone = function () { + var points = this.points.slice(); + var polygon = new Polygon(points); + polygon.closeStroke = this.closeStroke; + return polygon; + }; + /** + * Checks whether the x and y coordinates passed to this function are contained within this polygon. + * @param x - The X coordinate of the point to test. + * @param y - The Y coordinate of the point to test. + * @returns - Whether the x/y coordinates are within this polygon. + */ + Polygon.prototype.contains = function (x, y) { + var inside = false; + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = this.points.length / 2; + for (var i = 0, j = length - 1; i < length; j = i++) { + var xi = this.points[i * 2]; + var yi = this.points[(i * 2) + 1]; + var xj = this.points[j * 2]; + var yj = this.points[(j * 2) + 1]; + var intersect = ((yi > y) !== (yj > y)) && (x < ((xj - xi) * ((y - yi) / (yj - yi))) + xi); + if (intersect) { + inside = !inside; + } + } + return inside; + }; + Polygon.prototype.toString = function () { + return "[@pixi/math:Polygon" + + ("closeStroke=" + this.closeStroke) + + ("points=" + this.points.reduce(function (pointsDesc, currentPoint) { return pointsDesc + ", " + currentPoint; }, '') + "]"); + }; + return Polygon; + }()); -// some constants -var MAX_PROGRESS = 100; -var rgxExtractUrlHash = /(#[\w-]+)?$/; + /** + * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its + * top-left corner point (x, y) and by its width and its height and its radius. + * @memberof PIXI + */ + var RoundedRectangle = /** @class */ (function () { + /** + * @param x - The X coordinate of the upper-left corner of the rounded rectangle + * @param y - The Y coordinate of the upper-left corner of the rounded rectangle + * @param width - The overall width of this rounded rectangle + * @param height - The overall height of this rounded rectangle + * @param radius - Controls the radius of the rounded corners + */ + function RoundedRectangle(x, y, width, height, radius) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (width === void 0) { width = 0; } + if (height === void 0) { height = 0; } + if (radius === void 0) { radius = 20; } + this.x = x; + this.y = y; + this.width = width; + this.height = height; + this.radius = radius; + this.type = exports.SHAPES.RREC; + } + /** + * Creates a clone of this Rounded Rectangle. + * @returns - A copy of the rounded rectangle. + */ + RoundedRectangle.prototype.clone = function () { + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + }; + /** + * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * @param x - The X coordinate of the point to test. + * @param y - The Y coordinate of the point to test. + * @returns - Whether the x/y coordinates are within this Rounded Rectangle. + */ + RoundedRectangle.prototype.contains = function (x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x <= this.x + this.width) { + if (y >= this.y && y <= this.y + this.height) { + var radius = Math.max(0, Math.min(this.radius, Math.min(this.width, this.height) / 2)); + if ((y >= this.y + radius && y <= this.y + this.height - radius) + || (x >= this.x + radius && x <= this.x + this.width - radius)) { + return true; + } + var dx = x - (this.x + radius); + var dy = y - (this.y + radius); + var radius2 = radius * radius; + if ((dx * dx) + (dy * dy) <= radius2) { + return true; + } + dx = x - (this.x + this.width - radius); + if ((dx * dx) + (dy * dy) <= radius2) { + return true; + } + dy = y - (this.y + this.height - radius); + if ((dx * dx) + (dy * dy) <= radius2) { + return true; + } + dx = x - (this.x + radius); + if ((dx * dx) + (dy * dy) <= radius2) { + return true; + } + } + } + return false; + }; + RoundedRectangle.prototype.toString = function () { + return "[@pixi/math:RoundedRectangle x=" + this.x + " y=" + this.y + + ("width=" + this.width + " height=" + this.height + " radius=" + this.radius + "]"); + }; + return RoundedRectangle; + }()); -/** - * Manages the state and loading of multiple resources to load. - * - * @class - */ - -var Loader = function () { - /** - * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. - * @param {number} [concurrency=10] - The number of resources to load concurrently. - */ - function Loader() { - var _this = this; - - var baseUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; - var concurrency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; - - _classCallCheck(this, Loader); - - /** - * The base url for all resources loaded by this loader. - * - * @member {string} - */ - this.baseUrl = baseUrl; - - /** - * The progress percent of the loader going through the queue. - * - * @member {number} - */ - this.progress = 0; - - /** - * Loading state of the loader, true if it is currently loading resources. - * - * @member {boolean} - */ - this.loading = false; - - /** - * A querystring to append to every URL added to the loader. - * - * This should be a valid query string *without* the question-mark (`?`). The loader will - * also *not* escape values for you. Make sure to escape your parameters with - * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. - * - * @example - * const loader = new Loader(); - * - * loader.defaultQueryString = 'user=me&password=secret'; - * - * // This will request 'image.png?user=me&password=secret' - * loader.add('image.png').load(); - * - * loader.reset(); - * - * // This will request 'image.png?v=1&user=me&password=secret' - * loader.add('iamge.png?v=1').load(); - */ - this.defaultQueryString = ''; - - /** - * The middleware to run before loading each resource. - * - * @member {function[]} - */ - this._beforeMiddleware = []; - - /** - * The middleware to run after loading each resource. - * - * @member {function[]} - */ - this._afterMiddleware = []; - - /** - * The tracks the resources we are currently completing parsing for. - * - * @member {Resource[]} - */ - this._resourcesParsing = []; - - /** - * The `_loadResource` function bound with this object context. - * - * @private - * @member {function} - * @param {Resource} r - The resource to load - * @param {Function} d - The dequeue function - * @return {undefined} - */ - this._boundLoadResource = function (r, d) { - return _this._loadResource(r, d); - }; - - /** - * The resources waiting to be loaded. - * - * @private - * @member {Resource[]} - */ - this._queue = async.queue(this._boundLoadResource, concurrency); - - this._queue.pause(); - - /** - * All the resources for this loader keyed by name. - * - * @member {object} - */ - this.resources = {}; - - /** - * Dispatched once per loaded or errored resource. - * - * The callback looks like {@link Loader.OnProgressSignal}. - * - * @member {Signal} - */ - this.onProgress = new _miniSignals2.default(); - - /** - * Dispatched once per errored resource. - * - * The callback looks like {@link Loader.OnErrorSignal}. - * - * @member {Signal} - */ - this.onError = new _miniSignals2.default(); - - /** - * Dispatched once per loaded resource. - * - * The callback looks like {@link Loader.OnLoadSignal}. - * - * @member {Signal} - */ - this.onLoad = new _miniSignals2.default(); - - /** - * Dispatched when the loader begins to process the queue. - * - * The callback looks like {@link Loader.OnStartSignal}. - * - * @member {Signal} - */ - this.onStart = new _miniSignals2.default(); - - /** - * Dispatched when the queued resources all load. - * - * The callback looks like {@link Loader.OnCompleteSignal}. - * - * @member {Signal} - */ - this.onComplete = new _miniSignals2.default(); - - /** - * When the progress changes the loader and resource are disaptched. - * - * @memberof Loader - * @callback OnProgressSignal - * @param {Loader} loader - The loader the progress is advancing on. - * @param {Resource} resource - The resource that has completed or failed to cause the progress to advance. - */ - - /** - * When an error occurrs the loader and resource are disaptched. - * - * @memberof Loader - * @callback OnErrorSignal - * @param {Loader} loader - The loader the error happened in. - * @param {Resource} resource - The resource that caused the error. - */ - - /** - * When a load completes the loader and resource are disaptched. - * - * @memberof Loader - * @callback OnLoadSignal - * @param {Loader} loader - The loader that laoded the resource. - * @param {Resource} resource - The resource that has completed loading. - */ - - /** - * When the loader starts loading resources it dispatches this callback. - * - * @memberof Loader - * @callback OnStartSignal - * @param {Loader} loader - The loader that has started loading resources. - */ - - /** - * When the loader completes loading resources it dispatches this callback. - * - * @memberof Loader - * @callback OnCompleteSignal - * @param {Loader} loader - The loader that has finished loading resources. - */ - } - - /** - * Adds a resource (or multiple resources) to the loader queue. - * - * This function can take a wide variety of different parameters. The only thing that is always - * required the url to load. All the following will work: - * - * ```js - * loader - * // normal param syntax - * .add('key', 'http://...', function () {}) - * .add('http://...', function () {}) - * .add('http://...') - * - * // object syntax - * .add({ - * name: 'key2', - * url: 'http://...' - * }, function () {}) - * .add({ - * url: 'http://...' - * }, function () {}) - * .add({ - * name: 'key3', - * url: 'http://...' - * onComplete: function () {} - * }) - * .add({ - * url: 'https://...', - * onComplete: function () {}, - * crossOrigin: true - * }) - * - * // you can also pass an array of objects or urls or both - * .add([ - * { name: 'key4', url: 'http://...', onComplete: function () {} }, - * { url: 'http://...', onComplete: function () {} }, - * 'http://...' - * ]) - * - * // and you can use both params and options - * .add('key', 'http://...', { crossOrigin: true }, function () {}) - * .add('http://...', { crossOrigin: true }, function () {}); - * ``` - * - * @param {string} [name] - The name of the resource to load, if not passed the url is used. - * @param {string} [url] - The url for this resource, relative to the baseUrl of this loader. - * @param {object} [options] - The options for the load. - * @param {boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. - * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? - * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should - * the data being loaded be interpreted when using XHR? - * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. - * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The - * element to use for loading, instead of creating one. - * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This - * is useful if you want to pass in a `loadElement` that you already added load sources to. - * @param {function} [cb] - Function to call when this specific resource completes loading. - * @return {Loader} Returns itself. - */ - - - Loader.prototype.add = function add(name, url, options, cb) { - // special case of an array of objects or urls - if (Array.isArray(name)) { - for (var i = 0; i < name.length; ++i) { - this.add(name[i]); - } - - return this; - } - - // if an object is passed instead of params - if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') { - cb = url || name.callback || name.onComplete; - options = name; - url = name.url; - name = name.name || name.key || name.url; - } - - // case where no name is passed shift all args over by one. - if (typeof url !== 'string') { - cb = options; - options = url; - url = name; - } - - // now that we shifted make sure we have a proper url. - if (typeof url !== 'string') { - throw new Error('No url passed to add resource to loader.'); - } - - // options are optional so people might pass a function and no options - if (typeof options === 'function') { - cb = options; - options = null; - } - - // if loading already you can only add resources that have a parent. - if (this.loading && (!options || !options.parentResource)) { - throw new Error('Cannot add resources while the loader is running.'); - } - - // check if resource already exists. - if (this.resources[name]) { - throw new Error('Resource named "' + name + '" already exists.'); - } - - // add base url if this isn't an absolute url - url = this._prepareUrl(url); - - // create the store the resource - this.resources[name] = new _Resource2.default(name, url, options); - - if (typeof cb === 'function') { - this.resources[name].onAfterMiddleware.once(cb); - } - - // if actively loading, make sure to adjust progress chunks for that parent and its children - if (this.loading) { - var parent = options.parentResource; - var incompleteChildren = []; - - for (var _i = 0; _i < parent.children.length; ++_i) { - if (!parent.children[_i].isComplete) { - incompleteChildren.push(parent.children[_i]); - } - } - - var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent - var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child - - parent.children.push(this.resources[name]); - parent.progressChunk = eachChunk; - - for (var _i2 = 0; _i2 < incompleteChildren.length; ++_i2) { - incompleteChildren[_i2].progressChunk = eachChunk; - } - - this.resources[name].progressChunk = eachChunk; - } - - // add the resource to the queue - this._queue.push(this.resources[name]); - - return this; - }; - - /** - * Sets up a middleware function that will run *before* the - * resource is loaded. - * - * @method before - * @param {function} fn - The middleware function to register. - * @return {Loader} Returns itself. - */ - - - Loader.prototype.pre = function pre(fn) { - this._beforeMiddleware.push(fn); - - return this; - }; - - /** - * Sets up a middleware function that will run *after* the - * resource is loaded. - * - * @alias use - * @method after - * @param {function} fn - The middleware function to register. - * @return {Loader} Returns itself. - */ - - - Loader.prototype.use = function use(fn) { - this._afterMiddleware.push(fn); - - return this; - }; - - /** - * Resets the queue of the loader to prepare for a new load. - * - * @return {Loader} Returns itself. - */ - - - Loader.prototype.reset = function reset() { - this.progress = 0; - this.loading = false; - - this._queue.kill(); - this._queue.pause(); - - // abort all resource loads - for (var k in this.resources) { - var res = this.resources[k]; - - if (res._onLoadBinding) { - res._onLoadBinding.detach(); - } - - if (res.isLoading) { - res.abort(); - } - } - - this.resources = {}; - - return this; - }; - - /** - * Starts loading the queued resources. - * - * @param {function} [cb] - Optional callback that will be bound to the `complete` event. - * @return {Loader} Returns itself. - */ - - - Loader.prototype.load = function load(cb) { - // register complete callback if they pass one - if (typeof cb === 'function') { - this.onComplete.once(cb); - } - - // if the queue has already started we are done here - if (this.loading) { - return this; - } - - // distribute progress chunks - var chunk = 100 / this._queue._tasks.length; - - for (var i = 0; i < this._queue._tasks.length; ++i) { - this._queue._tasks[i].data.progressChunk = chunk; - } - - // update loading state - this.loading = true; - - // notify of start - this.onStart.dispatch(this); - - // start loading - this._queue.resume(); - - return this; - }; - - /** - * Prepares a url for usage based on the configuration of this object - * - * @private - * @param {string} url - The url to prepare. - * @return {string} The prepared url. - */ - - - Loader.prototype._prepareUrl = function _prepareUrl(url) { - var parsedUrl = (0, _parseUri2.default)(url, { strictMode: true }); - var result = void 0; - - // absolute url, just use it as is. - if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) { - result = url; - } - // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween - else if (this.baseUrl.length && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 && url.charAt(0) !== '/') { - result = this.baseUrl + '/' + url; - } else { - result = this.baseUrl + url; - } - - // if we need to add a default querystring, there is a bit more work - if (this.defaultQueryString) { - var hash = rgxExtractUrlHash.exec(result)[0]; - - result = result.substr(0, result.length - hash.length); - - if (result.indexOf('?') !== -1) { - result += '&' + this.defaultQueryString; - } else { - result += '?' + this.defaultQueryString; - } - - result += hash; - } - - return result; - }; - - /** - * Loads a single resource. - * - * @private - * @param {Resource} resource - The resource to load. - * @param {function} dequeue - The function to call when we need to dequeue this item. - */ - - - Loader.prototype._loadResource = function _loadResource(resource, dequeue) { - var _this2 = this; - - resource._dequeue = dequeue; - - // run before middleware - async.eachSeries(this._beforeMiddleware, function (fn, next) { - fn.call(_this2, resource, function () { - // if the before middleware marks the resource as complete, - // break and don't process any more before middleware - next(resource.isComplete ? {} : null); - }); - }, function () { - if (resource.isComplete) { - _this2._onLoad(resource); - } else { - resource._onLoadBinding = resource.onComplete.once(_this2._onLoad, _this2); - resource.load(); - } - }, true); - }; - - /** - * Called once each resource has loaded. - * - * @private - */ - - - Loader.prototype._onComplete = function _onComplete() { - this.loading = false; - - this.onComplete.dispatch(this, this.resources); - }; - - /** - * Called each time a resources is loaded. - * - * @private - * @param {Resource} resource - The resource that was loaded - */ - - - Loader.prototype._onLoad = function _onLoad(resource) { - var _this3 = this; - - resource._onLoadBinding = null; - - // remove this resource from the async queue, and add it to our list of resources that are being parsed - this._resourcesParsing.push(resource); - resource._dequeue(); - - // run all the after middleware for this resource - async.eachSeries(this._afterMiddleware, function (fn, next) { - fn.call(_this3, resource, next); - }, function () { - resource.onAfterMiddleware.dispatch(resource); - - _this3.progress += resource.progressChunk; - _this3.onProgress.dispatch(_this3, resource); - - if (resource.error) { - _this3.onError.dispatch(resource.error, _this3, resource); - } else { - _this3.onLoad.dispatch(_this3, resource); - } - - _this3._resourcesParsing.splice(_this3._resourcesParsing.indexOf(resource), 1); - - // do completion check - if (_this3._queue.idle() && _this3._resourcesParsing.length === 0) { - _this3.progress = MAX_PROGRESS; - _this3._onComplete(); - } - }, true); - }; - - return Loader; -}(); - -exports.default = Loader; - -},{"./Resource":33,"./async":34,"mini-signals":38,"parse-uri":39}],33:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _parseUri = require('parse-uri'); - -var _parseUri2 = _interopRequireDefault(_parseUri); - -var _miniSignals = require('mini-signals'); - -var _miniSignals2 = _interopRequireDefault(_miniSignals); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -// tests is CORS is supported in XHR, if not we need to use XDR -var useXdr = !!(window.XDomainRequest && !('withCredentials' in new XMLHttpRequest())); -var tempAnchor = null; - -// some status constants -var STATUS_NONE = 0; -var STATUS_OK = 200; -var STATUS_EMPTY = 204; -var STATUS_IE_BUG_EMPTY = 1223; -var STATUS_TYPE_OK = 2; - -// noop -function _noop() {} /* empty */ - -/** - * Manages the state and loading of a resource and all child resources. - * - * @class - */ - -var Resource = function () { - /** - * Sets the load type to be used for a specific extension. - * - * @static - * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" - * @param {Resource.LOAD_TYPE} loadType - The load type to set it to. - */ - Resource.setExtensionLoadType = function setExtensionLoadType(extname, loadType) { - setExtMap(Resource._loadTypeMap, extname, loadType); - }; - - /** - * Sets the load type to be used for a specific extension. - * - * @static - * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" - * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. - */ - - - Resource.setExtensionXhrType = function setExtensionXhrType(extname, xhrType) { - setExtMap(Resource._xhrTypeMap, extname, xhrType); - }; - - /** - * @param {string} name - The name of the resource to load. - * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass - * an array of sources. - * @param {object} [options] - The options for the load. - * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to - * determine automatically. - * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource - * be loaded? - * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How - * should the data being loaded be interpreted when using XHR? - * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. - * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The - * element to use for loading, instead of creating one. - * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This - * is useful if you want to pass in a `loadElement` that you already added load sources to. - * @param {string|string[]} [options.metadata.mimeType] - The mime type to use for the source element of a video/audio - * elment. If the urls are an array, you can pass this as an array as well where each index is the mime type to - * use for the corresponding url index. - */ - - - function Resource(name, url, options) { - _classCallCheck(this, Resource); - - if (typeof name !== 'string' || typeof url !== 'string') { - throw new Error('Both name and url are required for constructing a resource.'); - } - - options = options || {}; - - /** - * The state flags of this resource. - * - * @member {number} - */ - this._flags = 0; - - // set data url flag, needs to be set early for some _determineX checks to work. - this._setFlag(Resource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0); - - /** - * The name of this resource. - * - * @member {string} - * @readonly - */ - this.name = name; - - /** - * The url used to load this resource. - * - * @member {string} - * @readonly - */ - this.url = url; - - /** - * The extension used to load this resource. - * - * @member {string} - * @readonly - */ - this.extension = this._getExtension(); - - /** - * The data that was loaded by the resource. - * - * @member {any} - */ - this.data = null; - - /** - * Is this request cross-origin? If unset, determined automatically. - * - * @member {string} - */ - this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; - - /** - * The method of loading to use for this resource. - * - * @member {Resource.LOAD_TYPE} - */ - this.loadType = options.loadType || this._determineLoadType(); - - /** - * The type used to load the resource via XHR. If unset, determined automatically. - * - * @member {string} - */ - this.xhrType = options.xhrType; - - /** - * Extra info for middleware, and controlling specifics about how the resource loads. - * - * Note that if you pass in a `loadElement`, the Resource class takes ownership of it. - * Meaning it will modify it as it sees fit. - * - * @member {object} - * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The - * element to use for loading, instead of creating one. - * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This - * is useful if you want to pass in a `loadElement` that you already added load sources - * to. - */ - this.metadata = options.metadata || {}; - - /** - * The error that occurred while loading (if any). - * - * @member {Error} - * @readonly - */ - this.error = null; - - /** - * The XHR object that was used to load this resource. This is only set - * when `loadType` is `Resource.LOAD_TYPE.XHR`. - * - * @member {XMLHttpRequest} - * @readonly - */ - this.xhr = null; - - /** - * The child resources this resource owns. - * - * @member {Resource[]} - * @readonly - */ - this.children = []; - - /** - * The resource type. - * - * @member {Resource.TYPE} - * @readonly - */ - this.type = Resource.TYPE.UNKNOWN; - - /** - * The progress chunk owned by this resource. - * - * @member {number} - * @readonly - */ - this.progressChunk = 0; - - /** - * The `dequeue` method that will be used a storage place for the async queue dequeue method - * used privately by the loader. - * - * @private - * @member {function} - */ - this._dequeue = _noop; - - /** - * Used a storage place for the on load binding used privately by the loader. - * - * @private - * @member {function} - */ - this._onLoadBinding = null; - - /** - * The `complete` function bound to this resource's context. - * - * @private - * @member {function} - */ - this._boundComplete = this.complete.bind(this); - - /** - * The `_onError` function bound to this resource's context. - * - * @private - * @member {function} - */ - this._boundOnError = this._onError.bind(this); - - /** - * The `_onProgress` function bound to this resource's context. - * - * @private - * @member {function} - */ - this._boundOnProgress = this._onProgress.bind(this); - - // xhr callbacks - this._boundXhrOnError = this._xhrOnError.bind(this); - this._boundXhrOnAbort = this._xhrOnAbort.bind(this); - this._boundXhrOnLoad = this._xhrOnLoad.bind(this); - this._boundXdrOnTimeout = this._xdrOnTimeout.bind(this); - - /** - * Dispatched when the resource beings to load. - * - * The callback looks like {@link Resource.OnStartSignal}. - * - * @member {Signal} - */ - this.onStart = new _miniSignals2.default(); - - /** - * Dispatched each time progress of this resource load updates. - * Not all resources types and loader systems can support this event - * so sometimes it may not be available. If the resource - * is being loaded on a modern browser, using XHR, and the remote server - * properly sets Content-Length headers, then this will be available. - * - * The callback looks like {@link Resource.OnProgressSignal}. - * - * @member {Signal} - */ - this.onProgress = new _miniSignals2.default(); - - /** - * Dispatched once this resource has loaded, if there was an error it will - * be in the `error` property. - * - * The callback looks like {@link Resource.OnCompleteSignal}. - * - * @member {Signal} - */ - this.onComplete = new _miniSignals2.default(); - - /** - * Dispatched after this resource has had all the *after* middleware run on it. - * - * The callback looks like {@link Resource.OnCompleteSignal}. - * - * @member {Signal} - */ - this.onAfterMiddleware = new _miniSignals2.default(); - - /** - * When the resource starts to load. - * - * @memberof Resource - * @callback OnStartSignal - * @param {Resource} resource - The resource that the event happened on. - */ - - /** - * When the resource reports loading progress. - * - * @memberof Resource - * @callback OnProgressSignal - * @param {Resource} resource - The resource that the event happened on. - * @param {number} percentage - The progress of the load in the range [0, 1]. - */ - - /** - * When the resource finishes loading. - * - * @memberof Resource - * @callback OnCompleteSignal - * @param {Resource} resource - The resource that the event happened on. - */ - } - - /** - * Stores whether or not this url is a data url. - * - * @member {boolean} - * @readonly - */ - - - /** - * Marks the resource as complete. - * - */ - Resource.prototype.complete = function complete() { - // TODO: Clean this up in a wrapper or something...gross.... - if (this.data && this.data.removeEventListener) { - this.data.removeEventListener('error', this._boundOnError, false); - this.data.removeEventListener('load', this._boundComplete, false); - this.data.removeEventListener('progress', this._boundOnProgress, false); - this.data.removeEventListener('canplaythrough', this._boundComplete, false); - } - - if (this.xhr) { - if (this.xhr.removeEventListener) { - this.xhr.removeEventListener('error', this._boundXhrOnError, false); - this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); - this.xhr.removeEventListener('progress', this._boundOnProgress, false); - this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); - } else { - this.xhr.onerror = null; - this.xhr.ontimeout = null; - this.xhr.onprogress = null; - this.xhr.onload = null; - } - } - - if (this.isComplete) { - throw new Error('Complete called again for an already completed resource.'); - } - - this._setFlag(Resource.STATUS_FLAGS.COMPLETE, true); - this._setFlag(Resource.STATUS_FLAGS.LOADING, false); - - this.onComplete.dispatch(this); - }; - - /** - * Aborts the loading of this resource, with an optional message. - * - * @param {string} message - The message to use for the error - */ - - - Resource.prototype.abort = function abort(message) { - // abort can be called multiple times, ignore subsequent calls. - if (this.error) { - return; - } - - // store error - this.error = new Error(message); - - // abort the actual loading - if (this.xhr) { - this.xhr.abort(); - } else if (this.xdr) { - this.xdr.abort(); - } else if (this.data) { - // single source - if (this.data.src) { - this.data.src = Resource.EMPTY_GIF; - } - // multi-source - else { - while (this.data.firstChild) { - this.data.removeChild(this.data.firstChild); - } - } - } - - // done now. - this.complete(); - }; - - /** - * Kicks off loading of this resource. This method is asynchronous. - * - * @param {function} [cb] - Optional callback to call once the resource is loaded. - */ - - - Resource.prototype.load = function load(cb) { - var _this = this; - - if (this.isLoading) { - return; - } - - if (this.isComplete) { - if (cb) { - setTimeout(function () { - return cb(_this); - }, 1); - } - - return; - } else if (cb) { - this.onComplete.once(cb); - } - - this._setFlag(Resource.STATUS_FLAGS.LOADING, true); - - this.onStart.dispatch(this); - - // if unset, determine the value - if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { - this.crossOrigin = this._determineCrossOrigin(this.url); - } - - switch (this.loadType) { - case Resource.LOAD_TYPE.IMAGE: - this.type = Resource.TYPE.IMAGE; - this._loadElement('image'); - break; - - case Resource.LOAD_TYPE.AUDIO: - this.type = Resource.TYPE.AUDIO; - this._loadSourceElement('audio'); - break; - - case Resource.LOAD_TYPE.VIDEO: - this.type = Resource.TYPE.VIDEO; - this._loadSourceElement('video'); - break; - - case Resource.LOAD_TYPE.XHR: - /* falls through */ - default: - if (useXdr && this.crossOrigin) { - this._loadXdr(); - } else { - this._loadXhr(); - } - break; - } - }; - - /** - * Checks if the flag is set. - * - * @private - * @param {number} flag - The flag to check. - * @return {boolean} True if the flag is set. - */ - - - Resource.prototype._hasFlag = function _hasFlag(flag) { - return !!(this._flags & flag); - }; - - /** - * (Un)Sets the flag. - * - * @private - * @param {number} flag - The flag to (un)set. - * @param {boolean} value - Whether to set or (un)set the flag. - */ - - - Resource.prototype._setFlag = function _setFlag(flag, value) { - this._flags = value ? this._flags | flag : this._flags & ~flag; - }; - - /** - * Loads this resources using an element that has a single source, - * like an HTMLImageElement. - * - * @private - * @param {string} type - The type of element to use. - */ - - - Resource.prototype._loadElement = function _loadElement(type) { - if (this.metadata.loadElement) { - this.data = this.metadata.loadElement; - } else if (type === 'image' && typeof window.Image !== 'undefined') { - this.data = new Image(); - } else { - this.data = document.createElement(type); - } - - if (this.crossOrigin) { - this.data.crossOrigin = this.crossOrigin; - } - - if (!this.metadata.skipSource) { - this.data.src = this.url; - } - - this.data.addEventListener('error', this._boundOnError, false); - this.data.addEventListener('load', this._boundComplete, false); - this.data.addEventListener('progress', this._boundOnProgress, false); - }; - - /** - * Loads this resources using an element that has multiple sources, - * like an HTMLAudioElement or HTMLVideoElement. - * - * @private - * @param {string} type - The type of element to use. - */ - - - Resource.prototype._loadSourceElement = function _loadSourceElement(type) { - if (this.metadata.loadElement) { - this.data = this.metadata.loadElement; - } else if (type === 'audio' && typeof window.Audio !== 'undefined') { - this.data = new Audio(); - } else { - this.data = document.createElement(type); - } - - if (this.data === null) { - this.abort('Unsupported element: ' + type); - - return; - } - - if (!this.metadata.skipSource) { - // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') - if (navigator.isCocoonJS) { - this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; - } else if (Array.isArray(this.url)) { - var mimeTypes = this.metadata.mimeType; - - for (var i = 0; i < this.url.length; ++i) { - this.data.appendChild(this._createSource(type, this.url[i], Array.isArray(mimeTypes) ? mimeTypes[i] : mimeTypes)); - } - } else { - var _mimeTypes = this.metadata.mimeType; - - this.data.appendChild(this._createSource(type, this.url, Array.isArray(_mimeTypes) ? _mimeTypes[0] : _mimeTypes)); - } - } - - this.data.addEventListener('error', this._boundOnError, false); - this.data.addEventListener('load', this._boundComplete, false); - this.data.addEventListener('progress', this._boundOnProgress, false); - this.data.addEventListener('canplaythrough', this._boundComplete, false); - - this.data.load(); - }; - - /** - * Loads this resources using an XMLHttpRequest. - * - * @private - */ - - - Resource.prototype._loadXhr = function _loadXhr() { - // if unset, determine the value - if (typeof this.xhrType !== 'string') { - this.xhrType = this._determineXhrType(); - } - - var xhr = this.xhr = new XMLHttpRequest(); - - // set the request type and url - xhr.open('GET', this.url, true); - - // load json as text and parse it ourselves. We do this because some browsers - // *cough* safari *cough* can't deal with it. - if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { - xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT; - } else { - xhr.responseType = this.xhrType; - } - - xhr.addEventListener('error', this._boundXhrOnError, false); - xhr.addEventListener('abort', this._boundXhrOnAbort, false); - xhr.addEventListener('progress', this._boundOnProgress, false); - xhr.addEventListener('load', this._boundXhrOnLoad, false); - - xhr.send(); - }; - - /** - * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). - * - * @private - */ - - - Resource.prototype._loadXdr = function _loadXdr() { - // if unset, determine the value - if (typeof this.xhrType !== 'string') { - this.xhrType = this._determineXhrType(); - } - - var xdr = this.xhr = new XDomainRequest(); - - // XDomainRequest has a few quirks. Occasionally it will abort requests - // A way to avoid this is to make sure ALL callbacks are set even if not used - // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 - xdr.timeout = 5000; - - xdr.onerror = this._boundXhrOnError; - xdr.ontimeout = this._boundXdrOnTimeout; - xdr.onprogress = this._boundOnProgress; - xdr.onload = this._boundXhrOnLoad; - - xdr.open('GET', this.url, true); - - // Note: The xdr.send() call is wrapped in a timeout to prevent an - // issue with the interface where some requests are lost if multiple - // XDomainRequests are being sent at the same time. - // Some info here: https://github.com/photonstorm/phaser/issues/1248 - setTimeout(function () { - return xdr.send(); - }, 1); - }; - - /** - * Creates a source used in loading via an element. - * - * @private - * @param {string} type - The element type (video or audio). - * @param {string} url - The source URL to load from. - * @param {string} [mime] - The mime type of the video - * @return {HTMLSourceElement} The source element. - */ - - - Resource.prototype._createSource = function _createSource(type, url, mime) { - if (!mime) { - mime = type + '/' + this._getExtension(url); - } - - var source = document.createElement('source'); - - source.src = url; - source.type = mime; - - return source; - }; - - /** - * Called if a load errors out. - * - * @param {Event} event - The error event from the element that emits it. - * @private - */ - - - Resource.prototype._onError = function _onError(event) { - this.abort('Failed to load element using: ' + event.target.nodeName); - }; - - /** - * Called if a load progress event fires for xhr/xdr. - * - * @private - * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. - */ - - - Resource.prototype._onProgress = function _onProgress(event) { - if (event && event.lengthComputable) { - this.onProgress.dispatch(this, event.loaded / event.total); - } - }; - - /** - * Called if an error event fires for xhr/xdr. - * - * @private - * @param {XMLHttpRequestErrorEvent|Event} event - Error event. - */ - - - Resource.prototype._xhrOnError = function _xhrOnError() { - var xhr = this.xhr; - - this.abort(reqType(xhr) + ' Request failed. Status: ' + xhr.status + ', text: "' + xhr.statusText + '"'); - }; - - /** - * Called if an abort event fires for xhr. - * - * @private - * @param {XMLHttpRequestAbortEvent} event - Abort Event - */ - - - Resource.prototype._xhrOnAbort = function _xhrOnAbort() { - this.abort(reqType(this.xhr) + ' Request was aborted by the user.'); - }; - - /** - * Called if a timeout event fires for xdr. - * - * @private - * @param {Event} event - Timeout event. - */ - - - Resource.prototype._xdrOnTimeout = function _xdrOnTimeout() { - this.abort(reqType(this.xhr) + ' Request timed out.'); - }; - - /** - * Called when data successfully loads from an xhr/xdr request. - * - * @private - * @param {XMLHttpRequestLoadEvent|Event} event - Load event - */ - - - Resource.prototype._xhrOnLoad = function _xhrOnLoad() { - var xhr = this.xhr; - var text = ''; - var status = typeof xhr.status === 'undefined' ? STATUS_OK : xhr.status; // XDR has no `.status`, assume 200. - - // responseText is accessible only if responseType is '' or 'text' and on older browsers - if (xhr.responseType === '' || xhr.responseType === 'text' || typeof xhr.responseType === 'undefined') { - text = xhr.responseText; - } - - // status can be 0 when using the `file://` protocol so we also check if a response is set. - // If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request. - if (status === STATUS_NONE && text.length > 0) { - status = STATUS_OK; - } - // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request - else if (status === STATUS_IE_BUG_EMPTY) { - status = STATUS_EMPTY; - } - - var statusType = status / 100 | 0; - - if (statusType === STATUS_TYPE_OK) { - // if text, just return it - if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) { - this.data = text; - this.type = Resource.TYPE.TEXT; - } - // if json, parse into json object - else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { - try { - this.data = JSON.parse(text); - this.type = Resource.TYPE.JSON; - } catch (e) { - this.abort('Error trying to parse loaded json: ' + e); - - return; - } - } - // if xml, parse into an xml document or div element - else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { - try { - if (window.DOMParser) { - var domparser = new DOMParser(); - - this.data = domparser.parseFromString(text, 'text/xml'); - } else { - var div = document.createElement('div'); - - div.innerHTML = text; - - this.data = div; - } - - this.type = Resource.TYPE.XML; - } catch (e) { - this.abort('Error trying to parse loaded xml: ' + e); - - return; - } - } - // other types just return the response - else { - this.data = xhr.response || text; - } - } else { - this.abort('[' + xhr.status + '] ' + xhr.statusText + ': ' + xhr.responseURL); - - return; - } - - this.complete(); - }; - - /** - * Sets the `crossOrigin` property for this resource based on if the url - * for this resource is cross-origin. If crossOrigin was manually set, this - * function does nothing. - * - * @private - * @param {string} url - The url to test. - * @param {object} [loc=window.location] - The location object to test against. - * @return {string} The crossOrigin value to use (or empty string for none). - */ - - - Resource.prototype._determineCrossOrigin = function _determineCrossOrigin(url, loc) { - // data: and javascript: urls are considered same-origin - if (url.indexOf('data:') === 0) { - return ''; - } - - // default is window.location - loc = loc || window.location; - - if (!tempAnchor) { - tempAnchor = document.createElement('a'); - } - - // let the browser determine the full href for the url of this resource and then - // parse with the node url lib, we can't use the properties of the anchor element - // because they don't work in IE9 :( - tempAnchor.href = url; - url = (0, _parseUri2.default)(tempAnchor.href, { strictMode: true }); - - var samePort = !url.port && loc.port === '' || url.port === loc.port; - var protocol = url.protocol ? url.protocol + ':' : ''; - - // if cross origin - if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) { - return 'anonymous'; - } - - return ''; - }; - - /** - * Determines the responseType of an XHR request based on the extension of the - * resource being loaded. - * - * @private - * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. - */ - - - Resource.prototype._determineXhrType = function _determineXhrType() { - return Resource._xhrTypeMap[this.extension] || Resource.XHR_RESPONSE_TYPE.TEXT; - }; - - /** - * Determines the loadType of a resource based on the extension of the - * resource being loaded. - * - * @private - * @return {Resource.LOAD_TYPE} The loadType to use. - */ - - - Resource.prototype._determineLoadType = function _determineLoadType() { - return Resource._loadTypeMap[this.extension] || Resource.LOAD_TYPE.XHR; - }; - - /** - * Extracts the extension (sans '.') of the file being loaded by the resource. - * - * @private - * @return {string} The extension. - */ - - - Resource.prototype._getExtension = function _getExtension() { - var url = this.url; - var ext = ''; - - if (this.isDataUrl) { - var slashIndex = url.indexOf('/'); - - ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); - } else { - var queryStart = url.indexOf('?'); - var hashStart = url.indexOf('#'); - var index = Math.min(queryStart > -1 ? queryStart : url.length, hashStart > -1 ? hashStart : url.length); - - url = url.substring(0, index); - ext = url.substring(url.lastIndexOf('.') + 1); - } - - return ext.toLowerCase(); - }; - - /** - * Determines the mime type of an XHR request based on the responseType of - * resource being loaded. - * - * @private - * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. - * @return {string} The mime type to use. - */ - - - Resource.prototype._getMimeFromXhrType = function _getMimeFromXhrType(type) { - switch (type) { - case Resource.XHR_RESPONSE_TYPE.BUFFER: - return 'application/octet-binary'; - - case Resource.XHR_RESPONSE_TYPE.BLOB: - return 'application/blob'; - - case Resource.XHR_RESPONSE_TYPE.DOCUMENT: - return 'application/xml'; - - case Resource.XHR_RESPONSE_TYPE.JSON: - return 'application/json'; - - case Resource.XHR_RESPONSE_TYPE.DEFAULT: - case Resource.XHR_RESPONSE_TYPE.TEXT: - /* falls through */ - default: - return 'text/plain'; - - } - }; - - _createClass(Resource, [{ - key: 'isDataUrl', - get: function get() { - return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL); - } - - /** - * Describes if this resource has finished loading. Is true when the resource has completely - * loaded. - * - * @member {boolean} - * @readonly - */ - - }, { - key: 'isComplete', - get: function get() { - return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE); - } - - /** - * Describes if this resource is currently loading. Is true when the resource starts loading, - * and is false again when complete. - * - * @member {boolean} - * @readonly - */ - - }, { - key: 'isLoading', - get: function get() { - return this._hasFlag(Resource.STATUS_FLAGS.LOADING); - } - }]); - - return Resource; -}(); - -/** - * The types of resources a resource could represent. - * - * @static - * @readonly - * @enum {number} - */ - - -exports.default = Resource; -Resource.STATUS_FLAGS = { - NONE: 0, - DATA_URL: 1 << 0, - COMPLETE: 1 << 1, - LOADING: 1 << 2 -}; - -/** - * The types of resources a resource could represent. - * - * @static - * @readonly - * @enum {number} - */ -Resource.TYPE = { - UNKNOWN: 0, - JSON: 1, - XML: 2, - IMAGE: 3, - AUDIO: 4, - VIDEO: 5, - TEXT: 6 -}; - -/** - * The types of loading a resource can use. - * - * @static - * @readonly - * @enum {number} - */ -Resource.LOAD_TYPE = { - /** Uses XMLHttpRequest to load the resource. */ - XHR: 1, - /** Uses an `Image` object to load the resource. */ - IMAGE: 2, - /** Uses an `Audio` object to load the resource. */ - AUDIO: 3, - /** Uses a `Video` object to load the resource. */ - VIDEO: 4 -}; - -/** - * The XHR ready states, used internally. - * - * @static - * @readonly - * @enum {string} - */ -Resource.XHR_RESPONSE_TYPE = { - /** string */ - DEFAULT: 'text', - /** ArrayBuffer */ - BUFFER: 'arraybuffer', - /** Blob */ - BLOB: 'blob', - /** Document */ - DOCUMENT: 'document', - /** Object */ - JSON: 'json', - /** String */ - TEXT: 'text' -}; - -Resource._loadTypeMap = { - // images - gif: Resource.LOAD_TYPE.IMAGE, - png: Resource.LOAD_TYPE.IMAGE, - bmp: Resource.LOAD_TYPE.IMAGE, - jpg: Resource.LOAD_TYPE.IMAGE, - jpeg: Resource.LOAD_TYPE.IMAGE, - tif: Resource.LOAD_TYPE.IMAGE, - tiff: Resource.LOAD_TYPE.IMAGE, - webp: Resource.LOAD_TYPE.IMAGE, - tga: Resource.LOAD_TYPE.IMAGE, - svg: Resource.LOAD_TYPE.IMAGE, - 'svg+xml': Resource.LOAD_TYPE.IMAGE, // for SVG data urls - - // audio - mp3: Resource.LOAD_TYPE.AUDIO, - ogg: Resource.LOAD_TYPE.AUDIO, - wav: Resource.LOAD_TYPE.AUDIO, - - // videos - mp4: Resource.LOAD_TYPE.VIDEO, - webm: Resource.LOAD_TYPE.VIDEO -}; - -Resource._xhrTypeMap = { - // xml - xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, - html: Resource.XHR_RESPONSE_TYPE.DOCUMENT, - htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT, - xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, - tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, - svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT, - - // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. - // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, - // this should probably be fine. - tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, - - // images - gif: Resource.XHR_RESPONSE_TYPE.BLOB, - png: Resource.XHR_RESPONSE_TYPE.BLOB, - bmp: Resource.XHR_RESPONSE_TYPE.BLOB, - jpg: Resource.XHR_RESPONSE_TYPE.BLOB, - jpeg: Resource.XHR_RESPONSE_TYPE.BLOB, - tif: Resource.XHR_RESPONSE_TYPE.BLOB, - tiff: Resource.XHR_RESPONSE_TYPE.BLOB, - webp: Resource.XHR_RESPONSE_TYPE.BLOB, - tga: Resource.XHR_RESPONSE_TYPE.BLOB, - - // json - json: Resource.XHR_RESPONSE_TYPE.JSON, - - // text - text: Resource.XHR_RESPONSE_TYPE.TEXT, - txt: Resource.XHR_RESPONSE_TYPE.TEXT, - - // fonts - ttf: Resource.XHR_RESPONSE_TYPE.BUFFER, - otf: Resource.XHR_RESPONSE_TYPE.BUFFER -}; - -// We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif -Resource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; - -/** - * Quick helper to set a value on one of the extension maps. Ensures there is no - * dot at the start of the extension. - * - * @ignore - * @param {object} map - The map to set on. - * @param {string} extname - The extension (or key) to set. - * @param {number} val - The value to set. - */ -function setExtMap(map, extname, val) { - if (extname && extname.indexOf('.') === 0) { - extname = extname.substring(1); - } - - if (!extname) { - return; - } - - map[extname] = val; -} - -/** - * Quick helper to get string xhr type. - * - * @ignore - * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. - * @return {string} The type. - */ -function reqType(xhr) { - return xhr.toString().replace('object ', ''); -} - -},{"mini-signals":38,"parse-uri":39}],34:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.eachSeries = eachSeries; -exports.queue = queue; -/** - * Smaller version of the async library constructs. - * - */ -function _noop() {} /* empty */ - -/** - * Iterates an array in series. - * - * @param {Array.<*>} array - Array to iterate. - * @param {function} iterator - Function to call for each element. - * @param {function} callback - Function to call when done, or on error. - * @param {boolean} [deferNext=false] - Break synchronous each loop by calling next with a setTimeout of 1. - */ -function eachSeries(array, iterator, callback, deferNext) { - var i = 0; - var len = array.length; - - (function next(err) { - if (err || i === len) { - if (callback) { - callback(err); - } - - return; - } - - if (deferNext) { - setTimeout(function () { - iterator(array[i++], next); - }, 1); - } else { - iterator(array[i++], next); - } - })(); -} - -/** - * Ensures a function is only called once. - * - * @param {function} fn - The function to wrap. - * @return {function} The wrapping function. - */ -function onlyOnce(fn) { - return function onceWrapper() { - if (fn === null) { - throw new Error('Callback was already called.'); - } - - var callFn = fn; - - fn = null; - callFn.apply(this, arguments); - }; -} - -/** - * Async queue implementation, - * - * @param {function} worker - The worker function to call for each task. - * @param {number} concurrency - How many workers to run in parrallel. - * @return {*} The async queue object. - */ -function queue(worker, concurrency) { - if (concurrency == null) { - // eslint-disable-line no-eq-null,eqeqeq - concurrency = 1; - } else if (concurrency === 0) { - throw new Error('Concurrency must not be zero'); - } - - var workers = 0; - var q = { - _tasks: [], - concurrency: concurrency, - saturated: _noop, - unsaturated: _noop, - buffer: concurrency / 4, - empty: _noop, - drain: _noop, - error: _noop, - started: false, - paused: false, - push: function push(data, callback) { - _insert(data, false, callback); - }, - kill: function kill() { - workers = 0; - q.drain = _noop; - q.started = false; - q._tasks = []; - }, - unshift: function unshift(data, callback) { - _insert(data, true, callback); - }, - process: function process() { - while (!q.paused && workers < q.concurrency && q._tasks.length) { - var task = q._tasks.shift(); - - if (q._tasks.length === 0) { - q.empty(); - } - - workers += 1; - - if (workers === q.concurrency) { - q.saturated(); - } - - worker(task.data, onlyOnce(_next(task))); - } - }, - length: function length() { - return q._tasks.length; - }, - running: function running() { - return workers; - }, - idle: function idle() { - return q._tasks.length + workers === 0; - }, - pause: function pause() { - if (q.paused === true) { - return; - } - - q.paused = true; - }, - resume: function resume() { - if (q.paused === false) { - return; - } - - q.paused = false; - - // Need to call q.process once per concurrent - // worker to preserve full concurrency after pause - for (var w = 1; w <= q.concurrency; w++) { - q.process(); - } - } - }; - - function _insert(data, insertAtFront, callback) { - if (callback != null && typeof callback !== 'function') { - // eslint-disable-line no-eq-null,eqeqeq - throw new Error('task callback must be a function'); - } - - q.started = true; - - if (data == null && q.idle()) { - // eslint-disable-line no-eq-null,eqeqeq - // call drain immediately if there are no tasks - setTimeout(function () { - return q.drain(); - }, 1); - - return; - } - - var item = { - data: data, - callback: typeof callback === 'function' ? callback : _noop - }; - - if (insertAtFront) { - q._tasks.unshift(item); - } else { - q._tasks.push(item); - } - - setTimeout(function () { - return q.process(); - }, 1); - } - - function _next(task) { - return function next() { - workers -= 1; - - task.callback.apply(task, arguments); - - if (arguments[0] != null) { - // eslint-disable-line no-eq-null,eqeqeq - q.error(arguments[0], task.data); - } - - if (workers <= q.concurrency - q.buffer) { - q.unsaturated(); - } - - if (q.idle()) { - q.drain(); - } - - q.process(); - }; - } - - return q; -} - -},{}],35:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.encodeBinary = encodeBinary; -var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - -function encodeBinary(input) { - var output = ''; - var inx = 0; - - while (inx < input.length) { - // Fill byte buffer array - var bytebuffer = [0, 0, 0]; - var encodedCharIndexes = [0, 0, 0, 0]; - - for (var jnx = 0; jnx < bytebuffer.length; ++jnx) { - if (inx < input.length) { - // throw away high-order byte, as documented at: - // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data - bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; - } else { - bytebuffer[jnx] = 0; - } - } - - // Get each encoded character, 6 bits at a time - // index 1: first 6 bits - encodedCharIndexes[0] = bytebuffer[0] >> 2; - - // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) - encodedCharIndexes[1] = (bytebuffer[0] & 0x3) << 4 | bytebuffer[1] >> 4; - - // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) - encodedCharIndexes[2] = (bytebuffer[1] & 0x0f) << 2 | bytebuffer[2] >> 6; - - // index 3: forth 6 bits (6 least significant bits from input byte 3) - encodedCharIndexes[3] = bytebuffer[2] & 0x3f; - - // Determine whether padding happened, and adjust accordingly - var paddingBytes = inx - (input.length - 1); - - switch (paddingBytes) { - case 2: - // Set last 2 characters to padding char - encodedCharIndexes[3] = 64; - encodedCharIndexes[2] = 64; - break; - - case 1: - // Set last character to padding char - encodedCharIndexes[3] = 64; - break; - - default: - break; // No padding - proceed - } - - // Now we will grab each appropriate character out of our keystring - // based on our index array and append it to the output string - for (var _jnx = 0; _jnx < encodedCharIndexes.length; ++_jnx) { - output += _keyStr.charAt(encodedCharIndexes[_jnx]); - } - } - - return output; -} - -},{}],36:[function(require,module,exports){ -'use strict'; - -// import Loader from './Loader'; -// import Resource from './Resource'; -// import * as async from './async'; -// import * as b64 from './b64'; - -/* eslint-disable no-undef */ - -var Loader = require('./Loader').default; -var Resource = require('./Resource').default; -var async = require('./async'); -var b64 = require('./b64'); - -Loader.Resource = Resource; -Loader.async = async; -Loader.base64 = b64; - -// export manually, and also as default -module.exports = Loader; -// export default Loader; -module.exports.default = Loader; - -},{"./Loader":32,"./Resource":33,"./async":34,"./b64":35}],37:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -exports.blobMiddlewareFactory = blobMiddlewareFactory; - -var _Resource = require('../../Resource'); - -var _Resource2 = _interopRequireDefault(_Resource); - -var _b = require('../../b64'); - -var _b2 = _interopRequireDefault(_b); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var Url = window.URL || window.webkitURL; - -// a middleware for transforming XHR loaded Blobs into more useful objects -function blobMiddlewareFactory() { - return function blobMiddleware(resource, next) { - if (!resource.data) { - next(); - - return; - } - - // if this was an XHR load of a blob - if (resource.xhr && resource.xhrType === _Resource2.default.XHR_RESPONSE_TYPE.BLOB) { - // if there is no blob support we probably got a binary string back - if (!window.Blob || typeof resource.data === 'string') { - var type = resource.xhr.getResponseHeader('content-type'); - - // this is an image, convert the binary string into a data url - if (type && type.indexOf('image') === 0) { - resource.data = new Image(); - resource.data.src = 'data:' + type + ';base64,' + _b2.default.encodeBinary(resource.xhr.responseText); - - resource.type = _Resource2.default.TYPE.IMAGE; - - // wait until the image loads and then callback - resource.data.onload = function () { - resource.data.onload = null; - - next(); - }; - - // next will be called on load - return; - } - } - // if content type says this is an image, then we should transform the blob into an Image object - else if (resource.data.type.indexOf('image') === 0) { - var _ret = function () { - var src = Url.createObjectURL(resource.data); - - resource.blob = resource.data; - resource.data = new Image(); - resource.data.src = src; - - resource.type = _Resource2.default.TYPE.IMAGE; - - // cleanup the no longer used blob after the image loads - // TODO: Is this correct? Will the image be invalid after revoking? - resource.data.onload = function () { - Url.revokeObjectURL(src); - resource.data.onload = null; - - next(); - }; - - // next will be called on load. - return { - v: void 0 - }; - }(); - - if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; - } - } - - next(); - }; -} - -},{"../../Resource":33,"../../b64":35}],38:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, '__esModule', { - value: true -}); - -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - -var MiniSignalBinding = (function () { - function MiniSignalBinding(fn, once, thisArg) { - if (once === undefined) once = false; - - _classCallCheck(this, MiniSignalBinding); - - this._fn = fn; - this._once = once; - this._thisArg = thisArg; - this._next = this._prev = this._owner = null; - } - - _createClass(MiniSignalBinding, [{ - key: 'detach', - value: function detach() { - if (this._owner === null) return false; - this._owner.detach(this); - return true; - } - }]); - - return MiniSignalBinding; -})(); - -function _addMiniSignalBinding(self, node) { - if (!self._head) { - self._head = node; - self._tail = node; - } else { - self._tail._next = node; - node._prev = self._tail; - self._tail = node; - } - - node._owner = self; - - return node; -} - -var MiniSignal = (function () { - function MiniSignal() { - _classCallCheck(this, MiniSignal); - - this._head = this._tail = undefined; - } - - _createClass(MiniSignal, [{ - key: 'handlers', - value: function handlers() { - var exists = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; - - var node = this._head; - - if (exists) return !!node; - - var ee = []; - - while (node) { - ee.push(node); - node = node._next; - } - - return ee; - } - }, { - key: 'has', - value: function has(node) { - if (!(node instanceof MiniSignalBinding)) { - throw new Error('MiniSignal#has(): First arg must be a MiniSignalBinding object.'); - } - - return node._owner === this; - } - }, { - key: 'dispatch', - value: function dispatch() { - var node = this._head; - - if (!node) return false; - - while (node) { - if (node._once) this.detach(node); - node._fn.apply(node._thisArg, arguments); - node = node._next; - } - - return true; - } - }, { - key: 'add', - value: function add(fn) { - var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; - - if (typeof fn !== 'function') { - throw new Error('MiniSignal#add(): First arg must be a Function.'); - } - return _addMiniSignalBinding(this, new MiniSignalBinding(fn, false, thisArg)); - } - }, { - key: 'once', - value: function once(fn) { - var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; - - if (typeof fn !== 'function') { - throw new Error('MiniSignal#once(): First arg must be a Function.'); - } - return _addMiniSignalBinding(this, new MiniSignalBinding(fn, true, thisArg)); - } - }, { - key: 'detach', - value: function detach(node) { - if (!(node instanceof MiniSignalBinding)) { - throw new Error('MiniSignal#detach(): First arg must be a MiniSignalBinding object.'); - } - if (node._owner !== this) return this; - - if (node._prev) node._prev._next = node._next; - if (node._next) node._next._prev = node._prev; - - if (node === this._head) { - this._head = node._next; - if (node._next === null) { - this._tail = null; - } - } else if (node === this._tail) { - this._tail = node._prev; - this._tail._next = null; - } - - node._owner = null; - return this; - } - }, { - key: 'detachAll', - value: function detachAll() { - var node = this._head; - if (!node) return this; - - this._head = this._tail = null; - - while (node) { - node._owner = null; - node = node._next; - } - return this; - } - }]); - - return MiniSignal; -})(); - -MiniSignal.MiniSignalBinding = MiniSignalBinding; - -exports['default'] = MiniSignal; -module.exports = exports['default']; - -},{}],39:[function(require,module,exports){ -'use strict' - -module.exports = function parseURI (str, opts) { - opts = opts || {} - - var o = { - key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], - q: { - name: 'queryKey', - parser: /(?:^|&)([^&=]*)=?([^&]*)/g - }, - parser: { - strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, - loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ - } - } - - var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str) - var uri = {} - var i = 14 - - while (i--) uri[o.key[i]] = m[i] || '' - - uri[o.q.name] = {} - uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { - if ($1) uri[o.q.name][$1] = $2 - }) - - return uri -} - -},{}],40:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _core = require('../core'); - -var core = _interopRequireWildcard(_core); - -var _ismobilejs = require('ismobilejs'); - -var _ismobilejs2 = _interopRequireDefault(_ismobilejs); - -var _accessibleTarget = require('./accessibleTarget'); - -var _accessibleTarget2 = _interopRequireDefault(_accessibleTarget); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -// add some extra variables to the container.. -core.utils.mixins.delayMixin(core.DisplayObject.prototype, _accessibleTarget2.default); - -var KEY_CODE_TAB = 9; - -var DIV_TOUCH_SIZE = 100; -var DIV_TOUCH_POS_X = 0; -var DIV_TOUCH_POS_Y = 0; -var DIV_TOUCH_ZINDEX = 2; - -var DIV_HOOK_SIZE = 1; -var DIV_HOOK_POS_X = -1000; -var DIV_HOOK_POS_Y = -1000; -var DIV_HOOK_ZINDEX = 2; - -/** - * The Accessibility manager recreates the ability to tab and have content read by screen - * readers. This is very important as it can possibly help people with disabilities access pixi - * content. - * - * Much like interaction any DisplayObject can be made accessible. This manager will map the - * events as if the mouse was being used, minimizing the effort required to implement. - * - * An instance of this class is automatically created by default, and can be found at renderer.plugins.accessibility - * - * @class - * @memberof PIXI.accessibility - */ - -var AccessibilityManager = function () { - /** - * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer - */ - function AccessibilityManager(renderer) { - _classCallCheck(this, AccessibilityManager); - - if ((_ismobilejs2.default.tablet || _ismobilejs2.default.phone) && !navigator.isCocoonJS) { - this.createTouchHook(); - } - - // first we create a div that will sit over the PixiJS element. This is where the div overlays will go. - var div = document.createElement('div'); - - div.style.width = DIV_TOUCH_SIZE + 'px'; - div.style.height = DIV_TOUCH_SIZE + 'px'; - div.style.position = 'absolute'; - div.style.top = DIV_TOUCH_POS_X + 'px'; - div.style.left = DIV_TOUCH_POS_Y + 'px'; - div.style.zIndex = DIV_TOUCH_ZINDEX; - - /** - * This is the dom element that will sit over the PixiJS element. This is where the div overlays will go. - * - * @type {HTMLElement} - * @private - */ - this.div = div; - - /** - * A simple pool for storing divs. - * - * @type {*} - * @private - */ - this.pool = []; - - /** - * This is a tick used to check if an object is no longer being rendered. - * - * @type {Number} - * @private - */ - this.renderId = 0; - - /** - * Setting this to true will visually show the divs. - * - * @type {boolean} - */ - this.debug = false; - - /** - * The renderer this accessibility manager works for. - * - * @member {PIXI.SystemRenderer} - */ - this.renderer = renderer; - - /** - * The array of currently active accessible items. - * - * @member {Array<*>} - * @private - */ - this.children = []; - - /** - * pre-bind the functions - * - * @private - */ - this._onKeyDown = this._onKeyDown.bind(this); - this._onMouseMove = this._onMouseMove.bind(this); - - /** - * stores the state of the manager. If there are no accessible objects or the mouse is moving, this will be false. - * - * @member {Array<*>} - * @private - */ - this.isActive = false; - this.isMobileAccessabillity = false; - - // let listen for tab.. once pressed we can fire up and show the accessibility layer - window.addEventListener('keydown', this._onKeyDown, false); - } - - /** - * Creates the touch hooks. - * - */ - - - AccessibilityManager.prototype.createTouchHook = function createTouchHook() { - var _this = this; - - var hookDiv = document.createElement('button'); - - hookDiv.style.width = DIV_HOOK_SIZE + 'px'; - hookDiv.style.height = DIV_HOOK_SIZE + 'px'; - hookDiv.style.position = 'absolute'; - hookDiv.style.top = DIV_HOOK_POS_X + 'px'; - hookDiv.style.left = DIV_HOOK_POS_Y + 'px'; - hookDiv.style.zIndex = DIV_HOOK_ZINDEX; - hookDiv.style.backgroundColor = '#FF0000'; - hookDiv.title = 'HOOK DIV'; - - hookDiv.addEventListener('focus', function () { - _this.isMobileAccessabillity = true; - _this.activate(); - document.body.removeChild(hookDiv); - }); - - document.body.appendChild(hookDiv); - }; - - /** - * Activating will cause the Accessibility layer to be shown. This is called when a user - * preses the tab key. - * - * @private - */ - - - AccessibilityManager.prototype.activate = function activate() { - if (this.isActive) { - return; - } - - this.isActive = true; - - window.document.addEventListener('mousemove', this._onMouseMove, true); - window.removeEventListener('keydown', this._onKeyDown, false); - - this.renderer.on('postrender', this.update, this); - - if (this.renderer.view.parentNode) { - this.renderer.view.parentNode.appendChild(this.div); - } - }; - - /** - * Deactivating will cause the Accessibility layer to be hidden. This is called when a user moves - * the mouse. - * - * @private - */ - - - AccessibilityManager.prototype.deactivate = function deactivate() { - if (!this.isActive || this.isMobileAccessabillity) { - return; - } - - this.isActive = false; - - window.document.removeEventListener('mousemove', this._onMouseMove); - window.addEventListener('keydown', this._onKeyDown, false); - - this.renderer.off('postrender', this.update); - - if (this.div.parentNode) { - this.div.parentNode.removeChild(this.div); - } - }; - - /** - * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer. - * - * @private - * @param {PIXI.Container} displayObject - The DisplayObject to check. - */ - - - AccessibilityManager.prototype.updateAccessibleObjects = function updateAccessibleObjects(displayObject) { - if (!displayObject.visible) { - return; - } - - if (displayObject.accessible && displayObject.interactive) { - if (!displayObject._accessibleActive) { - this.addChild(displayObject); - } - - displayObject.renderId = this.renderId; - } - - var children = displayObject.children; - - for (var i = children.length - 1; i >= 0; i--) { - this.updateAccessibleObjects(children[i]); - } - }; - - /** - * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. - * - * @private - */ - - - AccessibilityManager.prototype.update = function update() { - if (!this.renderer.renderingToScreen) { - return; - } - - // update children... - this.updateAccessibleObjects(this.renderer._lastObjectRendered); - - var rect = this.renderer.view.getBoundingClientRect(); - var sx = rect.width / this.renderer.width; - var sy = rect.height / this.renderer.height; - - var div = this.div; - - div.style.left = rect.left + 'px'; - div.style.top = rect.top + 'px'; - div.style.width = this.renderer.width + 'px'; - div.style.height = this.renderer.height + 'px'; - - for (var i = 0; i < this.children.length; i++) { - var child = this.children[i]; - - if (child.renderId !== this.renderId) { - child._accessibleActive = false; - - core.utils.removeItems(this.children, i, 1); - this.div.removeChild(child._accessibleDiv); - this.pool.push(child._accessibleDiv); - child._accessibleDiv = null; - - i--; - - if (this.children.length === 0) { - this.deactivate(); - } - } else { - // map div to display.. - div = child._accessibleDiv; - var hitArea = child.hitArea; - var wt = child.worldTransform; - - if (child.hitArea) { - div.style.left = (wt.tx + hitArea.x * wt.a) * sx + 'px'; - div.style.top = (wt.ty + hitArea.y * wt.d) * sy + 'px'; - - div.style.width = hitArea.width * wt.a * sx + 'px'; - div.style.height = hitArea.height * wt.d * sy + 'px'; - } else { - hitArea = child.getBounds(); - - this.capHitArea(hitArea); - - div.style.left = hitArea.x * sx + 'px'; - div.style.top = hitArea.y * sy + 'px'; - - div.style.width = hitArea.width * sx + 'px'; - div.style.height = hitArea.height * sy + 'px'; - } - } - } - - // increment the render id.. - this.renderId++; - }; - - /** - * TODO: docs. - * - * @param {Rectangle} hitArea - TODO docs - */ - - - AccessibilityManager.prototype.capHitArea = function capHitArea(hitArea) { - if (hitArea.x < 0) { - hitArea.width += hitArea.x; - hitArea.x = 0; - } - - if (hitArea.y < 0) { - hitArea.height += hitArea.y; - hitArea.y = 0; - } - - if (hitArea.x + hitArea.width > this.renderer.width) { - hitArea.width = this.renderer.width - hitArea.x; - } - - if (hitArea.y + hitArea.height > this.renderer.height) { - hitArea.height = this.renderer.height - hitArea.y; - } - }; - - /** - * Adds a DisplayObject to the accessibility manager - * - * @private - * @param {DisplayObject} displayObject - The child to make accessible. - */ - - - AccessibilityManager.prototype.addChild = function addChild(displayObject) { - // this.activate(); - - var div = this.pool.pop(); - - if (!div) { - div = document.createElement('button'); - - div.style.width = DIV_TOUCH_SIZE + 'px'; - div.style.height = DIV_TOUCH_SIZE + 'px'; - div.style.backgroundColor = this.debug ? 'rgba(255,0,0,0.5)' : 'transparent'; - div.style.position = 'absolute'; - div.style.zIndex = DIV_TOUCH_ZINDEX; - div.style.borderStyle = 'none'; - - div.addEventListener('click', this._onClick.bind(this)); - div.addEventListener('focus', this._onFocus.bind(this)); - div.addEventListener('focusout', this._onFocusOut.bind(this)); - } - - if (displayObject.accessibleTitle) { - div.title = displayObject.accessibleTitle; - } else if (!displayObject.accessibleTitle && !displayObject.accessibleHint) { - div.title = 'displayObject ' + this.tabIndex; - } - - if (displayObject.accessibleHint) { - div.setAttribute('aria-label', displayObject.accessibleHint); - } - - // - - displayObject._accessibleActive = true; - displayObject._accessibleDiv = div; - div.displayObject = displayObject; - - this.children.push(displayObject); - this.div.appendChild(displayObject._accessibleDiv); - displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; - }; - - /** - * Maps the div button press to pixi's InteractionManager (click) - * - * @private - * @param {MouseEvent} e - The click event. - */ - - - AccessibilityManager.prototype._onClick = function _onClick(e) { - var interactionManager = this.renderer.plugins.interaction; - - interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); - }; - - /** - * Maps the div focus events to pixi's InteractionManager (mouseover) - * - * @private - * @param {FocusEvent} e - The focus event. - */ - - - AccessibilityManager.prototype._onFocus = function _onFocus(e) { - var interactionManager = this.renderer.plugins.interaction; - - interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); - }; - - /** - * Maps the div focus events to pixi's InteractionManager (mouseout) - * - * @private - * @param {FocusEvent} e - The focusout event. - */ - - - AccessibilityManager.prototype._onFocusOut = function _onFocusOut(e) { - var interactionManager = this.renderer.plugins.interaction; - - interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); - }; - - /** - * Is called when a key is pressed - * - * @private - * @param {KeyboardEvent} e - The keydown event. - */ - - - AccessibilityManager.prototype._onKeyDown = function _onKeyDown(e) { - if (e.keyCode !== KEY_CODE_TAB) { - return; - } - - this.activate(); - }; - - /** - * Is called when the mouse moves across the renderer element - * - * @private - */ - - - AccessibilityManager.prototype._onMouseMove = function _onMouseMove() { - this.deactivate(); - }; - - /** - * Destroys the accessibility manager - * - */ - - - AccessibilityManager.prototype.destroy = function destroy() { - this.div = null; - - for (var i = 0; i < this.children.length; i++) { - this.children[i].div = null; - } - - window.document.removeEventListener('mousemove', this._onMouseMove); - window.removeEventListener('keydown', this._onKeyDown); - - this.pool = null; - this.children = null; - this.renderer = null; - }; - - return AccessibilityManager; -}(); - -exports.default = AccessibilityManager; - - -core.WebGLRenderer.registerPlugin('accessibility', AccessibilityManager); -core.CanvasRenderer.registerPlugin('accessibility', AccessibilityManager); - -},{"../core":65,"./accessibleTarget":41,"ismobilejs":4}],41:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -/** - * Default property values of accessible objects - * used by {@link PIXI.accessibility.AccessibilityManager}. - * - * @function accessibleTarget - * @memberof PIXI.accessibility - * @example - * function MyObject() {} - * - * Object.assign( - * MyObject.prototype, - * PIXI.accessibility.accessibleTarget - * ); - */ -exports.default = { - /** - * Flag for if the object is accessible. If true AccessibilityManager will overlay a - * shadow div with attributes set - * - * @member {boolean} - */ - accessible: false, - - /** - * Sets the title attribute of the shadow div - * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' - * - * @member {string} - */ - accessibleTitle: null, - - /** - * Sets the aria-label attribute of the shadow div - * - * @member {string} - */ - accessibleHint: null, - - /** - * @todo Needs docs. - */ - tabIndex: 0, - - /** - * @todo Needs docs. - */ - _accessibleActive: false, - - /** - * @todo Needs docs. - */ - _accessibleDiv: false -}; - -},{}],42:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _accessibleTarget = require('./accessibleTarget'); - -Object.defineProperty(exports, 'accessibleTarget', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_accessibleTarget).default; - } -}); - -var _AccessibilityManager = require('./AccessibilityManager'); - -Object.defineProperty(exports, 'AccessibilityManager', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_AccessibilityManager).default; - } -}); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -},{"./AccessibilityManager":40,"./accessibleTarget":41}],43:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _autoDetectRenderer = require('./autoDetectRenderer'); - -var _Container = require('./display/Container'); - -var _Container2 = _interopRequireDefault(_Container); - -var _ticker = require('./ticker'); - -var _settings = require('./settings'); - -var _settings2 = _interopRequireDefault(_settings); - -var _const = require('./const'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * Convenience class to create a new PIXI application. - * This class automatically creates the renderer, ticker - * and root container. - * - * @example - * // Create the application - * const app = new PIXI.Application(); - * - * // Add the view to the DOM - * document.body.appendChild(app.view); - * - * // ex, add display objects - * app.stage.addChild(PIXI.Sprite.fromImage('something.png')); - * - * @class - * @memberof PIXI - */ -var Application = function () { - // eslint-disable-next-line valid-jsdoc - /** - * @param {object} [options] - The optional renderer parameters - * @param {number} [options.width=800] - the width of the renderers view - * @param {number} [options.height=600] - the height of the renderers view - * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional - * @param {boolean} [options.transparent=false] - If the render view is transparent, default false - * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) - * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you - * need to call toDataUrl on the webgl context - * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 - * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present - * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area - * (shown if not transparent). - * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or - * not before the new render pass. - * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, - * stopping pixel interpolation. - * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. - * FXAA is faster, but may not always look as great **webgl only** - * @param {boolean} [options.legacy=false] - `true` to ensure compatibility with older / less advanced devices. - * If you experience unexplained flickering try setting this to true. **webgl only** - * @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.ticker.shared, `false` to create new ticker. - * @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.loaders.shared, `false` to create new Loader. - */ - function Application(options, arg2, arg3, arg4, arg5) { - _classCallCheck(this, Application); - - // Support for constructor(width, height, options, noWebGL, useSharedTicker) - if (typeof options === 'number') { - options = Object.assign({ - width: options, - height: arg2 || _settings2.default.RENDER_OPTIONS.height, - forceCanvas: !!arg4, - sharedTicker: !!arg5 - }, arg3); - } - - /** - * The default options, so we mixin functionality later. - * @member {object} - * @protected - */ - this._options = options = Object.assign({ - sharedTicker: false, - forceCanvas: false, - sharedLoader: false - }, options); - - /** - * WebGL renderer if available, otherwise CanvasRenderer - * @member {PIXI.WebGLRenderer|PIXI.CanvasRenderer} - */ - this.renderer = (0, _autoDetectRenderer.autoDetectRenderer)(options); - - /** - * The root display container that's rendered. - * @member {PIXI.Container} - */ - this.stage = new _Container2.default(); - - /** - * Internal reference to the ticker - * @member {PIXI.ticker.Ticker} - * @private - */ - this._ticker = null; - - /** - * Ticker for doing render updates. - * @member {PIXI.ticker.Ticker} - * @default PIXI.ticker.shared - */ - this.ticker = options.sharedTicker ? _ticker.shared : new _ticker.Ticker(); - - // Start the rendering - this.start(); - } - - /** - * Render the current stage. - */ - Application.prototype.render = function render() { - this.renderer.render(this.stage); - }; - - /** - * Convenience method for stopping the render. - */ - - - Application.prototype.stop = function stop() { - this._ticker.stop(); - }; - - /** - * Convenience method for starting the render. - */ - - - Application.prototype.start = function start() { - this._ticker.start(); - }; - - /** - * Reference to the renderer's canvas element. - * @member {HTMLCanvasElement} - * @readonly - */ - - - /** - * Destroy and don't use after this. - * @param {Boolean} [removeView=false] Automatically remove canvas from DOM. - */ - Application.prototype.destroy = function destroy(removeView) { - var oldTicker = this._ticker; - - this.ticker = null; - - oldTicker.destroy(); - - this.stage.destroy(); - this.stage = null; - - this.renderer.destroy(removeView); - this.renderer = null; - - this._options = null; - }; - - _createClass(Application, [{ - key: 'ticker', - set: function set(ticker) // eslint-disable-line require-jsdoc - { - if (this._ticker) { - this._ticker.remove(this.render, this); - } - this._ticker = ticker; - if (ticker) { - ticker.add(this.render, this, _const.UPDATE_PRIORITY.LOW); - } - }, - get: function get() // eslint-disable-line require-jsdoc - { - return this._ticker; - } - }, { - key: 'view', - get: function get() { - return this.renderer.view; - } - - /** - * Reference to the renderer's screen rectangle. Its safe to use as filterArea or hitArea for whole screen - * @member {PIXI.Rectangle} - * @readonly - */ - - }, { - key: 'screen', - get: function get() { - return this.renderer.screen; - } - }]); - - return Application; -}(); - -exports.default = Application; - -},{"./autoDetectRenderer":45,"./const":46,"./display/Container":48,"./settings":101,"./ticker":120}],44:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _pixiGlCore = require('pixi-gl-core'); - -var _settings = require('./settings'); - -var _settings2 = _interopRequireDefault(_settings); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -function checkPrecision(src, def) { - if (src instanceof Array) { - if (src[0].substring(0, 9) !== 'precision') { - var copy = src.slice(0); - - copy.unshift('precision ' + def + ' float;'); - - return copy; - } - } else if (src.substring(0, 9) !== 'precision') { - return 'precision ' + def + ' float;\n' + src; - } - - return src; -} - -/** - * Wrapper class, webGL Shader for Pixi. - * Adds precision string if vertexSrc or fragmentSrc have no mention of it. - * - * @class - * @extends GLShader - * @memberof PIXI - */ - -var Shader = function (_GLShader) { - _inherits(Shader, _GLShader); - - /** - * - * @param {WebGLRenderingContext} gl - The current WebGL rendering context - * @param {string|string[]} vertexSrc - The vertex shader source as an array of strings. - * @param {string|string[]} fragmentSrc - The fragment shader source as an array of strings. - */ - function Shader(gl, vertexSrc, fragmentSrc) { - _classCallCheck(this, Shader); - - return _possibleConstructorReturn(this, _GLShader.call(this, gl, checkPrecision(vertexSrc, _settings2.default.PRECISION_VERTEX), checkPrecision(fragmentSrc, _settings2.default.PRECISION_FRAGMENT))); - } - - return Shader; -}(_pixiGlCore.GLShader); - -exports.default = Shader; - -},{"./settings":101,"pixi-gl-core":12}],45:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.autoDetectRenderer = autoDetectRenderer; - -var _utils = require('./utils'); - -var utils = _interopRequireWildcard(_utils); - -var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); - -var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); - -var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); - -var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -// eslint-disable-next-line valid-jsdoc -/** - * This helper function will automatically detect which renderer you should be using. - * WebGL is the preferred renderer as it is a lot faster. If webGL is not supported by - * the browser then this function will return a canvas renderer - * - * @memberof PIXI - * @function autoDetectRenderer - * @param {object} [options] - The optional renderer parameters - * @param {number} [options.width=800] - the width of the renderers view - * @param {number} [options.height=600] - the height of the renderers view - * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional - * @param {boolean} [options.transparent=false] - If the render view is transparent, default false - * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) - * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you - * need to call toDataUrl on the webgl context - * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area - * (shown if not transparent). - * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or - * not before the new render pass. - * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 - * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present - * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, - * stopping pixel interpolation. - * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. - * FXAA is faster, but may not always look as great **webgl only** - * @param {boolean} [options.legacy=false] - `true` to ensure compatibility with older / less advanced devices. - * If you experience unexplained flickering try setting this to true. **webgl only** - * @return {PIXI.WebGLRenderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer - */ -function autoDetectRenderer(options, arg1, arg2, arg3) { - // Backward-compatible support for noWebGL option - var forceCanvas = options && options.forceCanvas; - - if (arg3 !== undefined) { - forceCanvas = arg3; - } - - if (!forceCanvas && utils.isWebGLSupported()) { - return new _WebGLRenderer2.default(options, arg1, arg2); - } - - return new _CanvasRenderer2.default(options, arg1, arg2); -} - -},{"./renderers/canvas/CanvasRenderer":77,"./renderers/webgl/WebGLRenderer":84,"./utils":124}],46:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -/** - * String of the current PIXI version. - * - * @static - * @constant - * @memberof PIXI - * @name VERSION - * @type {string} - */ -var VERSION = exports.VERSION = '4.5.4'; - -/** - * Two Pi. - * - * @static - * @constant - * @memberof PIXI - * @type {number} - */ -var PI_2 = exports.PI_2 = Math.PI * 2; - -/** - * Conversion factor for converting radians to degrees. - * - * @static - * @constant - * @memberof PIXI - * @type {number} - */ -var RAD_TO_DEG = exports.RAD_TO_DEG = 180 / Math.PI; - -/** - * Conversion factor for converting degrees to radians. - * - * @static - * @constant - * @memberof PIXI - * @type {number} - */ -var DEG_TO_RAD = exports.DEG_TO_RAD = Math.PI / 180; - -/** - * Constant to identify the Renderer Type. - * - * @static - * @constant - * @memberof PIXI - * @name RENDERER_TYPE - * @type {object} - * @property {number} UNKNOWN - Unknown render type. - * @property {number} WEBGL - WebGL render type. - * @property {number} CANVAS - Canvas render type. - */ -var RENDERER_TYPE = exports.RENDERER_TYPE = { - UNKNOWN: 0, - WEBGL: 1, - CANVAS: 2 -}; - -/** - * Various blend modes supported by PIXI. - * - * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. - * Anything else will silently act like NORMAL. - * - * @static - * @constant - * @memberof PIXI - * @name BLEND_MODES - * @type {object} - * @property {number} NORMAL - * @property {number} ADD - * @property {number} MULTIPLY - * @property {number} SCREEN - * @property {number} OVERLAY - * @property {number} DARKEN - * @property {number} LIGHTEN - * @property {number} COLOR_DODGE - * @property {number} COLOR_BURN - * @property {number} HARD_LIGHT - * @property {number} SOFT_LIGHT - * @property {number} DIFFERENCE - * @property {number} EXCLUSION - * @property {number} HUE - * @property {number} SATURATION - * @property {number} COLOR - * @property {number} LUMINOSITY - */ -var BLEND_MODES = exports.BLEND_MODES = { - NORMAL: 0, - ADD: 1, - MULTIPLY: 2, - SCREEN: 3, - OVERLAY: 4, - DARKEN: 5, - LIGHTEN: 6, - COLOR_DODGE: 7, - COLOR_BURN: 8, - HARD_LIGHT: 9, - SOFT_LIGHT: 10, - DIFFERENCE: 11, - EXCLUSION: 12, - HUE: 13, - SATURATION: 14, - COLOR: 15, - LUMINOSITY: 16, - NORMAL_NPM: 17, - ADD_NPM: 18, - SCREEN_NPM: 19 -}; - -/** - * Various webgl draw modes. These can be used to specify which GL drawMode to use - * under certain situations and renderers. - * - * @static - * @constant - * @memberof PIXI - * @name DRAW_MODES - * @type {object} - * @property {number} POINTS - * @property {number} LINES - * @property {number} LINE_LOOP - * @property {number} LINE_STRIP - * @property {number} TRIANGLES - * @property {number} TRIANGLE_STRIP - * @property {number} TRIANGLE_FAN - */ -var DRAW_MODES = exports.DRAW_MODES = { - POINTS: 0, - LINES: 1, - LINE_LOOP: 2, - LINE_STRIP: 3, - TRIANGLES: 4, - TRIANGLE_STRIP: 5, - TRIANGLE_FAN: 6 -}; - -/** - * The scale modes that are supported by pixi. - * - * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. - * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. - * - * @static - * @constant - * @memberof PIXI - * @name SCALE_MODES - * @type {object} - * @property {number} LINEAR Smooth scaling - * @property {number} NEAREST Pixelating scaling - */ -var SCALE_MODES = exports.SCALE_MODES = { - LINEAR: 0, - NEAREST: 1 -}; - -/** - * The wrap modes that are supported by pixi. - * - * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wraping mode of future operations. - * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. - * If the texture is non power of two then clamp will be used regardless as webGL can - * only use REPEAT if the texture is po2. - * - * This property only affects WebGL. - * - * @static - * @constant - * @name WRAP_MODES - * @memberof PIXI - * @type {object} - * @property {number} CLAMP - The textures uvs are clamped - * @property {number} REPEAT - The texture uvs tile and repeat - * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring - */ -var WRAP_MODES = exports.WRAP_MODES = { - CLAMP: 0, - REPEAT: 1, - MIRRORED_REPEAT: 2 -}; - -/** - * The gc modes that are supported by pixi. - * - * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO - * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not - * used for a specified period of time they will be removed from the GPU. They will of course - * be uploaded again when they are required. This is a silent behind the scenes process that - * should ensure that the GPU does not get filled up. - * - * Handy for mobile devices! - * This property only affects WebGL. - * - * @static - * @constant - * @name GC_MODES - * @memberof PIXI - * @type {object} - * @property {number} AUTO - Garbage collection will happen periodically automatically - * @property {number} MANUAL - Garbage collection will need to be called manually - */ -var GC_MODES = exports.GC_MODES = { - AUTO: 0, - MANUAL: 1 -}; - -/** - * Regexp for image type by extension. - * - * @static - * @constant - * @memberof PIXI - * @type {RegExp|string} - * @example `image.png` - */ -var URL_FILE_EXTENSION = exports.URL_FILE_EXTENSION = /\.(\w{3,4})(?:$|\?|#)/i; - -/** - * Regexp for data URI. - * Based on: {@link https://github.com/ragingwind/data-uri-regex} - * - * @static - * @constant - * @name DATA_URI - * @memberof PIXI - * @type {RegExp|string} - * @example data:image/png;base64 - */ -var DATA_URI = exports.DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;(charset=[\w-]+|base64))?,(.*)/i; - -/** - * Regexp for SVG size. - * - * @static - * @constant - * @name SVG_SIZE - * @memberof PIXI - * @type {RegExp|string} - * @example <svg width="100" height="100"></svg> - */ -var SVG_SIZE = exports.SVG_SIZE = /]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len - -/** - * Constants that identify shapes, mainly to prevent `instanceof` calls. - * - * @static - * @constant - * @name SHAPES - * @memberof PIXI - * @type {object} - * @property {number} POLY Polygon - * @property {number} RECT Rectangle - * @property {number} CIRC Circle - * @property {number} ELIP Ellipse - * @property {number} RREC Rounded Rectangle - */ -var SHAPES = exports.SHAPES = { - POLY: 0, - RECT: 1, - CIRC: 2, - ELIP: 3, - RREC: 4 -}; - -/** - * Constants that specify float precision in shaders. - * - * @static - * @constant - * @name PRECISION - * @memberof PIXI - * @type {object} - * @property {string} LOW='lowp' - * @property {string} MEDIUM='mediump' - * @property {string} HIGH='highp' - */ -var PRECISION = exports.PRECISION = { - LOW: 'lowp', - MEDIUM: 'mediump', - HIGH: 'highp' -}; - -/** - * Constants that specify the transform type. - * - * @static - * @constant - * @name TRANSFORM_MODE - * @memberof PIXI - * @type {object} - * @property {number} STATIC - * @property {number} DYNAMIC - */ -var TRANSFORM_MODE = exports.TRANSFORM_MODE = { - STATIC: 0, - DYNAMIC: 1 -}; - -/** - * Constants that define the type of gradient on text. - * - * @static - * @constant - * @name TEXT_GRADIENT - * @memberof PIXI - * @type {object} - * @property {number} LINEAR_VERTICAL Vertical gradient - * @property {number} LINEAR_HORIZONTAL Linear gradient - */ -var TEXT_GRADIENT = exports.TEXT_GRADIENT = { - LINEAR_VERTICAL: 0, - LINEAR_HORIZONTAL: 1 -}; - -/** - * Represents the update priorities used by internal PIXI classes when registered with - * the {@link PIXI.ticker.Ticker} object. Higher priority items are updated first and lower - * priority items, such as render, should go later. - * - * @static - * @constant - * @name UPDATE_PRIORITY - * @memberof PIXI - * @type {object} - * @property {number} INTERACTION=50 Highest priority, used for {@link PIXI.interaction.InteractionManager} - * @property {number} HIGH=25 High priority updating, {@link PIXI.VideoBaseTexture} and {@link PIXI.extras.AnimatedSprite} - * @property {number} NORMAL=0 Default priority for ticker events, see {@link PIXI.ticker.Ticker#add}. - * @property {number} LOW=-25 Low priority used for {@link PIXI.Application} rendering. - * @property {number} UTILITY=-50 Lowest priority used for {@link PIXI.prepare.BasePrepare} utility. - */ -var UPDATE_PRIORITY = exports.UPDATE_PRIORITY = { - INTERACTION: 50, - HIGH: 25, - NORMAL: 0, - LOW: -25, - UTILITY: -50 -}; - -},{}],47:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _math = require('../math'); - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * 'Builder' pattern for bounds rectangles - * Axis-Aligned Bounding Box - * It is not a shape! Its mutable thing, no 'EMPTY' or that kind of problems - * - * @class - * @memberof PIXI - */ -var Bounds = function () { - /** - * - */ - function Bounds() { - _classCallCheck(this, Bounds); - - /** - * @member {number} - * @default 0 - */ - this.minX = Infinity; - - /** - * @member {number} - * @default 0 - */ - this.minY = Infinity; - - /** - * @member {number} - * @default 0 - */ - this.maxX = -Infinity; - - /** - * @member {number} - * @default 0 - */ - this.maxY = -Infinity; - - this.rect = null; - } - - /** - * Checks if bounds are empty. - * - * @return {boolean} True if empty. - */ - - - Bounds.prototype.isEmpty = function isEmpty() { - return this.minX > this.maxX || this.minY > this.maxY; - }; - - /** - * Clears the bounds and resets. - * - */ - - - Bounds.prototype.clear = function clear() { - this.updateID++; - - this.minX = Infinity; - this.minY = Infinity; - this.maxX = -Infinity; - this.maxY = -Infinity; - }; - - /** - * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle - * It is not guaranteed that it will return tempRect - * - * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty - * @returns {PIXI.Rectangle} A rectangle of the bounds - */ - - - Bounds.prototype.getRectangle = function getRectangle(rect) { - if (this.minX > this.maxX || this.minY > this.maxY) { - return _math.Rectangle.EMPTY; - } - - rect = rect || new _math.Rectangle(0, 0, 1, 1); - - rect.x = this.minX; - rect.y = this.minY; - rect.width = this.maxX - this.minX; - rect.height = this.maxY - this.minY; - - return rect; - }; - - /** - * This function should be inlined when its possible. - * - * @param {PIXI.Point} point - The point to add. - */ - - - Bounds.prototype.addPoint = function addPoint(point) { - this.minX = Math.min(this.minX, point.x); - this.maxX = Math.max(this.maxX, point.x); - this.minY = Math.min(this.minY, point.y); - this.maxY = Math.max(this.maxY, point.y); - }; - - /** - * Adds a quad, not transformed - * - * @param {Float32Array} vertices - The verts to add. - */ - - - Bounds.prototype.addQuad = function addQuad(vertices) { - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - - var x = vertices[0]; - var y = vertices[1]; - - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - - x = vertices[2]; - y = vertices[3]; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - - x = vertices[4]; - y = vertices[5]; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - - x = vertices[6]; - y = vertices[7]; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - - this.minX = minX; - this.minY = minY; - this.maxX = maxX; - this.maxY = maxY; - }; - - /** - * Adds sprite frame, transformed. - * - * @param {PIXI.TransformBase} transform - TODO - * @param {number} x0 - TODO - * @param {number} y0 - TODO - * @param {number} x1 - TODO - * @param {number} y1 - TODO - */ - - - Bounds.prototype.addFrame = function addFrame(transform, x0, y0, x1, y1) { - var matrix = transform.worldTransform; - var a = matrix.a; - var b = matrix.b; - var c = matrix.c; - var d = matrix.d; - var tx = matrix.tx; - var ty = matrix.ty; - - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - - var x = a * x0 + c * y0 + tx; - var y = b * x0 + d * y0 + ty; - - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - - x = a * x1 + c * y0 + tx; - y = b * x1 + d * y0 + ty; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - - x = a * x0 + c * y1 + tx; - y = b * x0 + d * y1 + ty; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - - x = a * x1 + c * y1 + tx; - y = b * x1 + d * y1 + ty; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - - this.minX = minX; - this.minY = minY; - this.maxX = maxX; - this.maxY = maxY; - }; - - /** - * Add an array of vertices - * - * @param {PIXI.TransformBase} transform - TODO - * @param {Float32Array} vertices - TODO - * @param {number} beginOffset - TODO - * @param {number} endOffset - TODO - */ - - - Bounds.prototype.addVertices = function addVertices(transform, vertices, beginOffset, endOffset) { - var matrix = transform.worldTransform; - var a = matrix.a; - var b = matrix.b; - var c = matrix.c; - var d = matrix.d; - var tx = matrix.tx; - var ty = matrix.ty; - - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - - for (var i = beginOffset; i < endOffset; i += 2) { - var rawX = vertices[i]; - var rawY = vertices[i + 1]; - var x = a * rawX + c * rawY + tx; - var y = d * rawY + b * rawX + ty; - - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - } - - this.minX = minX; - this.minY = minY; - this.maxX = maxX; - this.maxY = maxY; - }; - - /** - * Adds other Bounds - * - * @param {PIXI.Bounds} bounds - TODO - */ - - - Bounds.prototype.addBounds = function addBounds(bounds) { - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - - this.minX = bounds.minX < minX ? bounds.minX : minX; - this.minY = bounds.minY < minY ? bounds.minY : minY; - this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; - this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; - }; - - /** - * Adds other Bounds, masked with Bounds - * - * @param {PIXI.Bounds} bounds - TODO - * @param {PIXI.Bounds} mask - TODO - */ - - - Bounds.prototype.addBoundsMask = function addBoundsMask(bounds, mask) { - var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; - var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; - var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; - var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; - - if (_minX <= _maxX && _minY <= _maxY) { - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - - this.minX = _minX < minX ? _minX : minX; - this.minY = _minY < minY ? _minY : minY; - this.maxX = _maxX > maxX ? _maxX : maxX; - this.maxY = _maxY > maxY ? _maxY : maxY; - } - }; - - /** - * Adds other Bounds, masked with Rectangle - * - * @param {PIXI.Bounds} bounds - TODO - * @param {PIXI.Rectangle} area - TODO - */ - - - Bounds.prototype.addBoundsArea = function addBoundsArea(bounds, area) { - var _minX = bounds.minX > area.x ? bounds.minX : area.x; - var _minY = bounds.minY > area.y ? bounds.minY : area.y; - var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : area.x + area.width; - var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : area.y + area.height; - - if (_minX <= _maxX && _minY <= _maxY) { - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - - this.minX = _minX < minX ? _minX : minX; - this.minY = _minY < minY ? _minY : minY; - this.maxX = _maxX > maxX ? _maxX : maxX; - this.maxY = _maxY > maxY ? _maxY : maxY; - } - }; - - return Bounds; -}(); - -exports.default = Bounds; - -},{"../math":70}],48:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _utils = require('../utils'); - -var _DisplayObject2 = require('./DisplayObject'); - -var _DisplayObject3 = _interopRequireDefault(_DisplayObject2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * A Container represents a collection of display objects. - * It is the base class of all display objects that act as a container for other objects. - * - *```js - * let container = new PIXI.Container(); - * container.addChild(sprite); - * ``` - * - * @class - * @extends PIXI.DisplayObject - * @memberof PIXI - */ -var Container = function (_DisplayObject) { - _inherits(Container, _DisplayObject); - - /** - * - */ - function Container() { - _classCallCheck(this, Container); - - /** - * The array of children of this container. - * - * @member {PIXI.DisplayObject[]} - * @readonly - */ - var _this = _possibleConstructorReturn(this, _DisplayObject.call(this)); - - _this.children = []; - return _this; - } - - /** - * Overridable method that can be used by Container subclasses whenever the children array is modified - * - * @private - */ - - - Container.prototype.onChildrenChange = function onChildrenChange() {} - /* empty */ - - - /** - * Adds one or more children to the container. - * - * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` - * - * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to add to the container - * @return {PIXI.DisplayObject} The first child that was added. - */ - ; - - Container.prototype.addChild = function addChild(child) { - var argumentsLength = arguments.length; - - // if there is only one argument we can bypass looping through the them - if (argumentsLength > 1) { - // loop through the arguments property and add all children - // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes - for (var i = 0; i < argumentsLength; i++) { - this.addChild(arguments[i]); - } - } else { - // if the child has a parent then lets remove it as PixiJS objects can only exist in one place - if (child.parent) { - child.parent.removeChild(child); - } - - child.parent = this; - // ensure child transform will be recalculated - child.transform._parentID = -1; - - this.children.push(child); - - // ensure bounds will be recalculated - this._boundsID++; - - // TODO - lets either do all callbacks or all events.. not both! - this.onChildrenChange(this.children.length - 1); - child.emit('added', this); - } - - return child; - }; - - /** - * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown - * - * @param {PIXI.DisplayObject} child - The child to add - * @param {number} index - The index to place the child in - * @return {PIXI.DisplayObject} The child that was added. - */ - - - Container.prototype.addChildAt = function addChildAt(child, index) { - if (index < 0 || index > this.children.length) { - throw new Error(child + 'addChildAt: The index ' + index + ' supplied is out of bounds ' + this.children.length); - } - - if (child.parent) { - child.parent.removeChild(child); - } - - child.parent = this; - // ensure child transform will be recalculated - child.transform._parentID = -1; - - this.children.splice(index, 0, child); - - // ensure bounds will be recalculated - this._boundsID++; - - // TODO - lets either do all callbacks or all events.. not both! - this.onChildrenChange(index); - child.emit('added', this); - - return child; - }; - - /** - * Swaps the position of 2 Display Objects within this container. - * - * @param {PIXI.DisplayObject} child - First display object to swap - * @param {PIXI.DisplayObject} child2 - Second display object to swap - */ - - - Container.prototype.swapChildren = function swapChildren(child, child2) { - if (child === child2) { - return; - } - - var index1 = this.getChildIndex(child); - var index2 = this.getChildIndex(child2); - - this.children[index1] = child2; - this.children[index2] = child; - this.onChildrenChange(index1 < index2 ? index1 : index2); - }; - - /** - * Returns the index position of a child DisplayObject instance - * - * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify - * @return {number} The index position of the child display object to identify - */ - - - Container.prototype.getChildIndex = function getChildIndex(child) { - var index = this.children.indexOf(child); - - if (index === -1) { - throw new Error('The supplied DisplayObject must be a child of the caller'); - } - - return index; - }; - - /** - * Changes the position of an existing child in the display object container - * - * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number - * @param {number} index - The resulting index number for the child display object - */ - - - Container.prototype.setChildIndex = function setChildIndex(child, index) { - if (index < 0 || index >= this.children.length) { - throw new Error('The supplied index is out of bounds'); - } - - var currentIndex = this.getChildIndex(child); - - (0, _utils.removeItems)(this.children, currentIndex, 1); // remove from old position - this.children.splice(index, 0, child); // add at new position - - this.onChildrenChange(index); - }; - - /** - * Returns the child at the specified index - * - * @param {number} index - The index to get the child at - * @return {PIXI.DisplayObject} The child at the given index, if any. - */ - - - Container.prototype.getChildAt = function getChildAt(index) { - if (index < 0 || index >= this.children.length) { - throw new Error('getChildAt: Index (' + index + ') does not exist.'); - } - - return this.children[index]; - }; - - /** - * Removes one or more children from the container. - * - * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to remove - * @return {PIXI.DisplayObject} The first child that was removed. - */ - - - Container.prototype.removeChild = function removeChild(child) { - var argumentsLength = arguments.length; - - // if there is only one argument we can bypass looping through the them - if (argumentsLength > 1) { - // loop through the arguments property and add all children - // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes - for (var i = 0; i < argumentsLength; i++) { - this.removeChild(arguments[i]); - } - } else { - var index = this.children.indexOf(child); - - if (index === -1) return null; - - child.parent = null; - // ensure child transform will be recalculated - child.transform._parentID = -1; - (0, _utils.removeItems)(this.children, index, 1); - - // ensure bounds will be recalculated - this._boundsID++; - - // TODO - lets either do all callbacks or all events.. not both! - this.onChildrenChange(index); - child.emit('removed', this); - } - - return child; - }; - - /** - * Removes a child from the specified index position. - * - * @param {number} index - The index to get the child from - * @return {PIXI.DisplayObject} The child that was removed. - */ - - - Container.prototype.removeChildAt = function removeChildAt(index) { - var child = this.getChildAt(index); - - // ensure child transform will be recalculated.. - child.parent = null; - child.transform._parentID = -1; - (0, _utils.removeItems)(this.children, index, 1); - - // ensure bounds will be recalculated - this._boundsID++; - - // TODO - lets either do all callbacks or all events.. not both! - this.onChildrenChange(index); - child.emit('removed', this); - - return child; - }; - - /** - * Removes all children from this container that are within the begin and end indexes. - * - * @param {number} [beginIndex=0] - The beginning position. - * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container. - * @returns {DisplayObject[]} List of removed children - */ - - - Container.prototype.removeChildren = function removeChildren() { - var beginIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - var endIndex = arguments[1]; - - var begin = beginIndex; - var end = typeof endIndex === 'number' ? endIndex : this.children.length; - var range = end - begin; - var removed = void 0; - - if (range > 0 && range <= end) { - removed = this.children.splice(begin, range); - - for (var i = 0; i < removed.length; ++i) { - removed[i].parent = null; - if (removed[i].transform) { - removed[i].transform._parentID = -1; - } - } - - this._boundsID++; - - this.onChildrenChange(beginIndex); - - for (var _i = 0; _i < removed.length; ++_i) { - removed[_i].emit('removed', this); - } - - return removed; - } else if (range === 0 && this.children.length === 0) { - return []; - } - - throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); - }; - - /** - * Updates the transform on all children of this container for rendering - */ - - - Container.prototype.updateTransform = function updateTransform() { - this._boundsID++; - - this.transform.updateTransform(this.parent.transform); - - // TODO: check render flags, how to process stuff here - this.worldAlpha = this.alpha * this.parent.worldAlpha; - - for (var i = 0, j = this.children.length; i < j; ++i) { - var child = this.children[i]; - - if (child.visible) { - child.updateTransform(); - } - } - }; - - /** - * Recalculates the bounds of the container. - * - */ - - - Container.prototype.calculateBounds = function calculateBounds() { - this._bounds.clear(); - - this._calculateBounds(); - - for (var i = 0; i < this.children.length; i++) { - var child = this.children[i]; - - if (!child.visible || !child.renderable) { - continue; - } - - child.calculateBounds(); - - // TODO: filter+mask, need to mask both somehow - if (child._mask) { - child._mask.calculateBounds(); - this._bounds.addBoundsMask(child._bounds, child._mask._bounds); - } else if (child.filterArea) { - this._bounds.addBoundsArea(child._bounds, child.filterArea); - } else { - this._bounds.addBounds(child._bounds); - } - } - - this._lastBoundsID = this._boundsID; - }; - - /** - * Recalculates the bounds of the object. Override this to - * calculate the bounds of the specific object (not including children). - * - */ - - - Container.prototype._calculateBounds = function _calculateBounds() {} - // FILL IN// - - - /** - * Renders the object using the WebGL renderer - * - * @param {PIXI.WebGLRenderer} renderer - The renderer - */ - ; - - Container.prototype.renderWebGL = function renderWebGL(renderer) { - // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { - return; - } - - // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { - this.renderAdvancedWebGL(renderer); - } else { - this._renderWebGL(renderer); - - // simple render children! - for (var i = 0, j = this.children.length; i < j; ++i) { - this.children[i].renderWebGL(renderer); - } - } - }; - - /** - * Render the object using the WebGL renderer and advanced features. - * - * @private - * @param {PIXI.WebGLRenderer} renderer - The renderer - */ - - - Container.prototype.renderAdvancedWebGL = function renderAdvancedWebGL(renderer) { - renderer.flush(); - - var filters = this._filters; - var mask = this._mask; - - // push filter first as we need to ensure the stencil buffer is correct for any masking - if (filters) { - if (!this._enabledFilters) { - this._enabledFilters = []; - } - - this._enabledFilters.length = 0; - - for (var i = 0; i < filters.length; i++) { - if (filters[i].enabled) { - this._enabledFilters.push(filters[i]); - } - } - - if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); - } - } - - if (mask) { - renderer.maskManager.pushMask(this, this._mask); - } - - // add this object to the batch, only rendered if it has a texture. - this._renderWebGL(renderer); - - // now loop through the children and make sure they get rendered - for (var _i2 = 0, j = this.children.length; _i2 < j; _i2++) { - this.children[_i2].renderWebGL(renderer); - } - - renderer.flush(); - - if (mask) { - renderer.maskManager.popMask(this, this._mask); - } - - if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); - } - }; - - /** - * To be overridden by the subclasses. - * - * @private - * @param {PIXI.WebGLRenderer} renderer - The renderer - */ - - - Container.prototype._renderWebGL = function _renderWebGL(renderer) // eslint-disable-line no-unused-vars - {} - // this is where content itself gets rendered... - - - /** - * To be overridden by the subclass - * - * @private - * @param {PIXI.CanvasRenderer} renderer - The renderer - */ - ; - - Container.prototype._renderCanvas = function _renderCanvas(renderer) // eslint-disable-line no-unused-vars - {} - // this is where content itself gets rendered... - - - /** - * Renders the object using the Canvas renderer - * - * @param {PIXI.CanvasRenderer} renderer - The renderer - */ - ; - - Container.prototype.renderCanvas = function renderCanvas(renderer) { - // if not visible or the alpha is 0 then no need to render this - if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { - return; - } - - if (this._mask) { - renderer.maskManager.pushMask(this._mask); - } - - this._renderCanvas(renderer); - for (var i = 0, j = this.children.length; i < j; ++i) { - this.children[i].renderCanvas(renderer); - } - - if (this._mask) { - renderer.maskManager.popMask(renderer); - } - }; - - /** - * Removes all internal references and listeners as well as removes children from the display list. - * Do not use a Container after calling `destroy`. - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy - * method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the texture of the child sprite - * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the base texture of the child sprite - */ - - - Container.prototype.destroy = function destroy(options) { - _DisplayObject.prototype.destroy.call(this); - - var destroyChildren = typeof options === 'boolean' ? options : options && options.children; - - var oldChildren = this.removeChildren(0, this.children.length); - - if (destroyChildren) { - for (var i = 0; i < oldChildren.length; ++i) { - oldChildren[i].destroy(options); - } - } - }; - - /** - * The width of the Container, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - - - _createClass(Container, [{ - key: 'width', - get: function get() { - return this.scale.x * this.getLocalBounds().width; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - var width = this.getLocalBounds().width; - - if (width !== 0) { - this.scale.x = value / width; - } else { - this.scale.x = 1; - } - - this._width = value; - } - - /** - * The height of the Container, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - - }, { - key: 'height', - get: function get() { - return this.scale.y * this.getLocalBounds().height; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - var height = this.getLocalBounds().height; - - if (height !== 0) { - this.scale.y = value / height; - } else { - this.scale.y = 1; - } - - this._height = value; - } - }]); - - return Container; -}(_DisplayObject3.default); - -// performance increase to avoid using call.. (10x faster) - - -exports.default = Container; -Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; - -},{"../utils":124,"./DisplayObject":49}],49:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _eventemitter = require('eventemitter3'); - -var _eventemitter2 = _interopRequireDefault(_eventemitter); - -var _const = require('../const'); - -var _settings = require('../settings'); - -var _settings2 = _interopRequireDefault(_settings); - -var _TransformStatic = require('./TransformStatic'); - -var _TransformStatic2 = _interopRequireDefault(_TransformStatic); - -var _Transform = require('./Transform'); - -var _Transform2 = _interopRequireDefault(_Transform); - -var _Bounds = require('./Bounds'); - -var _Bounds2 = _interopRequireDefault(_Bounds); - -var _math = require('../math'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -// _tempDisplayObjectParent = new DisplayObject(); - -/** - * The base class for all objects that are rendered on the screen. - * This is an abstract class and should not be used on its own rather it should be extended. - * - * @class - * @extends EventEmitter - * @memberof PIXI - */ -var DisplayObject = function (_EventEmitter) { - _inherits(DisplayObject, _EventEmitter); - - /** - * - */ - function DisplayObject() { - _classCallCheck(this, DisplayObject); - - var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); - - var TransformClass = _settings2.default.TRANSFORM_MODE === _const.TRANSFORM_MODE.STATIC ? _TransformStatic2.default : _Transform2.default; - - _this.tempDisplayObjectParent = null; - - // TODO: need to create Transform from factory - /** - * World transform and local transform of this object. - * This will become read-only later, please do not assign anything there unless you know what are you doing - * - * @member {PIXI.TransformBase} - */ - _this.transform = new TransformClass(); - - /** - * The opacity of the object. - * - * @member {number} - */ - _this.alpha = 1; - - /** - * The visibility of the object. If false the object will not be drawn, and - * the updateTransform function will not be called. - * - * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually - * - * @member {boolean} - */ - _this.visible = true; - - /** - * Can this object be rendered, if false the object will not be drawn but the updateTransform - * methods will still be called. - * - * Only affects recursive calls from parent. You can ask for bounds manually - * - * @member {boolean} - */ - _this.renderable = true; - - /** - * The display object container that contains this display object. - * - * @member {PIXI.Container} - * @readonly - */ - _this.parent = null; - - /** - * The multiplied alpha of the displayObject - * - * @member {number} - * @readonly - */ - _this.worldAlpha = 1; - - /** - * The area the filter is applied to. This is used as more of an optimisation - * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle - * - * Also works as an interaction mask - * - * @member {PIXI.Rectangle} - */ - _this.filterArea = null; - - _this._filters = null; - _this._enabledFilters = null; - - /** - * The bounds object, this is used to calculate and store the bounds of the displayObject - * - * @member {PIXI.Rectangle} - * @private - */ - _this._bounds = new _Bounds2.default(); - _this._boundsID = 0; - _this._lastBoundsID = -1; - _this._boundsRect = null; - _this._localBoundsRect = null; - - /** - * The original, cached mask of the object - * - * @member {PIXI.Graphics|PIXI.Sprite} - * @private - */ - _this._mask = null; - - /** - * If the object has been destroyed via destroy(). If true, it should not be used. - * - * @member {boolean} - * @private - * @readonly - */ - _this._destroyed = false; - - /** - * Fired when this DisplayObject is added to a Container. - * - * @event PIXI.DisplayObject#added - * @param {PIXI.Container} container - The container added to. - */ - - /** - * Fired when this DisplayObject is removed from a Container. - * - * @event PIXI.DisplayObject#removed - * @param {PIXI.Container} container - The container removed from. - */ - return _this; - } - - /** - * @private - * @member {PIXI.DisplayObject} - */ - - - /** - * Updates the object transform for rendering - * - * TODO - Optimization pass! - */ - DisplayObject.prototype.updateTransform = function updateTransform() { - this.transform.updateTransform(this.parent.transform); - // multiply the alphas.. - this.worldAlpha = this.alpha * this.parent.worldAlpha; - - this._bounds.updateID++; - }; - - /** - * recursively updates transform of all objects from the root to this one - * internal function for toLocal() - */ - - - DisplayObject.prototype._recursivePostUpdateTransform = function _recursivePostUpdateTransform() { - if (this.parent) { - this.parent._recursivePostUpdateTransform(); - this.transform.updateTransform(this.parent.transform); - } else { - this.transform.updateTransform(this._tempDisplayObjectParent.transform); - } - }; - - /** - * Retrieves the bounds of the displayObject as a rectangle object. - * - * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from - * being updated. This means the calculation returned MAY be out of date BUT will give you a - * nice performance boost - * @param {PIXI.Rectangle} rect - Optional rectangle to store the result of the bounds calculation - * @return {PIXI.Rectangle} the rectangular bounding area - */ - - - DisplayObject.prototype.getBounds = function getBounds(skipUpdate, rect) { - if (!skipUpdate) { - if (!this.parent) { - this.parent = this._tempDisplayObjectParent; - this.updateTransform(); - this.parent = null; - } else { - this._recursivePostUpdateTransform(); - this.updateTransform(); - } - } - - if (this._boundsID !== this._lastBoundsID) { - this.calculateBounds(); - } - - if (!rect) { - if (!this._boundsRect) { - this._boundsRect = new _math.Rectangle(); - } - - rect = this._boundsRect; - } - - return this._bounds.getRectangle(rect); - }; - - /** - * Retrieves the local bounds of the displayObject as a rectangle object - * - * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation - * @return {PIXI.Rectangle} the rectangular bounding area - */ - - - DisplayObject.prototype.getLocalBounds = function getLocalBounds(rect) { - var transformRef = this.transform; - var parentRef = this.parent; - - this.parent = null; - this.transform = this._tempDisplayObjectParent.transform; - - if (!rect) { - if (!this._localBoundsRect) { - this._localBoundsRect = new _math.Rectangle(); - } - - rect = this._localBoundsRect; - } - - var bounds = this.getBounds(false, rect); - - this.parent = parentRef; - this.transform = transformRef; - - return bounds; - }; - - /** - * Calculates the global position of the display object - * - * @param {PIXI.Point} position - The world origin to calculate from - * @param {PIXI.Point} [point] - A Point object in which to store the value, optional - * (otherwise will create a new Point) - * @param {boolean} [skipUpdate=false] - Should we skip the update transform. - * @return {PIXI.Point} A point object representing the position of this object - */ - - - DisplayObject.prototype.toGlobal = function toGlobal(position, point) { - var skipUpdate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - - if (!skipUpdate) { - this._recursivePostUpdateTransform(); - - // this parent check is for just in case the item is a root object. - // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly - // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) - if (!this.parent) { - this.parent = this._tempDisplayObjectParent; - this.displayObjectUpdateTransform(); - this.parent = null; - } else { - this.displayObjectUpdateTransform(); - } - } - - // don't need to update the lot - return this.worldTransform.apply(position, point); - }; - - /** - * Calculates the local position of the display object relative to another point - * - * @param {PIXI.Point} position - The world origin to calculate from - * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from - * @param {PIXI.Point} [point] - A Point object in which to store the value, optional - * (otherwise will create a new Point) - * @param {boolean} [skipUpdate=false] - Should we skip the update transform - * @return {PIXI.Point} A point object representing the position of this object - */ - - - DisplayObject.prototype.toLocal = function toLocal(position, from, point, skipUpdate) { - if (from) { - position = from.toGlobal(position, point, skipUpdate); - } - - if (!skipUpdate) { - this._recursivePostUpdateTransform(); - - // this parent check is for just in case the item is a root object. - // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly - // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) - if (!this.parent) { - this.parent = this._tempDisplayObjectParent; - this.displayObjectUpdateTransform(); - this.parent = null; - } else { - this.displayObjectUpdateTransform(); - } - } - - // simply apply the matrix.. - return this.worldTransform.applyInverse(position, point); - }; - - /** - * Renders the object using the WebGL renderer - * - * @param {PIXI.WebGLRenderer} renderer - The renderer - */ - - - DisplayObject.prototype.renderWebGL = function renderWebGL(renderer) // eslint-disable-line no-unused-vars - {} - // OVERWRITE; - - - /** - * Renders the object using the Canvas renderer - * - * @param {PIXI.CanvasRenderer} renderer - The renderer - */ - ; - - DisplayObject.prototype.renderCanvas = function renderCanvas(renderer) // eslint-disable-line no-unused-vars - {} - // OVERWRITE; - - - /** - * Set the parent Container of this DisplayObject - * - * @param {PIXI.Container} container - The Container to add this DisplayObject to - * @return {PIXI.Container} The Container that this DisplayObject was added to - */ - ; - - DisplayObject.prototype.setParent = function setParent(container) { - if (!container || !container.addChild) { - throw new Error('setParent: Argument must be a Container'); - } - - container.addChild(this); - - return container; - }; - - /** - * Convenience function to set the position, scale, skew and pivot at once. - * - * @param {number} [x=0] - The X position - * @param {number} [y=0] - The Y position - * @param {number} [scaleX=1] - The X scale value - * @param {number} [scaleY=1] - The Y scale value - * @param {number} [rotation=0] - The rotation - * @param {number} [skewX=0] - The X skew value - * @param {number} [skewY=0] - The Y skew value - * @param {number} [pivotX=0] - The X pivot value - * @param {number} [pivotY=0] - The Y pivot value - * @return {PIXI.DisplayObject} The DisplayObject instance - */ - - - DisplayObject.prototype.setTransform = function setTransform() { - var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - var scaleX = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; - var scaleY = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; - var rotation = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; - var skewX = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; - var skewY = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; - var pivotX = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0; - var pivotY = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0; - - this.position.x = x; - this.position.y = y; - this.scale.x = !scaleX ? 1 : scaleX; - this.scale.y = !scaleY ? 1 : scaleY; - this.rotation = rotation; - this.skew.x = skewX; - this.skew.y = skewY; - this.pivot.x = pivotX; - this.pivot.y = pivotY; - - return this; - }; - - /** - * Base destroy method for generic display objects. This will automatically - * remove the display object from its parent Container as well as remove - * all current event listeners and internal references. Do not use a DisplayObject - * after calling `destroy`. - * - */ - - - DisplayObject.prototype.destroy = function destroy() { - this.removeAllListeners(); - if (this.parent) { - this.parent.removeChild(this); - } - this.transform = null; - - this.parent = null; - - this._bounds = null; - this._currentBounds = null; - this._mask = null; - - this.filterArea = null; - - this.interactive = false; - this.interactiveChildren = false; - - this._destroyed = true; - }; - - /** - * The position of the displayObject on the x axis relative to the local coordinates of the parent. - * An alias to position.x - * - * @member {number} - */ - - - _createClass(DisplayObject, [{ - key: '_tempDisplayObjectParent', - get: function get() { - if (this.tempDisplayObjectParent === null) { - this.tempDisplayObjectParent = new DisplayObject(); - } - - return this.tempDisplayObjectParent; - } - }, { - key: 'x', - get: function get() { - return this.position.x; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.transform.position.x = value; - } - - /** - * The position of the displayObject on the y axis relative to the local coordinates of the parent. - * An alias to position.y - * - * @member {number} - */ - - }, { - key: 'y', - get: function get() { - return this.position.y; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.transform.position.y = value; - } - - /** - * Current transform of the object based on world (parent) factors - * - * @member {PIXI.Matrix} - * @readonly - */ - - }, { - key: 'worldTransform', - get: function get() { - return this.transform.worldTransform; - } - - /** - * Current transform of the object based on local factors: position, scale, other stuff - * - * @member {PIXI.Matrix} - * @readonly - */ - - }, { - key: 'localTransform', - get: function get() { - return this.transform.localTransform; - } - - /** - * The coordinate of the object relative to the local coordinates of the parent. - * Assignment by value since pixi-v4. - * - * @member {PIXI.Point|PIXI.ObservablePoint} - */ - - }, { - key: 'position', - get: function get() { - return this.transform.position; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.transform.position.copy(value); - } - - /** - * The scale factor of the object. - * Assignment by value since pixi-v4. - * - * @member {PIXI.Point|PIXI.ObservablePoint} - */ - - }, { - key: 'scale', - get: function get() { - return this.transform.scale; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.transform.scale.copy(value); - } - - /** - * The pivot point of the displayObject that it rotates around - * Assignment by value since pixi-v4. - * - * @member {PIXI.Point|PIXI.ObservablePoint} - */ - - }, { - key: 'pivot', - get: function get() { - return this.transform.pivot; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.transform.pivot.copy(value); - } - - /** - * The skew factor for the object in radians. - * Assignment by value since pixi-v4. - * - * @member {PIXI.ObservablePoint} - */ - - }, { - key: 'skew', - get: function get() { - return this.transform.skew; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.transform.skew.copy(value); - } - - /** - * The rotation of the object in radians. - * - * @member {number} - */ - - }, { - key: 'rotation', - get: function get() { - return this.transform.rotation; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.transform.rotation = value; - } - - /** - * Indicates if the object is globally visible. - * - * @member {boolean} - * @readonly - */ - - }, { - key: 'worldVisible', - get: function get() { - var item = this; - - do { - if (!item.visible) { - return false; - } - - item = item.parent; - } while (item); - - return true; - } - - /** - * Sets a mask for the displayObject. A mask is an object that limits the visibility of an - * object to the shape of the mask applied to it. In PIXI a regular mask must be a - * PIXI.Graphics or a PIXI.Sprite object. This allows for much faster masking in canvas as it - * utilises shape clipping. To remove a mask, set this property to null. - * - * @todo For the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. - * - * @member {PIXI.Graphics|PIXI.Sprite} - */ - - }, { - key: 'mask', - get: function get() { - return this._mask; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - if (this._mask) { - this._mask.renderable = true; - } - - this._mask = value; - - if (this._mask) { - this._mask.renderable = false; - } - } - - /** - * Sets the filters for the displayObject. - * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. - * To remove filters simply set this property to 'null' - * - * @member {PIXI.Filter[]} - */ - - }, { - key: 'filters', - get: function get() { - return this._filters && this._filters.slice(); - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._filters = value && value.slice(); - } - }]); - - return DisplayObject; -}(_eventemitter2.default); - -// performance increase to avoid using call.. (10x faster) - - -exports.default = DisplayObject; -DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; - -},{"../const":46,"../math":70,"../settings":101,"./Bounds":47,"./Transform":50,"./TransformStatic":52,"eventemitter3":3}],50:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _math = require('../math'); - -var _TransformBase2 = require('./TransformBase'); - -var _TransformBase3 = _interopRequireDefault(_TransformBase2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * Generic class to deal with traditional 2D matrix transforms - * local transformation is calculated from position,scale,skew and rotation - * - * @class - * @extends PIXI.TransformBase - * @memberof PIXI - */ -var Transform = function (_TransformBase) { - _inherits(Transform, _TransformBase); - - /** - * - */ - function Transform() { - _classCallCheck(this, Transform); - - /** - * The coordinate of the object relative to the local coordinates of the parent. - * - * @member {PIXI.Point} - */ - var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); - - _this.position = new _math.Point(0, 0); - - /** - * The scale factor of the object. - * - * @member {PIXI.Point} - */ - _this.scale = new _math.Point(1, 1); - - /** - * The skew amount, on the x and y axis. - * - * @member {PIXI.ObservablePoint} - */ - _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); - - /** - * The pivot point of the displayObject that it rotates around - * - * @member {PIXI.Point} - */ - _this.pivot = new _math.Point(0, 0); - - /** - * The rotation value of the object, in radians - * - * @member {Number} - * @private - */ - _this._rotation = 0; - - _this._cx = 1; // cos rotation + skewY; - _this._sx = 0; // sin rotation + skewY; - _this._cy = 0; // cos rotation + Math.PI/2 - skewX; - _this._sy = 1; // sin rotation + Math.PI/2 - skewX; - return _this; - } - - /** - * Updates the skew values when the skew or rotation changes. - * - * @private - */ - - - Transform.prototype.updateSkew = function updateSkew() { - this._cx = Math.cos(this._rotation + this.skew._y); - this._sx = Math.sin(this._rotation + this.skew._y); - this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 - this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 - }; - - /** - * Updates only local matrix - */ - - - Transform.prototype.updateLocalTransform = function updateLocalTransform() { - var lt = this.localTransform; - - lt.a = this._cx * this.scale.x; - lt.b = this._sx * this.scale.x; - lt.c = this._cy * this.scale.y; - lt.d = this._sy * this.scale.y; - - lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); - lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); - }; - - /** - * Updates the values of the object and applies the parent's transform. - * - * @param {PIXI.Transform} parentTransform - The transform of the parent of this object - */ - - - Transform.prototype.updateTransform = function updateTransform(parentTransform) { - var lt = this.localTransform; - - lt.a = this._cx * this.scale.x; - lt.b = this._sx * this.scale.x; - lt.c = this._cy * this.scale.y; - lt.d = this._sy * this.scale.y; - - lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); - lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); - - // concat the parent matrix with the objects transform. - var pt = parentTransform.worldTransform; - var wt = this.worldTransform; - - wt.a = lt.a * pt.a + lt.b * pt.c; - wt.b = lt.a * pt.b + lt.b * pt.d; - wt.c = lt.c * pt.a + lt.d * pt.c; - wt.d = lt.c * pt.b + lt.d * pt.d; - wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; - wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; - - this._worldID++; - }; - - /** - * Decomposes a matrix and sets the transforms properties based on it. - * - * @param {PIXI.Matrix} matrix - The matrix to decompose - */ - - - Transform.prototype.setFromMatrix = function setFromMatrix(matrix) { - matrix.decompose(this); - }; - - /** - * The rotation of the object in radians. - * - * @member {number} - */ - - - _createClass(Transform, [{ - key: 'rotation', - get: function get() { - return this._rotation; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._rotation = value; - this.updateSkew(); - } - }]); - - return Transform; -}(_TransformBase3.default); - -exports.default = Transform; - -},{"../math":70,"./TransformBase":51}],51:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _math = require('../math'); - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * Generic class to deal with traditional 2D matrix transforms - * - * @class - * @memberof PIXI - */ -var TransformBase = function () { - /** - * - */ - function TransformBase() { - _classCallCheck(this, TransformBase); - - /** - * The global matrix transform. It can be swapped temporarily by some functions like getLocalBounds() - * - * @member {PIXI.Matrix} - */ - this.worldTransform = new _math.Matrix(); - - /** - * The local matrix transform - * - * @member {PIXI.Matrix} - */ - this.localTransform = new _math.Matrix(); - - this._worldID = 0; - this._parentID = 0; - } - - /** - * TransformBase does not have decomposition, so this function wont do anything - */ - - - TransformBase.prototype.updateLocalTransform = function updateLocalTransform() {} - // empty - - - /** - * Updates the values of the object and applies the parent's transform. - * - * @param {PIXI.TransformBase} parentTransform - The transform of the parent of this object - */ - ; - - TransformBase.prototype.updateTransform = function updateTransform(parentTransform) { - var pt = parentTransform.worldTransform; - var wt = this.worldTransform; - var lt = this.localTransform; - - // concat the parent matrix with the objects transform. - wt.a = lt.a * pt.a + lt.b * pt.c; - wt.b = lt.a * pt.b + lt.b * pt.d; - wt.c = lt.c * pt.a + lt.d * pt.c; - wt.d = lt.c * pt.b + lt.d * pt.d; - wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; - wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; - - this._worldID++; - }; - - return TransformBase; -}(); - -/** - * Updates the values of the object and applies the parent's transform. - * @param parentTransform {PIXI.Transform} The transform of the parent of this object - * - */ - - -exports.default = TransformBase; -TransformBase.prototype.updateWorldTransform = TransformBase.prototype.updateTransform; - -TransformBase.IDENTITY = new TransformBase(); - -},{"../math":70}],52:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _math = require('../math'); - -var _TransformBase2 = require('./TransformBase'); - -var _TransformBase3 = _interopRequireDefault(_TransformBase2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * Transform that takes care about its versions - * - * @class - * @extends PIXI.TransformBase - * @memberof PIXI - */ -var TransformStatic = function (_TransformBase) { - _inherits(TransformStatic, _TransformBase); - - /** - * - */ - function TransformStatic() { - _classCallCheck(this, TransformStatic); - - /** - * The coordinate of the object relative to the local coordinates of the parent. - * - * @member {PIXI.ObservablePoint} - */ - var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); - - _this.position = new _math.ObservablePoint(_this.onChange, _this, 0, 0); - - /** - * The scale factor of the object. - * - * @member {PIXI.ObservablePoint} - */ - _this.scale = new _math.ObservablePoint(_this.onChange, _this, 1, 1); - - /** - * The pivot point of the displayObject that it rotates around - * - * @member {PIXI.ObservablePoint} - */ - _this.pivot = new _math.ObservablePoint(_this.onChange, _this, 0, 0); - - /** - * The skew amount, on the x and y axis. - * - * @member {PIXI.ObservablePoint} - */ - _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); - - _this._rotation = 0; - - _this._cx = 1; // cos rotation + skewY; - _this._sx = 0; // sin rotation + skewY; - _this._cy = 0; // cos rotation + Math.PI/2 - skewX; - _this._sy = 1; // sin rotation + Math.PI/2 - skewX; - - _this._localID = 0; - _this._currentLocalID = 0; - return _this; - } - - /** - * Called when a value changes. - * - * @private - */ - - - TransformStatic.prototype.onChange = function onChange() { - this._localID++; - }; - - /** - * Called when skew or rotation changes - * - * @private - */ - - - TransformStatic.prototype.updateSkew = function updateSkew() { - this._cx = Math.cos(this._rotation + this.skew._y); - this._sx = Math.sin(this._rotation + this.skew._y); - this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 - this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 - - this._localID++; - }; - - /** - * Updates only local matrix - */ - - - TransformStatic.prototype.updateLocalTransform = function updateLocalTransform() { - var lt = this.localTransform; - - if (this._localID !== this._currentLocalID) { - // get the matrix values of the displayobject based on its transform properties.. - lt.a = this._cx * this.scale._x; - lt.b = this._sx * this.scale._x; - lt.c = this._cy * this.scale._y; - lt.d = this._sy * this.scale._y; - - lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); - lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); - this._currentLocalID = this._localID; - - // force an update.. - this._parentID = -1; - } - }; - - /** - * Updates the values of the object and applies the parent's transform. - * - * @param {PIXI.Transform} parentTransform - The transform of the parent of this object - */ - - - TransformStatic.prototype.updateTransform = function updateTransform(parentTransform) { - var lt = this.localTransform; - - if (this._localID !== this._currentLocalID) { - // get the matrix values of the displayobject based on its transform properties.. - lt.a = this._cx * this.scale._x; - lt.b = this._sx * this.scale._x; - lt.c = this._cy * this.scale._y; - lt.d = this._sy * this.scale._y; - - lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); - lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); - this._currentLocalID = this._localID; - - // force an update.. - this._parentID = -1; - } - - if (this._parentID !== parentTransform._worldID) { - // concat the parent matrix with the objects transform. - var pt = parentTransform.worldTransform; - var wt = this.worldTransform; - - wt.a = lt.a * pt.a + lt.b * pt.c; - wt.b = lt.a * pt.b + lt.b * pt.d; - wt.c = lt.c * pt.a + lt.d * pt.c; - wt.d = lt.c * pt.b + lt.d * pt.d; - wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; - wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; - - this._parentID = parentTransform._worldID; - - // update the id of the transform.. - this._worldID++; - } - }; - - /** - * Decomposes a matrix and sets the transforms properties based on it. - * - * @param {PIXI.Matrix} matrix - The matrix to decompose - */ - - - TransformStatic.prototype.setFromMatrix = function setFromMatrix(matrix) { - matrix.decompose(this); - this._localID++; - }; - - /** - * The rotation of the object in radians. - * - * @member {number} - */ - - - _createClass(TransformStatic, [{ - key: 'rotation', - get: function get() { - return this._rotation; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._rotation = value; - this.updateSkew(); - } - }]); - - return TransformStatic; -}(_TransformBase3.default); - -exports.default = TransformStatic; - -},{"../math":70,"./TransformBase":51}],53:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _Container2 = require('../display/Container'); - -var _Container3 = _interopRequireDefault(_Container2); - -var _RenderTexture = require('../textures/RenderTexture'); - -var _RenderTexture2 = _interopRequireDefault(_RenderTexture); - -var _Texture = require('../textures/Texture'); - -var _Texture2 = _interopRequireDefault(_Texture); - -var _GraphicsData = require('./GraphicsData'); - -var _GraphicsData2 = _interopRequireDefault(_GraphicsData); - -var _Sprite = require('../sprites/Sprite'); - -var _Sprite2 = _interopRequireDefault(_Sprite); - -var _math = require('../math'); - -var _utils = require('../utils'); - -var _const = require('../const'); - -var _Bounds = require('../display/Bounds'); - -var _Bounds2 = _interopRequireDefault(_Bounds); - -var _bezierCurveTo2 = require('./utils/bezierCurveTo'); - -var _bezierCurveTo3 = _interopRequireDefault(_bezierCurveTo2); - -var _CanvasRenderer = require('../renderers/canvas/CanvasRenderer'); - -var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -var canvasRenderer = void 0; -var tempMatrix = new _math.Matrix(); -var tempPoint = new _math.Point(); -var tempColor1 = new Float32Array(4); -var tempColor2 = new Float32Array(4); - -/** - * The Graphics class contains methods used to draw primitive shapes such as lines, circles and - * rectangles to the display, and to color and fill them. - * - * @class - * @extends PIXI.Container - * @memberof PIXI - */ - -var Graphics = function (_Container) { - _inherits(Graphics, _Container); - - /** - * - * @param {boolean} [nativeLines=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP - */ - function Graphics() { - var nativeLines = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - - _classCallCheck(this, Graphics); - - /** - * The alpha value used when filling the Graphics object. - * - * @member {number} - * @default 1 - */ - var _this = _possibleConstructorReturn(this, _Container.call(this)); - - _this.fillAlpha = 1; - - /** - * The width (thickness) of any lines drawn. - * - * @member {number} - * @default 0 - */ - _this.lineWidth = 0; - - /** - * If true the lines will be draw using LINES instead of TRIANGLE_STRIP - * - * @member {boolean} - */ - _this.nativeLines = nativeLines; - - /** - * The color of any lines drawn. - * - * @member {string} - * @default 0 - */ - _this.lineColor = 0; - - /** - * Graphics data - * - * @member {PIXI.GraphicsData[]} - * @private - */ - _this.graphicsData = []; - - /** - * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to - * reset the tint. - * - * @member {number} - * @default 0xFFFFFF - */ - _this.tint = 0xFFFFFF; - - /** - * The previous tint applied to the graphic shape. Used to compare to the current tint and - * check if theres change. - * - * @member {number} - * @private - * @default 0xFFFFFF - */ - _this._prevTint = 0xFFFFFF; - - /** - * The blend mode to be applied to the graphic shape. Apply a value of - * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. - * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL; - * @see PIXI.BLEND_MODES - */ - _this.blendMode = _const.BLEND_MODES.NORMAL; - - /** - * Current path - * - * @member {PIXI.GraphicsData} - * @private - */ - _this.currentPath = null; - - /** - * Array containing some WebGL-related properties used by the WebGL renderer. - * - * @member {object} - * @private - */ - // TODO - _webgl should use a prototype object, not a random undocumented object... - _this._webGL = {}; - - /** - * Whether this shape is being used as a mask. - * - * @member {boolean} - */ - _this.isMask = false; - - /** - * The bounds' padding used for bounds calculation. - * - * @member {number} - */ - _this.boundsPadding = 0; - - /** - * A cache of the local bounds to prevent recalculation. - * - * @member {PIXI.Rectangle} - * @private - */ - _this._localBounds = new _Bounds2.default(); - - /** - * Used to detect if the graphics object has changed. If this is set to true then the graphics - * object will be recalculated. - * - * @member {boolean} - * @private - */ - _this.dirty = 0; - - /** - * Used to detect if we need to do a fast rect check using the id compare method - * @type {Number} - */ - _this.fastRectDirty = -1; - - /** - * Used to detect if we clear the graphics webGL data - * @type {Number} - */ - _this.clearDirty = 0; - - /** - * Used to detect if we we need to recalculate local bounds - * @type {Number} - */ - _this.boundsDirty = -1; - - /** - * Used to detect if the cached sprite object needs to be updated. - * - * @member {boolean} - * @private - */ - _this.cachedSpriteDirty = false; - - _this._spriteRect = null; - _this._fastRect = false; - - /** - * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. - * This is useful if your graphics element does not change often, as it will speed up the rendering - * of the object in exchange for taking up texture memory. It is also useful if you need the graphics - * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if - * you are constantly redrawing the graphics element. - * - * @name cacheAsBitmap - * @member {boolean} - * @memberof PIXI.Graphics# - * @default false - */ - return _this; - } - - /** - * Creates a new Graphics object with the same values as this one. - * Note that the only the properties of the object are cloned, not its transform (position,scale,etc) - * - * @return {PIXI.Graphics} A clone of the graphics object - */ - - - Graphics.prototype.clone = function clone() { - var clone = new Graphics(); - - clone.renderable = this.renderable; - clone.fillAlpha = this.fillAlpha; - clone.lineWidth = this.lineWidth; - clone.lineColor = this.lineColor; - clone.tint = this.tint; - clone.blendMode = this.blendMode; - clone.isMask = this.isMask; - clone.boundsPadding = this.boundsPadding; - clone.dirty = 0; - clone.cachedSpriteDirty = this.cachedSpriteDirty; - - // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { - clone.graphicsData.push(this.graphicsData[i].clone()); - } - - clone.currentPath = clone.graphicsData[clone.graphicsData.length - 1]; - - clone.updateLocalBounds(); - - return clone; - }; - - /** - * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() - * method or the drawCircle() method. - * - * @param {number} [lineWidth=0] - width of the line to draw, will update the objects stored style - * @param {number} [color=0] - color of the line to draw, will update the objects stored style - * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - - - Graphics.prototype.lineStyle = function lineStyle() { - var lineWidth = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - var color = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - var alpha = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; - - this.lineWidth = lineWidth; - this.lineColor = color; - this.lineAlpha = alpha; - - if (this.currentPath) { - if (this.currentPath.shape.points.length) { - // halfway through a line? start a new one! - var shape = new _math.Polygon(this.currentPath.shape.points.slice(-2)); - - shape.closed = false; - - this.drawShape(shape); - } else { - // otherwise its empty so lets just set the line properties - this.currentPath.lineWidth = this.lineWidth; - this.currentPath.lineColor = this.lineColor; - this.currentPath.lineAlpha = this.lineAlpha; - } - } - - return this; - }; - - /** - * Moves the current drawing position to x, y. - * - * @param {number} x - the X coordinate to move to - * @param {number} y - the Y coordinate to move to - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - - - Graphics.prototype.moveTo = function moveTo(x, y) { - var shape = new _math.Polygon([x, y]); - - shape.closed = false; - this.drawShape(shape); - - return this; - }; - - /** - * Draws a line using the current line style from the current drawing position to (x, y); - * The current drawing position is then set to (x, y). - * - * @param {number} x - the X coordinate to draw to - * @param {number} y - the Y coordinate to draw to - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - - - Graphics.prototype.lineTo = function lineTo(x, y) { - this.currentPath.shape.points.push(x, y); - this.dirty++; - - return this; - }; - - /** - * Calculate the points for a quadratic bezier curve and then draws it. - * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c - * - * @param {number} cpX - Control point x - * @param {number} cpY - Control point y - * @param {number} toX - Destination point x - * @param {number} toY - Destination point y - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - - - Graphics.prototype.quadraticCurveTo = function quadraticCurveTo(cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { - this.currentPath.shape.points = [0, 0]; - } - } else { - this.moveTo(0, 0); - } - - var n = 20; - var points = this.currentPath.shape.points; - var xa = 0; - var ya = 0; - - if (points.length === 0) { - this.moveTo(0, 0); - } - - var fromX = points[points.length - 2]; - var fromY = points[points.length - 1]; - - for (var i = 1; i <= n; ++i) { - var j = i / n; - - xa = fromX + (cpX - fromX) * j; - ya = fromY + (cpY - fromY) * j; - - points.push(xa + (cpX + (toX - cpX) * j - xa) * j, ya + (cpY + (toY - cpY) * j - ya) * j); - } - - this.dirty++; - - return this; - }; - - /** - * Calculate the points for a bezier curve and then draws it. - * - * @param {number} cpX - Control point x - * @param {number} cpY - Control point y - * @param {number} cpX2 - Second Control point x - * @param {number} cpY2 - Second Control point y - * @param {number} toX - Destination point x - * @param {number} toY - Destination point y - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - - - Graphics.prototype.bezierCurveTo = function bezierCurveTo(cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { - this.currentPath.shape.points = [0, 0]; - } - } else { - this.moveTo(0, 0); - } - - var points = this.currentPath.shape.points; - - var fromX = points[points.length - 2]; - var fromY = points[points.length - 1]; - - points.length -= 2; - - (0, _bezierCurveTo3.default)(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, points); - - this.dirty++; - - return this; - }; - - /** - * The arcTo() method creates an arc/curve between two tangents on the canvas. - * - * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! - * - * @param {number} x1 - The x-coordinate of the beginning of the arc - * @param {number} y1 - The y-coordinate of the beginning of the arc - * @param {number} x2 - The x-coordinate of the end of the arc - * @param {number} y2 - The y-coordinate of the end of the arc - * @param {number} radius - The radius of the arc - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - - - Graphics.prototype.arcTo = function arcTo(x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { - this.currentPath.shape.points.push(x1, y1); - } - } else { - this.moveTo(x1, y1); - } - - var points = this.currentPath.shape.points; - var fromX = points[points.length - 2]; - var fromY = points[points.length - 1]; - var a1 = fromY - y1; - var b1 = fromX - x1; - var a2 = y2 - y1; - var b2 = x2 - x1; - var mm = Math.abs(a1 * b2 - b1 * a2); - - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { - points.push(x1, y1); - } - } else { - var dd = a1 * a1 + b1 * b1; - var cc = a2 * a2 + b2 * b2; - var tt = a1 * a2 + b1 * b2; - var k1 = radius * Math.sqrt(dd) / mm; - var k2 = radius * Math.sqrt(cc) / mm; - var j1 = k1 * tt / dd; - var j2 = k2 * tt / cc; - var cx = k1 * b2 + k2 * b1; - var cy = k1 * a2 + k2 * a1; - var px = b1 * (k2 + j1); - var py = a1 * (k2 + j1); - var qx = b2 * (k1 + j2); - var qy = a2 * (k1 + j2); - var startAngle = Math.atan2(py - cy, px - cx); - var endAngle = Math.atan2(qy - cy, qx - cx); - - this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); - } - - this.dirty++; - - return this; - }; - - /** - * The arc method creates an arc/curve (used to create circles, or parts of circles). - * - * @param {number} cx - The x-coordinate of the center of the circle - * @param {number} cy - The y-coordinate of the center of the circle - * @param {number} radius - The radius of the circle - * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position - * of the arc's circle) - * @param {number} endAngle - The ending angle, in radians - * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be - * counter-clockwise or clockwise. False is default, and indicates clockwise, while true - * indicates counter-clockwise. - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - - - Graphics.prototype.arc = function arc(cx, cy, radius, startAngle, endAngle) { - var anticlockwise = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; - - if (startAngle === endAngle) { - return this; - } - - if (!anticlockwise && endAngle <= startAngle) { - endAngle += Math.PI * 2; - } else if (anticlockwise && startAngle <= endAngle) { - startAngle += Math.PI * 2; - } - - var sweep = endAngle - startAngle; - var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * 40; - - if (sweep === 0) { - return this; - } - - var startX = cx + Math.cos(startAngle) * radius; - var startY = cy + Math.sin(startAngle) * radius; - - // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. - var points = this.currentPath ? this.currentPath.shape.points : null; - - if (points) { - if (points[points.length - 2] !== startX || points[points.length - 1] !== startY) { - points.push(startX, startY); - } - } else { - this.moveTo(startX, startY); - points = this.currentPath.shape.points; - } - - var theta = sweep / (segs * 2); - var theta2 = theta * 2; - - var cTheta = Math.cos(theta); - var sTheta = Math.sin(theta); - - var segMinus = segs - 1; - - var remainder = segMinus % 1 / segMinus; - - for (var i = 0; i <= segMinus; ++i) { - var real = i + remainder * i; - - var angle = theta + startAngle + theta2 * real; - - var c = Math.cos(angle); - var s = -Math.sin(angle); - - points.push((cTheta * c + sTheta * s) * radius + cx, (cTheta * -s + sTheta * c) * radius + cy); - } - - this.dirty++; - - return this; - }; - - /** - * Specifies a simple one-color fill that subsequent calls to other Graphics methods - * (such as lineTo() or drawCircle()) use when drawing. - * - * @param {number} [color=0] - the color of the fill - * @param {number} [alpha=1] - the alpha of the fill - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - - - Graphics.prototype.beginFill = function beginFill() { - var color = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - var alpha = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; - - this.filling = true; - this.fillColor = color; - this.fillAlpha = alpha; - - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { - this.currentPath.fill = this.filling; - this.currentPath.fillColor = this.fillColor; - this.currentPath.fillAlpha = this.fillAlpha; - } - } - - return this; - }; - - /** - * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. - * - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - - - Graphics.prototype.endFill = function endFill() { - this.filling = false; - this.fillColor = null; - this.fillAlpha = 1; - - return this; - }; - - /** - * - * @param {number} x - The X coord of the top-left of the rectangle - * @param {number} y - The Y coord of the top-left of the rectangle - * @param {number} width - The width of the rectangle - * @param {number} height - The height of the rectangle - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - - - Graphics.prototype.drawRect = function drawRect(x, y, width, height) { - this.drawShape(new _math.Rectangle(x, y, width, height)); - - return this; - }; - - /** - * - * @param {number} x - The X coord of the top-left of the rectangle - * @param {number} y - The Y coord of the top-left of the rectangle - * @param {number} width - The width of the rectangle - * @param {number} height - The height of the rectangle - * @param {number} radius - Radius of the rectangle corners - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - - - Graphics.prototype.drawRoundedRect = function drawRoundedRect(x, y, width, height, radius) { - this.drawShape(new _math.RoundedRectangle(x, y, width, height, radius)); - - return this; - }; - - /** - * Draws a circle. - * - * @param {number} x - The X coordinate of the center of the circle - * @param {number} y - The Y coordinate of the center of the circle - * @param {number} radius - The radius of the circle - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - - - Graphics.prototype.drawCircle = function drawCircle(x, y, radius) { - this.drawShape(new _math.Circle(x, y, radius)); - - return this; - }; - - /** - * Draws an ellipse. - * - * @param {number} x - The X coordinate of the center of the ellipse - * @param {number} y - The Y coordinate of the center of the ellipse - * @param {number} width - The half width of the ellipse - * @param {number} height - The half height of the ellipse - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - - - Graphics.prototype.drawEllipse = function drawEllipse(x, y, width, height) { - this.drawShape(new _math.Ellipse(x, y, width, height)); - - return this; - }; - - /** - * Draws a polygon using the given path. - * - * @param {number[]|PIXI.Point[]} path - The path data used to construct the polygon. - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - - - Graphics.prototype.drawPolygon = function drawPolygon(path) { - // prevents an argument assignment deopt - // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments - var points = path; - - var closed = true; - - if (points instanceof _math.Polygon) { - closed = points.closed; - points = points.points; - } - - if (!Array.isArray(points)) { - // prevents an argument leak deopt - // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments - points = new Array(arguments.length); - - for (var i = 0; i < points.length; ++i) { - points[i] = arguments[i]; // eslint-disable-line prefer-rest-params - } - } - - var shape = new _math.Polygon(points); - - shape.closed = closed; - - this.drawShape(shape); - - return this; - }; - - /** - * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. - * - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - - - Graphics.prototype.clear = function clear() { - if (this.lineWidth || this.filling || this.graphicsData.length > 0) { - this.lineWidth = 0; - this.filling = false; - - this.boundsDirty = -1; - this.dirty++; - this.clearDirty++; - this.graphicsData.length = 0; - } - - this.currentPath = null; - this._spriteRect = null; - - return this; - }; - - /** - * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and - * masked with gl.scissor. - * - * @returns {boolean} True if only 1 rect. - */ - - - Graphics.prototype.isFastRect = function isFastRect() { - return this.graphicsData.length === 1 && this.graphicsData[0].shape.type === _const.SHAPES.RECT && !this.graphicsData[0].lineWidth; - }; - - /** - * Renders the object using the WebGL renderer - * - * @private - * @param {PIXI.WebGLRenderer} renderer - The renderer - */ - - - Graphics.prototype._renderWebGL = function _renderWebGL(renderer) { - // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.dirty !== this.fastRectDirty) { - this.fastRectDirty = this.dirty; - this._fastRect = this.isFastRect(); - } - - // TODO this check can be moved to dirty? - if (this._fastRect) { - this._renderSpriteRect(renderer); - } else { - renderer.setObjectRenderer(renderer.plugins.graphics); - renderer.plugins.graphics.render(this); - } - }; - - /** - * Renders a sprite rectangle. - * - * @private - * @param {PIXI.WebGLRenderer} renderer - The renderer - */ - - - Graphics.prototype._renderSpriteRect = function _renderSpriteRect(renderer) { - var rect = this.graphicsData[0].shape; - - if (!this._spriteRect) { - this._spriteRect = new _Sprite2.default(new _Texture2.default(_Texture2.default.WHITE)); - } - - var sprite = this._spriteRect; - - if (this.tint === 0xffffff) { - sprite.tint = this.graphicsData[0].fillColor; - } else { - var t1 = tempColor1; - var t2 = tempColor2; - - (0, _utils.hex2rgb)(this.graphicsData[0].fillColor, t1); - (0, _utils.hex2rgb)(this.tint, t2); - - t1[0] *= t2[0]; - t1[1] *= t2[1]; - t1[2] *= t2[2]; - - sprite.tint = (0, _utils.rgb2hex)(t1); - } - sprite.alpha = this.graphicsData[0].fillAlpha; - sprite.worldAlpha = this.worldAlpha * sprite.alpha; - sprite.blendMode = this.blendMode; - - sprite._texture._frame.width = rect.width; - sprite._texture._frame.height = rect.height; - - sprite.transform.worldTransform = this.transform.worldTransform; - - sprite.anchor.set(-rect.x / rect.width, -rect.y / rect.height); - sprite._onAnchorUpdate(); - - sprite._renderWebGL(renderer); - }; - - /** - * Renders the object using the Canvas renderer - * - * @private - * @param {PIXI.CanvasRenderer} renderer - The renderer - */ - - - Graphics.prototype._renderCanvas = function _renderCanvas(renderer) { - if (this.isMask === true) { - return; - } - - renderer.plugins.graphics.render(this); - }; - - /** - * Retrieves the bounds of the graphic shape as a rectangle object - * - * @private - */ - - - Graphics.prototype._calculateBounds = function _calculateBounds() { - if (this.boundsDirty !== this.dirty) { - this.boundsDirty = this.dirty; - this.updateLocalBounds(); - - this.cachedSpriteDirty = true; - } - - var lb = this._localBounds; - - this._bounds.addFrame(this.transform, lb.minX, lb.minY, lb.maxX, lb.maxY); - }; - - /** - * Tests if a point is inside this graphics object - * - * @param {PIXI.Point} point - the point to test - * @return {boolean} the result of the test - */ - - - Graphics.prototype.containsPoint = function containsPoint(point) { - this.worldTransform.applyInverse(point, tempPoint); - - var graphicsData = this.graphicsData; - - for (var i = 0; i < graphicsData.length; ++i) { - var data = graphicsData[i]; - - if (!data.fill) { - continue; - } - - // only deal with fills.. - if (data.shape) { - if (data.shape.contains(tempPoint.x, tempPoint.y)) { - if (data.holes) { - for (var _i = 0; _i < data.holes.length; _i++) { - var hole = data.holes[_i]; - - if (hole.contains(tempPoint.x, tempPoint.y)) { - return false; - } - } - } - - return true; - } - } - } - - return false; - }; - - /** - * Update the bounds of the object - * - */ - - - Graphics.prototype.updateLocalBounds = function updateLocalBounds() { - var minX = Infinity; - var maxX = -Infinity; - - var minY = Infinity; - var maxY = -Infinity; - - if (this.graphicsData.length) { - var shape = 0; - var x = 0; - var y = 0; - var w = 0; - var h = 0; - - for (var i = 0; i < this.graphicsData.length; i++) { - var data = this.graphicsData[i]; - var type = data.type; - var lineWidth = data.lineWidth; - - shape = data.shape; - - if (type === _const.SHAPES.RECT || type === _const.SHAPES.RREC) { - x = shape.x - lineWidth / 2; - y = shape.y - lineWidth / 2; - w = shape.width + lineWidth; - h = shape.height + lineWidth; - - minX = x < minX ? x : minX; - maxX = x + w > maxX ? x + w : maxX; - - minY = y < minY ? y : minY; - maxY = y + h > maxY ? y + h : maxY; - } else if (type === _const.SHAPES.CIRC) { - x = shape.x; - y = shape.y; - w = shape.radius + lineWidth / 2; - h = shape.radius + lineWidth / 2; - - minX = x - w < minX ? x - w : minX; - maxX = x + w > maxX ? x + w : maxX; - - minY = y - h < minY ? y - h : minY; - maxY = y + h > maxY ? y + h : maxY; - } else if (type === _const.SHAPES.ELIP) { - x = shape.x; - y = shape.y; - w = shape.width + lineWidth / 2; - h = shape.height + lineWidth / 2; - - minX = x - w < minX ? x - w : minX; - maxX = x + w > maxX ? x + w : maxX; - - minY = y - h < minY ? y - h : minY; - maxY = y + h > maxY ? y + h : maxY; - } else { - // POLY - var points = shape.points; - var x2 = 0; - var y2 = 0; - var dx = 0; - var dy = 0; - var rw = 0; - var rh = 0; - var cx = 0; - var cy = 0; - - for (var j = 0; j + 2 < points.length; j += 2) { - x = points[j]; - y = points[j + 1]; - x2 = points[j + 2]; - y2 = points[j + 3]; - dx = Math.abs(x2 - x); - dy = Math.abs(y2 - y); - h = lineWidth; - w = Math.sqrt(dx * dx + dy * dy); - - if (w < 1e-9) { - continue; - } - - rw = (h / w * dy + dx) / 2; - rh = (h / w * dx + dy) / 2; - cx = (x2 + x) / 2; - cy = (y2 + y) / 2; - - minX = cx - rw < minX ? cx - rw : minX; - maxX = cx + rw > maxX ? cx + rw : maxX; - - minY = cy - rh < minY ? cy - rh : minY; - maxY = cy + rh > maxY ? cy + rh : maxY; - } - } - } - } else { - minX = 0; - maxX = 0; - minY = 0; - maxY = 0; - } - - var padding = this.boundsPadding; - - this._localBounds.minX = minX - padding; - this._localBounds.maxX = maxX + padding; - - this._localBounds.minY = minY - padding; - this._localBounds.maxY = maxY + padding; - }; - - /** - * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. - * - * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. - * @return {PIXI.GraphicsData} The generated GraphicsData object. - */ - - - Graphics.prototype.drawShape = function drawShape(shape) { - if (this.currentPath) { - // check current path! - if (this.currentPath.shape.points.length <= 2) { - this.graphicsData.pop(); - } - } - - this.currentPath = null; - - var data = new _GraphicsData2.default(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, this.nativeLines, shape); - - this.graphicsData.push(data); - - if (data.type === _const.SHAPES.POLY) { - data.shape.closed = data.shape.closed || this.filling; - this.currentPath = data; - } - - this.dirty++; - - return data; - }; - - /** - * Generates a canvas texture. - * - * @param {number} scaleMode - The scale mode of the texture. - * @param {number} resolution - The resolution of the texture. - * @return {PIXI.Texture} The new texture. - */ - - - Graphics.prototype.generateCanvasTexture = function generateCanvasTexture(scaleMode) { - var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; - - var bounds = this.getLocalBounds(); - - var canvasBuffer = _RenderTexture2.default.create(bounds.width, bounds.height, scaleMode, resolution); - - if (!canvasRenderer) { - canvasRenderer = new _CanvasRenderer2.default(); - } - - this.transform.updateLocalTransform(); - this.transform.localTransform.copy(tempMatrix); - - tempMatrix.invert(); - - tempMatrix.tx -= bounds.x; - tempMatrix.ty -= bounds.y; - - canvasRenderer.render(this, canvasBuffer, true, tempMatrix); - - var texture = _Texture2.default.fromCanvas(canvasBuffer.baseTexture._canvasRenderTarget.canvas, scaleMode, 'graphics'); - - texture.baseTexture.resolution = resolution; - texture.baseTexture.update(); - - return texture; - }; - - /** - * Closes the current path. - * - * @return {PIXI.Graphics} Returns itself. - */ - - - Graphics.prototype.closePath = function closePath() { - // ok so close path assumes next one is a hole! - var currentPath = this.currentPath; - - if (currentPath && currentPath.shape) { - currentPath.shape.close(); - } - - return this; - }; - - /** - * Adds a hole in the current path. - * - * @return {PIXI.Graphics} Returns itself. - */ - - - Graphics.prototype.addHole = function addHole() { - // this is a hole! - var hole = this.graphicsData.pop(); - - this.currentPath = this.graphicsData[this.graphicsData.length - 1]; - - this.currentPath.addHole(hole.shape); - this.currentPath = null; - - return this; - }; - - /** - * Destroys the Graphics object. - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all - * options have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have - * their destroy method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the texture of the child sprite - * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the base texture of the child sprite - */ - - - Graphics.prototype.destroy = function destroy(options) { - _Container.prototype.destroy.call(this, options); - - // destroy each of the GraphicsData objects - for (var i = 0; i < this.graphicsData.length; ++i) { - this.graphicsData[i].destroy(); - } - - // for each webgl data entry, destroy the WebGLGraphicsData - for (var id in this._webgl) { - for (var j = 0; j < this._webgl[id].data.length; ++j) { - this._webgl[id].data[j].destroy(); - } - } - - if (this._spriteRect) { - this._spriteRect.destroy(); - } - - this.graphicsData = null; - - this.currentPath = null; - this._webgl = null; - this._localBounds = null; - }; - - return Graphics; -}(_Container3.default); - -exports.default = Graphics; - - -Graphics._SPRITE_TEXTURE = null; - -},{"../const":46,"../display/Bounds":47,"../display/Container":48,"../math":70,"../renderers/canvas/CanvasRenderer":77,"../sprites/Sprite":102,"../textures/RenderTexture":113,"../textures/Texture":115,"../utils":124,"./GraphicsData":54,"./utils/bezierCurveTo":56}],54:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * A GraphicsData object. - * - * @class - * @memberof PIXI - */ -var GraphicsData = function () { - /** - * - * @param {number} lineWidth - the width of the line to draw - * @param {number} lineColor - the color of the line to draw - * @param {number} lineAlpha - the alpha of the line to draw - * @param {number} fillColor - the color of the fill - * @param {number} fillAlpha - the alpha of the fill - * @param {boolean} fill - whether or not the shape is filled with a colour - * @param {boolean} nativeLines - the method for drawing lines - * @param {PIXI.Circle|PIXI.Rectangle|PIXI.Ellipse|PIXI.Polygon} shape - The shape object to draw. - */ - function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, nativeLines, shape) { - _classCallCheck(this, GraphicsData); - - /** - * @member {number} the width of the line to draw - */ - this.lineWidth = lineWidth; - /** - * @member {boolean} if true the liens will be draw using LINES instead of TRIANGLE_STRIP - */ - this.nativeLines = nativeLines; - - /** - * @member {number} the color of the line to draw - */ - this.lineColor = lineColor; - - /** - * @member {number} the alpha of the line to draw - */ - this.lineAlpha = lineAlpha; - - /** - * @member {number} cached tint of the line to draw - */ - this._lineTint = lineColor; - - /** - * @member {number} the color of the fill - */ - this.fillColor = fillColor; - - /** - * @member {number} the alpha of the fill - */ - this.fillAlpha = fillAlpha; - - /** - * @member {number} cached tint of the fill - */ - this._fillTint = fillColor; - - /** - * @member {boolean} whether or not the shape is filled with a colour - */ - this.fill = fill; - - this.holes = []; - - /** - * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} The shape object to draw. - */ - this.shape = shape; - - /** - * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, - */ - this.type = shape.type; - } - - /** - * Creates a new GraphicsData object with the same values as this one. - * - * @return {PIXI.GraphicsData} Cloned GraphicsData object - */ - - - GraphicsData.prototype.clone = function clone() { - return new GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.fill, this.nativeLines, this.shape); - }; - - /** - * Adds a hole to the shape. - * - * @param {PIXI.Rectangle|PIXI.Circle} shape - The shape of the hole. - */ - - - GraphicsData.prototype.addHole = function addHole(shape) { - this.holes.push(shape); - }; - - /** - * Destroys the Graphics data. - */ - - - GraphicsData.prototype.destroy = function destroy() { - this.shape = null; - this.holes = null; - }; - - return GraphicsData; -}(); - -exports.default = GraphicsData; - -},{}],55:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); - -var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); - -var _const = require('../../const'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * @author Mat Groves - * - * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ - * for creating the original PixiJS version! - * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they - * now share 4 bytes on the vertex buffer - * - * Heavily inspired by LibGDX's CanvasGraphicsRenderer: - * https://github.com/libgdx/libgdx/blob/1.0.0/gdx/src/com/badlogic/gdx/graphics/glutils/ShapeRenderer.java - */ - -/** - * Renderer dedicated to drawing and batching graphics objects. - * - * @class - * @private - * @memberof PIXI - */ -var CanvasGraphicsRenderer = function () { - /** - * @param {PIXI.CanvasRenderer} renderer - The current PIXI renderer. - */ - function CanvasGraphicsRenderer(renderer) { - _classCallCheck(this, CanvasGraphicsRenderer); - - this.renderer = renderer; - } - - /** - * Renders a Graphics object to a canvas. - * - * @param {PIXI.Graphics} graphics - the actual graphics object to render - */ - - - CanvasGraphicsRenderer.prototype.render = function render(graphics) { - var renderer = this.renderer; - var context = renderer.context; - var worldAlpha = graphics.worldAlpha; - var transform = graphics.transform.worldTransform; - var resolution = renderer.resolution; - - // if the tint has changed, set the graphics object to dirty. - if (this._prevTint !== this.tint) { - this.dirty = true; - } - - context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); - - if (graphics.dirty) { - this.updateGraphicsTint(graphics); - graphics.dirty = false; - } - - renderer.setBlendMode(graphics.blendMode); - - for (var i = 0; i < graphics.graphicsData.length; i++) { - var data = graphics.graphicsData[i]; - var shape = data.shape; - - var fillColor = data._fillTint; - var lineColor = data._lineTint; - - context.lineWidth = data.lineWidth; - - if (data.type === _const.SHAPES.POLY) { - context.beginPath(); - - this.renderPolygon(shape.points, shape.closed, context); - - for (var j = 0; j < data.holes.length; j++) { - this.renderPolygon(data.holes[j].points, true, context); - } - - if (data.fill) { - context.globalAlpha = data.fillAlpha * worldAlpha; - context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); - context.fill(); - } - if (data.lineWidth) { - context.globalAlpha = data.lineAlpha * worldAlpha; - context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); - context.stroke(); - } - } else if (data.type === _const.SHAPES.RECT) { - if (data.fillColor || data.fillColor === 0) { - context.globalAlpha = data.fillAlpha * worldAlpha; - context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); - context.fillRect(shape.x, shape.y, shape.width, shape.height); - } - if (data.lineWidth) { - context.globalAlpha = data.lineAlpha * worldAlpha; - context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); - context.strokeRect(shape.x, shape.y, shape.width, shape.height); - } - } else if (data.type === _const.SHAPES.CIRC) { - // TODO - need to be Undefined! - context.beginPath(); - context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); - context.closePath(); - - if (data.fill) { - context.globalAlpha = data.fillAlpha * worldAlpha; - context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); - context.fill(); - } - if (data.lineWidth) { - context.globalAlpha = data.lineAlpha * worldAlpha; - context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); - context.stroke(); - } - } else if (data.type === _const.SHAPES.ELIP) { - // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas - - var w = shape.width * 2; - var h = shape.height * 2; - - var x = shape.x - w / 2; - var y = shape.y - h / 2; - - context.beginPath(); - - var kappa = 0.5522848; - var ox = w / 2 * kappa; // control point offset horizontal - var oy = h / 2 * kappa; // control point offset vertical - var xe = x + w; // x-end - var ye = y + h; // y-end - var xm = x + w / 2; // x-middle - var ym = y + h / 2; // y-middle - - context.moveTo(x, ym); - context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); - context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); - context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); - context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); - - context.closePath(); - - if (data.fill) { - context.globalAlpha = data.fillAlpha * worldAlpha; - context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); - context.fill(); - } - if (data.lineWidth) { - context.globalAlpha = data.lineAlpha * worldAlpha; - context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); - context.stroke(); - } - } else if (data.type === _const.SHAPES.RREC) { - var rx = shape.x; - var ry = shape.y; - var width = shape.width; - var height = shape.height; - var radius = shape.radius; - - var maxRadius = Math.min(width, height) / 2 | 0; - - radius = radius > maxRadius ? maxRadius : radius; - - context.beginPath(); - context.moveTo(rx, ry + radius); - context.lineTo(rx, ry + height - radius); - context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); - context.lineTo(rx + width - radius, ry + height); - context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); - context.lineTo(rx + width, ry + radius); - context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); - context.lineTo(rx + radius, ry); - context.quadraticCurveTo(rx, ry, rx, ry + radius); - context.closePath(); - - if (data.fillColor || data.fillColor === 0) { - context.globalAlpha = data.fillAlpha * worldAlpha; - context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); - context.fill(); - } - - if (data.lineWidth) { - context.globalAlpha = data.lineAlpha * worldAlpha; - context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); - context.stroke(); - } - } - } - }; - - /** - * Updates the tint of a graphics object - * - * @private - * @param {PIXI.Graphics} graphics - the graphics that will have its tint updated - */ - - - CanvasGraphicsRenderer.prototype.updateGraphicsTint = function updateGraphicsTint(graphics) { - graphics._prevTint = graphics.tint; - - var tintR = (graphics.tint >> 16 & 0xFF) / 255; - var tintG = (graphics.tint >> 8 & 0xFF) / 255; - var tintB = (graphics.tint & 0xFF) / 255; - - for (var i = 0; i < graphics.graphicsData.length; ++i) { - var data = graphics.graphicsData[i]; - - var fillColor = data.fillColor | 0; - var lineColor = data.lineColor | 0; - - // super inline cos im an optimization NAZI :) - data._fillTint = ((fillColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (fillColor & 0xFF) / 255 * tintB * 255; - - data._lineTint = ((lineColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (lineColor & 0xFF) / 255 * tintB * 255; - } - }; - - /** - * Renders a polygon. - * - * @param {PIXI.Point[]} points - The points to render - * @param {boolean} close - Should the polygon be closed - * @param {CanvasRenderingContext2D} context - The rendering context to use - */ - - - CanvasGraphicsRenderer.prototype.renderPolygon = function renderPolygon(points, close, context) { - context.moveTo(points[0], points[1]); - - for (var j = 1; j < points.length / 2; ++j) { - context.lineTo(points[j * 2], points[j * 2 + 1]); - } - - if (close) { - context.closePath(); - } - }; - - /** - * destroy graphics object - * - */ - - - CanvasGraphicsRenderer.prototype.destroy = function destroy() { - this.renderer = null; - }; - - return CanvasGraphicsRenderer; -}(); - -exports.default = CanvasGraphicsRenderer; - - -_CanvasRenderer2.default.registerPlugin('graphics', CanvasGraphicsRenderer); - -},{"../../const":46,"../../renderers/canvas/CanvasRenderer":77}],56:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.default = bezierCurveTo; -/** - * Calculate the points for a bezier curve and then draws it. - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @param {number} fromX - Starting point x - * @param {number} fromY - Starting point y - * @param {number} cpX - Control point x - * @param {number} cpY - Control point y - * @param {number} cpX2 - Second Control point x - * @param {number} cpY2 - Second Control point y - * @param {number} toX - Destination point x - * @param {number} toY - Destination point y - * @param {number[]} [path=[]] - Path array to push points into - * @return {number[]} Array of points of the curve - */ -function bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { - var path = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : []; - - var n = 20; - var dt = 0; - var dt2 = 0; - var dt3 = 0; - var t2 = 0; - var t3 = 0; - - path.push(fromX, fromY); - - for (var i = 1, j = 0; i <= n; ++i) { - j = i / n; - - dt = 1 - j; - dt2 = dt * dt; - dt3 = dt2 * dt; - - t2 = j * j; - t3 = t2 * j; - - path.push(dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); - } - - return path; -} - -},{}],57:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _utils = require('../../utils'); - -var _const = require('../../const'); - -var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); - -var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); - -var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); - -var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); - -var _WebGLGraphicsData = require('./WebGLGraphicsData'); - -var _WebGLGraphicsData2 = _interopRequireDefault(_WebGLGraphicsData); - -var _PrimitiveShader = require('./shaders/PrimitiveShader'); - -var _PrimitiveShader2 = _interopRequireDefault(_PrimitiveShader); - -var _buildPoly = require('./utils/buildPoly'); - -var _buildPoly2 = _interopRequireDefault(_buildPoly); - -var _buildRectangle = require('./utils/buildRectangle'); - -var _buildRectangle2 = _interopRequireDefault(_buildRectangle); - -var _buildRoundedRectangle = require('./utils/buildRoundedRectangle'); - -var _buildRoundedRectangle2 = _interopRequireDefault(_buildRoundedRectangle); - -var _buildCircle = require('./utils/buildCircle'); - -var _buildCircle2 = _interopRequireDefault(_buildCircle); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * Renders the graphics object. - * - * @class - * @memberof PIXI - * @extends PIXI.ObjectRenderer - */ -var GraphicsRenderer = function (_ObjectRenderer) { - _inherits(GraphicsRenderer, _ObjectRenderer); - - /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this object renderer works for. - */ - function GraphicsRenderer(renderer) { - _classCallCheck(this, GraphicsRenderer); - - var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); - - _this.graphicsDataPool = []; - - _this.primitiveShader = null; - - _this.gl = renderer.gl; - - // easy access! - _this.CONTEXT_UID = 0; - return _this; - } - - /** - * Called when there is a WebGL context change - * - * @private - * - */ - - - GraphicsRenderer.prototype.onContextChange = function onContextChange() { - this.gl = this.renderer.gl; - this.CONTEXT_UID = this.renderer.CONTEXT_UID; - this.primitiveShader = new _PrimitiveShader2.default(this.gl); - }; - - /** - * Destroys this renderer. - * - */ - - - GraphicsRenderer.prototype.destroy = function destroy() { - _ObjectRenderer3.default.prototype.destroy.call(this); - - for (var i = 0; i < this.graphicsDataPool.length; ++i) { - this.graphicsDataPool[i].destroy(); - } - - this.graphicsDataPool = null; - }; - - /** - * Renders a graphics object. - * - * @param {PIXI.Graphics} graphics - The graphics object to render. - */ - - - GraphicsRenderer.prototype.render = function render(graphics) { - var renderer = this.renderer; - var gl = renderer.gl; - - var webGLData = void 0; - var webGL = graphics._webGL[this.CONTEXT_UID]; - - if (!webGL || graphics.dirty !== webGL.dirty) { - this.updateGraphics(graphics); - - webGL = graphics._webGL[this.CONTEXT_UID]; - } - - // This could be speeded up for sure! - var shader = this.primitiveShader; - - renderer.bindShader(shader); - renderer.state.setBlendMode(graphics.blendMode); - - for (var i = 0, n = webGL.data.length; i < n; i++) { - webGLData = webGL.data[i]; - var shaderTemp = webGLData.shader; - - renderer.bindShader(shaderTemp); - shaderTemp.uniforms.translationMatrix = graphics.transform.worldTransform.toArray(true); - shaderTemp.uniforms.tint = (0, _utils.hex2rgb)(graphics.tint); - shaderTemp.uniforms.alpha = graphics.worldAlpha; - - renderer.bindVao(webGLData.vao); - - if (webGLData.nativeLines) { - gl.drawArrays(gl.LINES, 0, webGLData.points.length / 6); - } else { - webGLData.vao.draw(gl.TRIANGLE_STRIP, webGLData.indices.length); - } - } - }; - - /** - * Updates the graphics object - * - * @private - * @param {PIXI.Graphics} graphics - The graphics object to update - */ - - - GraphicsRenderer.prototype.updateGraphics = function updateGraphics(graphics) { - var gl = this.renderer.gl; - - // get the contexts graphics object - var webGL = graphics._webGL[this.CONTEXT_UID]; - - // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { - webGL = graphics._webGL[this.CONTEXT_UID] = { lastIndex: 0, data: [], gl: gl, clearDirty: -1, dirty: -1 }; - } - - // flag the graphics as not dirty as we are about to update it... - webGL.dirty = graphics.dirty; - - // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty !== webGL.clearDirty) { - webGL.clearDirty = graphics.clearDirty; - - // loop through and return all the webGLDatas to the object pool so than can be reused later on - for (var i = 0; i < webGL.data.length; i++) { - this.graphicsDataPool.push(webGL.data[i]); - } - - // clear the array and reset the index.. - webGL.data.length = 0; - webGL.lastIndex = 0; - } - - var webGLData = void 0; - var webGLDataNativeLines = void 0; - - // loop through the graphics datas and construct each one.. - // if the object is a complex fill then the new stencil buffer technique will be used - // other wise graphics objects will be pushed into a batch.. - for (var _i = webGL.lastIndex; _i < graphics.graphicsData.length; _i++) { - var data = graphics.graphicsData[_i]; - - // TODO - this can be simplified - webGLData = this.getWebGLData(webGL, 0); - - if (data.nativeLines && data.lineWidth) { - webGLDataNativeLines = this.getWebGLData(webGL, 0, true); - webGL.lastIndex++; - } - - if (data.type === _const.SHAPES.POLY) { - (0, _buildPoly2.default)(data, webGLData, webGLDataNativeLines); - } - if (data.type === _const.SHAPES.RECT) { - (0, _buildRectangle2.default)(data, webGLData, webGLDataNativeLines); - } else if (data.type === _const.SHAPES.CIRC || data.type === _const.SHAPES.ELIP) { - (0, _buildCircle2.default)(data, webGLData, webGLDataNativeLines); - } else if (data.type === _const.SHAPES.RREC) { - (0, _buildRoundedRectangle2.default)(data, webGLData, webGLDataNativeLines); - } - - webGL.lastIndex++; - } - - this.renderer.bindVao(null); - - // upload all the dirty data... - for (var _i2 = 0; _i2 < webGL.data.length; _i2++) { - webGLData = webGL.data[_i2]; - - if (webGLData.dirty) { - webGLData.upload(); - } - } - }; - - /** - * - * @private - * @param {WebGLRenderingContext} gl - the current WebGL drawing context - * @param {number} type - TODO @Alvin - * @param {number} nativeLines - indicate whether the webGLData use for nativeLines. - * @return {*} TODO - */ - - - GraphicsRenderer.prototype.getWebGLData = function getWebGLData(gl, type, nativeLines) { - var webGLData = gl.data[gl.data.length - 1]; - - if (!webGLData || webGLData.nativeLines !== nativeLines || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new _WebGLGraphicsData2.default(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); - webGLData.nativeLines = nativeLines; - webGLData.reset(type); - gl.data.push(webGLData); - } - - webGLData.dirty = true; - - return webGLData; - }; - - return GraphicsRenderer; -}(_ObjectRenderer3.default); - -exports.default = GraphicsRenderer; - - -_WebGLRenderer2.default.registerPlugin('graphics', GraphicsRenderer); - -},{"../../const":46,"../../renderers/webgl/WebGLRenderer":84,"../../renderers/webgl/utils/ObjectRenderer":94,"../../utils":124,"./WebGLGraphicsData":58,"./shaders/PrimitiveShader":59,"./utils/buildCircle":60,"./utils/buildPoly":62,"./utils/buildRectangle":63,"./utils/buildRoundedRectangle":64}],58:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _pixiGlCore = require('pixi-gl-core'); - -var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * An object containing WebGL specific properties to be used by the WebGL renderer - * - * @class - * @private - * @memberof PIXI - */ -var WebGLGraphicsData = function () { - /** - * @param {WebGLRenderingContext} gl - The current WebGL drawing context - * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO - */ - function WebGLGraphicsData(gl, shader, attribsState) { - _classCallCheck(this, WebGLGraphicsData); - - /** - * The current WebGL drawing context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - // TODO does this need to be split before uploading?? - /** - * An array of color components (r,g,b) - * @member {number[]} - */ - this.color = [0, 0, 0]; // color split! - - /** - * An array of points to draw - * @member {PIXI.Point[]} - */ - this.points = []; - - /** - * The indices of the vertices - * @member {number[]} - */ - this.indices = []; - /** - * The main buffer - * @member {WebGLBuffer} - */ - this.buffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl); - - /** - * The index buffer - * @member {WebGLBuffer} - */ - this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl); - - /** - * Whether this graphics is dirty or not - * @member {boolean} - */ - this.dirty = true; - - /** - * Whether this graphics is nativeLines or not - * @member {boolean} - */ - this.nativeLines = false; - - this.glPoints = null; - this.glIndices = null; - - /** - * - * @member {PIXI.Shader} - */ - this.shader = shader; - - this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, attribsState).addIndex(this.indexBuffer).addAttribute(this.buffer, shader.attributes.aVertexPosition, gl.FLOAT, false, 4 * 6, 0).addAttribute(this.buffer, shader.attributes.aColor, gl.FLOAT, false, 4 * 6, 2 * 4); - } - - /** - * Resets the vertices and the indices - */ - - - WebGLGraphicsData.prototype.reset = function reset() { - this.points.length = 0; - this.indices.length = 0; - }; - - /** - * Binds the buffers and uploads the data - */ - - - WebGLGraphicsData.prototype.upload = function upload() { - this.glPoints = new Float32Array(this.points); - this.buffer.upload(this.glPoints); - - this.glIndices = new Uint16Array(this.indices); - this.indexBuffer.upload(this.glIndices); - - this.dirty = false; - }; - - /** - * Empties all the data - */ - - - WebGLGraphicsData.prototype.destroy = function destroy() { - this.color = null; - this.points = null; - this.indices = null; - - this.vao.destroy(); - this.buffer.destroy(); - this.indexBuffer.destroy(); - - this.gl = null; - - this.buffer = null; - this.indexBuffer = null; - - this.glPoints = null; - this.glIndices = null; - }; - - return WebGLGraphicsData; -}(); - -exports.default = WebGLGraphicsData; - -},{"pixi-gl-core":12}],59:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _Shader2 = require('../../../Shader'); - -var _Shader3 = _interopRequireDefault(_Shader2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. - * - * @class - * @memberof PIXI - * @extends PIXI.Shader - */ -var PrimitiveShader = function (_Shader) { - _inherits(PrimitiveShader, _Shader); - - /** - * @param {WebGLRenderingContext} gl - The webgl shader manager this shader works for. - */ - function PrimitiveShader(gl) { - _classCallCheck(this, PrimitiveShader); - - return _possibleConstructorReturn(this, _Shader.call(this, gl, - // vertex shader - ['attribute vec2 aVertexPosition;', 'attribute vec4 aColor;', 'uniform mat3 translationMatrix;', 'uniform mat3 projectionMatrix;', 'uniform float alpha;', 'uniform vec3 tint;', 'varying vec4 vColor;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vColor = aColor * vec4(tint * alpha, alpha);', '}'].join('\n'), - // fragment shader - ['varying vec4 vColor;', 'void main(void){', ' gl_FragColor = vColor;', '}'].join('\n'))); - } - - return PrimitiveShader; -}(_Shader3.default); - -exports.default = PrimitiveShader; - -},{"../../../Shader":44}],60:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.default = buildCircle; - -var _buildLine = require('./buildLine'); - -var _buildLine2 = _interopRequireDefault(_buildLine); - -var _const = require('../../../const'); - -var _utils = require('../../../utils'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Builds a circle to draw - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw - * @param {object} webGLData - an object containing all the webGL-specific information to create this shape - * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines - */ -function buildCircle(graphicsData, webGLData, webGLDataNativeLines) { - // need to convert points to a nice regular data - var circleData = graphicsData.shape; - var x = circleData.x; - var y = circleData.y; - var width = void 0; - var height = void 0; - - // TODO - bit hacky?? - if (graphicsData.type === _const.SHAPES.CIRC) { - width = circleData.radius; - height = circleData.radius; - } else { - width = circleData.width; - height = circleData.height; - } - - if (width === 0 || height === 0) { - return; - } - - var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) || Math.floor(15 * Math.sqrt(circleData.width + circleData.height)); - - var seg = Math.PI * 2 / totalSegs; - - if (graphicsData.fill) { - var color = (0, _utils.hex2rgb)(graphicsData.fillColor); - var alpha = graphicsData.fillAlpha; - - var r = color[0] * alpha; - var g = color[1] * alpha; - var b = color[2] * alpha; - - var verts = webGLData.points; - var indices = webGLData.indices; - - var vecPos = verts.length / 6; - - indices.push(vecPos); - - for (var i = 0; i < totalSegs + 1; i++) { - verts.push(x, y, r, g, b, alpha); - - verts.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height, r, g, b, alpha); - - indices.push(vecPos++, vecPos++); - } - - indices.push(vecPos - 1); - } - - if (graphicsData.lineWidth) { - var tempPoints = graphicsData.points; - - graphicsData.points = []; - - for (var _i = 0; _i < totalSegs + 1; _i++) { - graphicsData.points.push(x + Math.sin(seg * _i) * width, y + Math.cos(seg * _i) * height); - } - - (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); - - graphicsData.points = tempPoints; - } -} - -},{"../../../const":46,"../../../utils":124,"./buildLine":61}],61:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -exports.default = function (graphicsData, webGLData, webGLDataNativeLines) { - if (graphicsData.nativeLines) { - buildNativeLine(graphicsData, webGLDataNativeLines); - } else { - buildLine(graphicsData, webGLData); - } -}; - -var _math = require('../../../math'); - -var _utils = require('../../../utils'); - -/** - * Builds a line to draw using the poligon method. - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {object} webGLData - an object containing all the webGL-specific information to create this shape - */ -function buildLine(graphicsData, webGLData) { - // TODO OPTIMISE! - var points = graphicsData.points; - - if (points.length === 0) { - return; - } - // if the line width is an odd number add 0.5 to align to a whole pixel - // commenting this out fixes #711 and #1620 - // if (graphicsData.lineWidth%2) - // { - // for (i = 0; i < points.length; i++) - // { - // points[i] += 0.5; - // } - // } - - // get first and last point.. figure out the middle! - var firstPoint = new _math.Point(points[0], points[1]); - var lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); - - // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { - // need to clone as we are going to slightly modify the shape.. - points = points.slice(); - - points.pop(); - points.pop(); - - lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); - - var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) * 0.5; - var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) * 0.5; - - points.unshift(midPointX, midPointY); - points.push(midPointX, midPointY); - } - - var verts = webGLData.points; - var indices = webGLData.indices; - var length = points.length / 2; - var indexCount = points.length; - var indexStart = verts.length / 6; - - // DRAW the Line - var width = graphicsData.lineWidth / 2; - - // sort color - var color = (0, _utils.hex2rgb)(graphicsData.lineColor); - var alpha = graphicsData.lineAlpha; - var r = color[0] * alpha; - var g = color[1] * alpha; - var b = color[2] * alpha; - - var p1x = points[0]; - var p1y = points[1]; - var p2x = points[2]; - var p2y = points[3]; - var p3x = 0; - var p3y = 0; - - var perpx = -(p1y - p2y); - var perpy = p1x - p2x; - var perp2x = 0; - var perp2y = 0; - var perp3x = 0; - var perp3y = 0; - - var dist = Math.sqrt(perpx * perpx + perpy * perpy); - - perpx /= dist; - perpy /= dist; - perpx *= width; - perpy *= width; - - // start - verts.push(p1x - perpx, p1y - perpy, r, g, b, alpha); - - verts.push(p1x + perpx, p1y + perpy, r, g, b, alpha); - - for (var i = 1; i < length - 1; ++i) { - p1x = points[(i - 1) * 2]; - p1y = points[(i - 1) * 2 + 1]; - - p2x = points[i * 2]; - p2y = points[i * 2 + 1]; - - p3x = points[(i + 1) * 2]; - p3y = points[(i + 1) * 2 + 1]; - - perpx = -(p1y - p2y); - perpy = p1x - p2x; - - dist = Math.sqrt(perpx * perpx + perpy * perpy); - perpx /= dist; - perpy /= dist; - perpx *= width; - perpy *= width; - - perp2x = -(p2y - p3y); - perp2y = p2x - p3x; - - dist = Math.sqrt(perp2x * perp2x + perp2y * perp2y); - perp2x /= dist; - perp2y /= dist; - perp2x *= width; - perp2y *= width; - - var a1 = -perpy + p1y - (-perpy + p2y); - var b1 = -perpx + p2x - (-perpx + p1x); - var c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); - var a2 = -perp2y + p3y - (-perp2y + p2y); - var b2 = -perp2x + p2x - (-perp2x + p3x); - var c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); - - var denom = a1 * b2 - a2 * b1; - - if (Math.abs(denom) < 0.1) { - denom += 10.1; - verts.push(p2x - perpx, p2y - perpy, r, g, b, alpha); - - verts.push(p2x + perpx, p2y + perpy, r, g, b, alpha); - - continue; - } - - var px = (b1 * c2 - b2 * c1) / denom; - var py = (a2 * c1 - a1 * c2) / denom; - var pdist = (px - p2x) * (px - p2x) + (py - p2y) * (py - p2y); - - if (pdist > 196 * width * width) { - perp3x = perpx - perp2x; - perp3y = perpy - perp2y; - - dist = Math.sqrt(perp3x * perp3x + perp3y * perp3y); - perp3x /= dist; - perp3y /= dist; - perp3x *= width; - perp3y *= width; - - verts.push(p2x - perp3x, p2y - perp3y); - verts.push(r, g, b, alpha); - - verts.push(p2x + perp3x, p2y + perp3y); - verts.push(r, g, b, alpha); - - verts.push(p2x - perp3x, p2y - perp3y); - verts.push(r, g, b, alpha); - - indexCount++; - } else { - verts.push(px, py); - verts.push(r, g, b, alpha); - - verts.push(p2x - (px - p2x), p2y - (py - p2y)); - verts.push(r, g, b, alpha); - } - } - - p1x = points[(length - 2) * 2]; - p1y = points[(length - 2) * 2 + 1]; - - p2x = points[(length - 1) * 2]; - p2y = points[(length - 1) * 2 + 1]; - - perpx = -(p1y - p2y); - perpy = p1x - p2x; - - dist = Math.sqrt(perpx * perpx + perpy * perpy); - perpx /= dist; - perpy /= dist; - perpx *= width; - perpy *= width; - - verts.push(p2x - perpx, p2y - perpy); - verts.push(r, g, b, alpha); - - verts.push(p2x + perpx, p2y + perpy); - verts.push(r, g, b, alpha); - - indices.push(indexStart); - - for (var _i = 0; _i < indexCount; ++_i) { - indices.push(indexStart++); - } - - indices.push(indexStart - 1); -} - -/** - * Builds a line to draw using the gl.drawArrays(gl.LINES) method - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {object} webGLData - an object containing all the webGL-specific information to create this shape - */ - - -/** - * Builds a line to draw - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {object} webGLData - an object containing all the webGL-specific information to create this shape - * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines - */ -function buildNativeLine(graphicsData, webGLData) { - var i = 0; - var points = graphicsData.points; - - if (points.length === 0) return; - - var verts = webGLData.points; - var length = points.length / 2; - - // sort color - var color = (0, _utils.hex2rgb)(graphicsData.lineColor); - var alpha = graphicsData.lineAlpha; - var r = color[0] * alpha; - var g = color[1] * alpha; - var b = color[2] * alpha; - - for (i = 1; i < length; i++) { - var p1x = points[(i - 1) * 2]; - var p1y = points[(i - 1) * 2 + 1]; - - var p2x = points[i * 2]; - var p2y = points[i * 2 + 1]; - - verts.push(p1x, p1y); - verts.push(r, g, b, alpha); - - verts.push(p2x, p2y); - verts.push(r, g, b, alpha); - } -} - -},{"../../../math":70,"../../../utils":124}],62:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.default = buildPoly; - -var _buildLine = require('./buildLine'); - -var _buildLine2 = _interopRequireDefault(_buildLine); - -var _utils = require('../../../utils'); - -var _earcut = require('earcut'); - -var _earcut2 = _interopRequireDefault(_earcut); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Builds a polygon to draw - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {object} webGLData - an object containing all the webGL-specific information to create this shape - * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines - */ -function buildPoly(graphicsData, webGLData, webGLDataNativeLines) { - graphicsData.points = graphicsData.shape.points.slice(); - - var points = graphicsData.points; - - if (graphicsData.fill && points.length >= 6) { - var holeArray = []; - // Process holes.. - var holes = graphicsData.holes; - - for (var i = 0; i < holes.length; i++) { - var hole = holes[i]; - - holeArray.push(points.length / 2); - - points = points.concat(hole.points); - } - - // get first and last point.. figure out the middle! - var verts = webGLData.points; - var indices = webGLData.indices; - - var length = points.length / 2; - - // sort color - var color = (0, _utils.hex2rgb)(graphicsData.fillColor); - var alpha = graphicsData.fillAlpha; - var r = color[0] * alpha; - var g = color[1] * alpha; - var b = color[2] * alpha; - - var triangles = (0, _earcut2.default)(points, holeArray, 2); - - if (!triangles) { - return; - } - - var vertPos = verts.length / 6; - - for (var _i = 0; _i < triangles.length; _i += 3) { - indices.push(triangles[_i] + vertPos); - indices.push(triangles[_i] + vertPos); - indices.push(triangles[_i + 1] + vertPos); - indices.push(triangles[_i + 2] + vertPos); - indices.push(triangles[_i + 2] + vertPos); - } - - for (var _i2 = 0; _i2 < length; _i2++) { - verts.push(points[_i2 * 2], points[_i2 * 2 + 1], r, g, b, alpha); - } - } - - if (graphicsData.lineWidth > 0) { - (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); - } -} - -},{"../../../utils":124,"./buildLine":61,"earcut":2}],63:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.default = buildRectangle; - -var _buildLine = require('./buildLine'); - -var _buildLine2 = _interopRequireDefault(_buildLine); - -var _utils = require('../../../utils'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Builds a rectangle to draw - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {object} webGLData - an object containing all the webGL-specific information to create this shape - * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines - */ -function buildRectangle(graphicsData, webGLData, webGLDataNativeLines) { - // --- // - // need to convert points to a nice regular data - // - var rectData = graphicsData.shape; - var x = rectData.x; - var y = rectData.y; - var width = rectData.width; - var height = rectData.height; - - if (graphicsData.fill) { - var color = (0, _utils.hex2rgb)(graphicsData.fillColor); - var alpha = graphicsData.fillAlpha; - - var r = color[0] * alpha; - var g = color[1] * alpha; - var b = color[2] * alpha; - - var verts = webGLData.points; - var indices = webGLData.indices; - - var vertPos = verts.length / 6; - - // start - verts.push(x, y); - verts.push(r, g, b, alpha); - - verts.push(x + width, y); - verts.push(r, g, b, alpha); - - verts.push(x, y + height); - verts.push(r, g, b, alpha); - - verts.push(x + width, y + height); - verts.push(r, g, b, alpha); - - // insert 2 dead triangles.. - indices.push(vertPos, vertPos, vertPos + 1, vertPos + 2, vertPos + 3, vertPos + 3); - } - - if (graphicsData.lineWidth) { - var tempPoints = graphicsData.points; - - graphicsData.points = [x, y, x + width, y, x + width, y + height, x, y + height, x, y]; - - (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); - - graphicsData.points = tempPoints; - } -} - -},{"../../../utils":124,"./buildLine":61}],64:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.default = buildRoundedRectangle; - -var _earcut = require('earcut'); - -var _earcut2 = _interopRequireDefault(_earcut); - -var _buildLine = require('./buildLine'); - -var _buildLine2 = _interopRequireDefault(_buildLine); - -var _utils = require('../../../utils'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Builds a rounded rectangle to draw - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {object} webGLData - an object containing all the webGL-specific information to create this shape - * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines - */ -function buildRoundedRectangle(graphicsData, webGLData, webGLDataNativeLines) { - var rrectData = graphicsData.shape; - var x = rrectData.x; - var y = rrectData.y; - var width = rrectData.width; - var height = rrectData.height; - - var radius = rrectData.radius; - - var recPoints = []; - - recPoints.push(x, y + radius); - quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height, recPoints); - quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius, recPoints); - quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y, recPoints); - quadraticBezierCurve(x + radius, y, x, y, x, y + radius + 0.0000000001, recPoints); - - // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. - // TODO - fix this properly, this is not very elegant.. but it works for now. - - if (graphicsData.fill) { - var color = (0, _utils.hex2rgb)(graphicsData.fillColor); - var alpha = graphicsData.fillAlpha; - - var r = color[0] * alpha; - var g = color[1] * alpha; - var b = color[2] * alpha; - - var verts = webGLData.points; - var indices = webGLData.indices; - - var vecPos = verts.length / 6; - - var triangles = (0, _earcut2.default)(recPoints, null, 2); - - for (var i = 0, j = triangles.length; i < j; i += 3) { - indices.push(triangles[i] + vecPos); - indices.push(triangles[i] + vecPos); - indices.push(triangles[i + 1] + vecPos); - indices.push(triangles[i + 2] + vecPos); - indices.push(triangles[i + 2] + vecPos); - } - - for (var _i = 0, _j = recPoints.length; _i < _j; _i++) { - verts.push(recPoints[_i], recPoints[++_i], r, g, b, alpha); - } - } - - if (graphicsData.lineWidth) { - var tempPoints = graphicsData.points; - - graphicsData.points = recPoints; - - (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); - - graphicsData.points = tempPoints; - } -} - -/** - * Calculate a single point for a quadratic bezier curve. - * Utility function used by quadraticBezierCurve. - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {number} n1 - first number - * @param {number} n2 - second number - * @param {number} perc - percentage - * @return {number} the result - * - */ -function getPt(n1, n2, perc) { - var diff = n2 - n1; - - return n1 + diff * perc; -} - -/** - * Calculate the points for a quadratic bezier curve. (helper function..) - * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {number} fromX - Origin point x - * @param {number} fromY - Origin point x - * @param {number} cpX - Control point x - * @param {number} cpY - Control point y - * @param {number} toX - Destination point x - * @param {number} toY - Destination point y - * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. - * @return {number[]} an array of points - */ -function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY) { - var out = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : []; - - var n = 20; - var points = out; - - var xa = 0; - var ya = 0; - var xb = 0; - var yb = 0; - var x = 0; - var y = 0; - - for (var i = 0, j = 0; i <= n; ++i) { - j = i / n; - - // The Green Line - xa = getPt(fromX, cpX, j); - ya = getPt(fromY, cpY, j); - xb = getPt(cpX, toX, j); - yb = getPt(cpY, toY, j); - - // The Black Dot - x = getPt(xa, xb, j); - y = getPt(ya, yb, j); - - points.push(x, y); - } - - return points; -} - -},{"../../../utils":124,"./buildLine":61,"earcut":2}],65:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.autoDetectRenderer = exports.Application = exports.Filter = exports.SpriteMaskFilter = exports.Quad = exports.RenderTarget = exports.ObjectRenderer = exports.WebGLManager = exports.Shader = exports.CanvasRenderTarget = exports.TextureUvs = exports.VideoBaseTexture = exports.BaseRenderTexture = exports.RenderTexture = exports.BaseTexture = exports.Texture = exports.Spritesheet = exports.CanvasGraphicsRenderer = exports.GraphicsRenderer = exports.GraphicsData = exports.Graphics = exports.TextMetrics = exports.TextStyle = exports.Text = exports.SpriteRenderer = exports.CanvasTinter = exports.CanvasSpriteRenderer = exports.Sprite = exports.TransformBase = exports.TransformStatic = exports.Transform = exports.Container = exports.DisplayObject = exports.Bounds = exports.glCore = exports.WebGLRenderer = exports.CanvasRenderer = exports.ticker = exports.utils = exports.settings = undefined; - -var _const = require('./const'); - -Object.keys(_const).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _const[key]; - } - }); -}); - -var _math = require('./math'); - -Object.keys(_math).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _math[key]; - } - }); -}); - -var _pixiGlCore = require('pixi-gl-core'); - -Object.defineProperty(exports, 'glCore', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_pixiGlCore).default; - } -}); - -var _Bounds = require('./display/Bounds'); - -Object.defineProperty(exports, 'Bounds', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Bounds).default; - } -}); - -var _DisplayObject = require('./display/DisplayObject'); - -Object.defineProperty(exports, 'DisplayObject', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_DisplayObject).default; - } -}); - -var _Container = require('./display/Container'); - -Object.defineProperty(exports, 'Container', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Container).default; - } -}); - -var _Transform = require('./display/Transform'); - -Object.defineProperty(exports, 'Transform', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Transform).default; - } -}); - -var _TransformStatic = require('./display/TransformStatic'); - -Object.defineProperty(exports, 'TransformStatic', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_TransformStatic).default; - } -}); - -var _TransformBase = require('./display/TransformBase'); - -Object.defineProperty(exports, 'TransformBase', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_TransformBase).default; - } -}); - -var _Sprite = require('./sprites/Sprite'); - -Object.defineProperty(exports, 'Sprite', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Sprite).default; - } -}); - -var _CanvasSpriteRenderer = require('./sprites/canvas/CanvasSpriteRenderer'); - -Object.defineProperty(exports, 'CanvasSpriteRenderer', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_CanvasSpriteRenderer).default; - } -}); - -var _CanvasTinter = require('./sprites/canvas/CanvasTinter'); - -Object.defineProperty(exports, 'CanvasTinter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_CanvasTinter).default; - } -}); - -var _SpriteRenderer = require('./sprites/webgl/SpriteRenderer'); - -Object.defineProperty(exports, 'SpriteRenderer', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_SpriteRenderer).default; - } -}); - -var _Text = require('./text/Text'); - -Object.defineProperty(exports, 'Text', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Text).default; - } -}); - -var _TextStyle = require('./text/TextStyle'); - -Object.defineProperty(exports, 'TextStyle', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_TextStyle).default; - } -}); - -var _TextMetrics = require('./text/TextMetrics'); - -Object.defineProperty(exports, 'TextMetrics', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_TextMetrics).default; - } -}); - -var _Graphics = require('./graphics/Graphics'); - -Object.defineProperty(exports, 'Graphics', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Graphics).default; - } -}); - -var _GraphicsData = require('./graphics/GraphicsData'); - -Object.defineProperty(exports, 'GraphicsData', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_GraphicsData).default; - } -}); - -var _GraphicsRenderer = require('./graphics/webgl/GraphicsRenderer'); - -Object.defineProperty(exports, 'GraphicsRenderer', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_GraphicsRenderer).default; - } -}); - -var _CanvasGraphicsRenderer = require('./graphics/canvas/CanvasGraphicsRenderer'); - -Object.defineProperty(exports, 'CanvasGraphicsRenderer', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_CanvasGraphicsRenderer).default; - } -}); - -var _Spritesheet = require('./textures/Spritesheet'); - -Object.defineProperty(exports, 'Spritesheet', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Spritesheet).default; - } -}); - -var _Texture = require('./textures/Texture'); - -Object.defineProperty(exports, 'Texture', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Texture).default; - } -}); - -var _BaseTexture = require('./textures/BaseTexture'); - -Object.defineProperty(exports, 'BaseTexture', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_BaseTexture).default; - } -}); - -var _RenderTexture = require('./textures/RenderTexture'); - -Object.defineProperty(exports, 'RenderTexture', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_RenderTexture).default; - } -}); - -var _BaseRenderTexture = require('./textures/BaseRenderTexture'); - -Object.defineProperty(exports, 'BaseRenderTexture', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_BaseRenderTexture).default; - } -}); - -var _VideoBaseTexture = require('./textures/VideoBaseTexture'); - -Object.defineProperty(exports, 'VideoBaseTexture', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_VideoBaseTexture).default; - } -}); - -var _TextureUvs = require('./textures/TextureUvs'); - -Object.defineProperty(exports, 'TextureUvs', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_TextureUvs).default; - } -}); - -var _CanvasRenderTarget = require('./renderers/canvas/utils/CanvasRenderTarget'); - -Object.defineProperty(exports, 'CanvasRenderTarget', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_CanvasRenderTarget).default; - } -}); - -var _Shader = require('./Shader'); - -Object.defineProperty(exports, 'Shader', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Shader).default; - } -}); - -var _WebGLManager = require('./renderers/webgl/managers/WebGLManager'); - -Object.defineProperty(exports, 'WebGLManager', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_WebGLManager).default; - } -}); - -var _ObjectRenderer = require('./renderers/webgl/utils/ObjectRenderer'); - -Object.defineProperty(exports, 'ObjectRenderer', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_ObjectRenderer).default; - } -}); - -var _RenderTarget = require('./renderers/webgl/utils/RenderTarget'); - -Object.defineProperty(exports, 'RenderTarget', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_RenderTarget).default; - } -}); - -var _Quad = require('./renderers/webgl/utils/Quad'); - -Object.defineProperty(exports, 'Quad', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Quad).default; - } -}); - -var _SpriteMaskFilter = require('./renderers/webgl/filters/spriteMask/SpriteMaskFilter'); - -Object.defineProperty(exports, 'SpriteMaskFilter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_SpriteMaskFilter).default; - } -}); - -var _Filter = require('./renderers/webgl/filters/Filter'); - -Object.defineProperty(exports, 'Filter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Filter).default; - } -}); - -var _Application = require('./Application'); - -Object.defineProperty(exports, 'Application', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Application).default; - } -}); - -var _autoDetectRenderer = require('./autoDetectRenderer'); - -Object.defineProperty(exports, 'autoDetectRenderer', { - enumerable: true, - get: function get() { - return _autoDetectRenderer.autoDetectRenderer; - } -}); - -var _utils = require('./utils'); - -var utils = _interopRequireWildcard(_utils); - -var _ticker = require('./ticker'); - -var ticker = _interopRequireWildcard(_ticker); - -var _settings = require('./settings'); - -var _settings2 = _interopRequireDefault(_settings); - -var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); - -var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); - -var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); - -var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.settings = _settings2.default; -exports.utils = utils; -exports.ticker = ticker; -exports.CanvasRenderer = _CanvasRenderer2.default; -exports.WebGLRenderer = _WebGLRenderer2.default; /** - * @namespace PIXI - */ - -},{"./Application":43,"./Shader":44,"./autoDetectRenderer":45,"./const":46,"./display/Bounds":47,"./display/Container":48,"./display/DisplayObject":49,"./display/Transform":50,"./display/TransformBase":51,"./display/TransformStatic":52,"./graphics/Graphics":53,"./graphics/GraphicsData":54,"./graphics/canvas/CanvasGraphicsRenderer":55,"./graphics/webgl/GraphicsRenderer":57,"./math":70,"./renderers/canvas/CanvasRenderer":77,"./renderers/canvas/utils/CanvasRenderTarget":79,"./renderers/webgl/WebGLRenderer":84,"./renderers/webgl/filters/Filter":86,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":89,"./renderers/webgl/managers/WebGLManager":93,"./renderers/webgl/utils/ObjectRenderer":94,"./renderers/webgl/utils/Quad":95,"./renderers/webgl/utils/RenderTarget":96,"./settings":101,"./sprites/Sprite":102,"./sprites/canvas/CanvasSpriteRenderer":103,"./sprites/canvas/CanvasTinter":104,"./sprites/webgl/SpriteRenderer":106,"./text/Text":108,"./text/TextMetrics":109,"./text/TextStyle":110,"./textures/BaseRenderTexture":111,"./textures/BaseTexture":112,"./textures/RenderTexture":113,"./textures/Spritesheet":114,"./textures/Texture":115,"./textures/TextureUvs":116,"./textures/VideoBaseTexture":117,"./ticker":120,"./utils":124,"pixi-gl-core":12}],66:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _Matrix = require('./Matrix'); - -var _Matrix2 = _interopRequireDefault(_Matrix); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group of order 16 - -var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; -var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; -var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; -var tempMatrices = []; - -var mul = []; - -function signum(x) { - if (x < 0) { - return -1; - } - if (x > 0) { - return 1; - } - - return 0; -} - -function init() { - for (var i = 0; i < 16; i++) { - var row = []; - - mul.push(row); - - for (var j = 0; j < 16; j++) { - var _ux = signum(ux[i] * ux[j] + vx[i] * uy[j]); - var _uy = signum(uy[i] * ux[j] + vy[i] * uy[j]); - var _vx = signum(ux[i] * vx[j] + vx[i] * vy[j]); - var _vy = signum(uy[i] * vx[j] + vy[i] * vy[j]); - - for (var k = 0; k < 16; k++) { - if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) { - row.push(k); - break; - } - } - } - } - - for (var _i = 0; _i < 16; _i++) { - var mat = new _Matrix2.default(); - - mat.set(ux[_i], uy[_i], vx[_i], vy[_i], 0, 0); - tempMatrices.push(mat); - } -} - -init(); - -/** - * Implements Dihedral Group D_8, see [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}, - * D8 is the same but with diagonals. Used for texture rotations. - * - * Vector xX(i), xY(i) is U-axis of sprite with rotation i - * Vector yY(i), yY(i) is V-axis of sprite with rotation i - * Rotations: 0 grad (0), 90 grad (2), 180 grad (4), 270 grad (6) - * Mirrors: vertical (8), main diagonal (10), horizontal (12), reverse diagonal (14) - * This is the small part of gameofbombs.com portal system. It works. - * - * @author Ivan @ivanpopelyshev - * @class - * @memberof PIXI - */ -var GroupD8 = { - E: 0, - SE: 1, - S: 2, - SW: 3, - W: 4, - NW: 5, - N: 6, - NE: 7, - MIRROR_VERTICAL: 8, - MIRROR_HORIZONTAL: 12, - uX: function uX(ind) { - return ux[ind]; - }, - uY: function uY(ind) { - return uy[ind]; - }, - vX: function vX(ind) { - return vx[ind]; - }, - vY: function vY(ind) { - return vy[ind]; - }, - inv: function inv(rotation) { - if (rotation & 8) { - return rotation & 15; - } - - return -rotation & 7; - }, - add: function add(rotationSecond, rotationFirst) { - return mul[rotationSecond][rotationFirst]; - }, - sub: function sub(rotationSecond, rotationFirst) { - return mul[rotationSecond][GroupD8.inv(rotationFirst)]; - }, - - /** - * Adds 180 degrees to rotation. Commutative operation. - * - * @memberof PIXI.GroupD8 - * @param {number} rotation - The number to rotate. - * @returns {number} rotated number - */ - rotate180: function rotate180(rotation) { - return rotation ^ 4; - }, - - /** - * I dont know why sometimes width and heights needs to be swapped. We'll fix it later. - * - * @memberof PIXI.GroupD8 - * @param {number} rotation - The number to check. - * @returns {boolean} Whether or not the width/height should be swapped. - */ - isSwapWidthHeight: function isSwapWidthHeight(rotation) { - return (rotation & 3) === 2; - }, - - /** - * @memberof PIXI.GroupD8 - * @param {number} dx - TODO - * @param {number} dy - TODO - * - * @return {number} TODO - */ - byDirection: function byDirection(dx, dy) { - if (Math.abs(dx) * 2 <= Math.abs(dy)) { - if (dy >= 0) { - return GroupD8.S; - } - - return GroupD8.N; - } else if (Math.abs(dy) * 2 <= Math.abs(dx)) { - if (dx > 0) { - return GroupD8.E; - } - - return GroupD8.W; - } else if (dy > 0) { - if (dx > 0) { - return GroupD8.SE; - } - - return GroupD8.SW; - } else if (dx > 0) { - return GroupD8.NE; - } - - return GroupD8.NW; - }, - - /** - * Helps sprite to compensate texture packer rotation. - * - * @memberof PIXI.GroupD8 - * @param {PIXI.Matrix} matrix - sprite world matrix - * @param {number} rotation - The rotation factor to use. - * @param {number} tx - sprite anchoring - * @param {number} ty - sprite anchoring - */ - matrixAppendRotationInv: function matrixAppendRotationInv(matrix, rotation) { - var tx = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; - var ty = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; - - // Packer used "rotation", we use "inv(rotation)" - var mat = tempMatrices[GroupD8.inv(rotation)]; - - mat.tx = tx; - mat.ty = ty; - matrix.append(mat); - } -}; - -exports.default = GroupD8; - -},{"./Matrix":67}],67:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _Point = require('./Point'); - -var _Point2 = _interopRequireDefault(_Point); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * The PixiJS Matrix class as an object, which makes it a lot faster, - * here is a representation of it : - * | a | b | tx| - * | c | d | ty| - * | 0 | 0 | 1 | - * - * @class - * @memberof PIXI - */ -var Matrix = function () { - /** - * @param {number} [a=1] - x scale - * @param {number} [b=0] - y skew - * @param {number} [c=0] - x skew - * @param {number} [d=1] - y scale - * @param {number} [tx=0] - x translation - * @param {number} [ty=0] - y translation - */ - function Matrix() { - var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; - var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - var c = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; - var d = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; - var tx = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; - var ty = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; - - _classCallCheck(this, Matrix); - - /** - * @member {number} - * @default 1 - */ - this.a = a; - - /** - * @member {number} - * @default 0 - */ - this.b = b; - - /** - * @member {number} - * @default 0 - */ - this.c = c; - - /** - * @member {number} - * @default 1 - */ - this.d = d; - - /** - * @member {number} - * @default 0 - */ - this.tx = tx; - - /** - * @member {number} - * @default 0 - */ - this.ty = ty; - - this.array = null; - } - - /** - * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: - * - * a = array[0] - * b = array[1] - * c = array[3] - * d = array[4] - * tx = array[2] - * ty = array[5] - * - * @param {number[]} array - The array that the matrix will be populated from. - */ - - - Matrix.prototype.fromArray = function fromArray(array) { - this.a = array[0]; - this.b = array[1]; - this.c = array[3]; - this.d = array[4]; - this.tx = array[2]; - this.ty = array[5]; - }; - - /** - * sets the matrix properties - * - * @param {number} a - Matrix component - * @param {number} b - Matrix component - * @param {number} c - Matrix component - * @param {number} d - Matrix component - * @param {number} tx - Matrix component - * @param {number} ty - Matrix component - * - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. - */ - - - Matrix.prototype.set = function set(a, b, c, d, tx, ty) { - this.a = a; - this.b = b; - this.c = c; - this.d = d; - this.tx = tx; - this.ty = ty; - - return this; - }; - - /** - * Creates an array from the current Matrix object. - * - * @param {boolean} transpose - Whether we need to transpose the matrix or not - * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out - * @return {number[]} the newly created array which contains the matrix - */ - - - Matrix.prototype.toArray = function toArray(transpose, out) { - if (!this.array) { - this.array = new Float32Array(9); - } - - var array = out || this.array; - - if (transpose) { - array[0] = this.a; - array[1] = this.b; - array[2] = 0; - array[3] = this.c; - array[4] = this.d; - array[5] = 0; - array[6] = this.tx; - array[7] = this.ty; - array[8] = 1; - } else { - array[0] = this.a; - array[1] = this.c; - array[2] = this.tx; - array[3] = this.b; - array[4] = this.d; - array[5] = this.ty; - array[6] = 0; - array[7] = 0; - array[8] = 1; - } - - return array; - }; - - /** - * Get a new position with the current transformation applied. - * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) - * - * @param {PIXI.Point} pos - The origin - * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) - * @return {PIXI.Point} The new point, transformed through this matrix - */ - - - Matrix.prototype.apply = function apply(pos, newPos) { - newPos = newPos || new _Point2.default(); - - var x = pos.x; - var y = pos.y; - - newPos.x = this.a * x + this.c * y + this.tx; - newPos.y = this.b * x + this.d * y + this.ty; - - return newPos; - }; - - /** - * Get a new position with the inverse of the current transformation applied. - * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) - * - * @param {PIXI.Point} pos - The origin - * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) - * @return {PIXI.Point} The new point, inverse-transformed through this matrix - */ - - - Matrix.prototype.applyInverse = function applyInverse(pos, newPos) { - newPos = newPos || new _Point2.default(); - - var id = 1 / (this.a * this.d + this.c * -this.b); - - var x = pos.x; - var y = pos.y; - - newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; - newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; - - return newPos; - }; - - /** - * Translates the matrix on the x and y. - * - * @param {number} x How much to translate x by - * @param {number} y How much to translate y by - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. - */ - - - Matrix.prototype.translate = function translate(x, y) { - this.tx += x; - this.ty += y; - - return this; - }; - - /** - * Applies a scale transformation to the matrix. - * - * @param {number} x The amount to scale horizontally - * @param {number} y The amount to scale vertically - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. - */ - - - Matrix.prototype.scale = function scale(x, y) { - this.a *= x; - this.d *= y; - this.c *= x; - this.b *= y; - this.tx *= x; - this.ty *= y; - - return this; - }; - - /** - * Applies a rotation transformation to the matrix. - * - * @param {number} angle - The angle in radians. - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. - */ - - - Matrix.prototype.rotate = function rotate(angle) { - var cos = Math.cos(angle); - var sin = Math.sin(angle); - - var a1 = this.a; - var c1 = this.c; - var tx1 = this.tx; - - this.a = a1 * cos - this.b * sin; - this.b = a1 * sin + this.b * cos; - this.c = c1 * cos - this.d * sin; - this.d = c1 * sin + this.d * cos; - this.tx = tx1 * cos - this.ty * sin; - this.ty = tx1 * sin + this.ty * cos; - - return this; - }; - - /** - * Appends the given Matrix to this Matrix. - * - * @param {PIXI.Matrix} matrix - The matrix to append. - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. - */ - - - Matrix.prototype.append = function append(matrix) { - var a1 = this.a; - var b1 = this.b; - var c1 = this.c; - var d1 = this.d; - - this.a = matrix.a * a1 + matrix.b * c1; - this.b = matrix.a * b1 + matrix.b * d1; - this.c = matrix.c * a1 + matrix.d * c1; - this.d = matrix.c * b1 + matrix.d * d1; - - this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; - this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; - - return this; - }; - - /** - * Sets the matrix based on all the available properties - * - * @param {number} x - Position on the x axis - * @param {number} y - Position on the y axis - * @param {number} pivotX - Pivot on the x axis - * @param {number} pivotY - Pivot on the y axis - * @param {number} scaleX - Scale on the x axis - * @param {number} scaleY - Scale on the y axis - * @param {number} rotation - Rotation in radians - * @param {number} skewX - Skew on the x axis - * @param {number} skewY - Skew on the y axis - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. - */ - - - Matrix.prototype.setTransform = function setTransform(x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { - var sr = Math.sin(rotation); - var cr = Math.cos(rotation); - var cy = Math.cos(skewY); - var sy = Math.sin(skewY); - var nsx = -Math.sin(skewX); - var cx = Math.cos(skewX); - - var a = cr * scaleX; - var b = sr * scaleX; - var c = -sr * scaleY; - var d = cr * scaleY; - - this.a = cy * a + sy * c; - this.b = cy * b + sy * d; - this.c = nsx * a + cx * c; - this.d = nsx * b + cx * d; - - this.tx = x + (pivotX * a + pivotY * c); - this.ty = y + (pivotX * b + pivotY * d); - - return this; - }; - - /** - * Prepends the given Matrix to this Matrix. - * - * @param {PIXI.Matrix} matrix - The matrix to prepend - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. - */ - - - Matrix.prototype.prepend = function prepend(matrix) { - var tx1 = this.tx; - - if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { - var a1 = this.a; - var c1 = this.c; - - this.a = a1 * matrix.a + this.b * matrix.c; - this.b = a1 * matrix.b + this.b * matrix.d; - this.c = c1 * matrix.a + this.d * matrix.c; - this.d = c1 * matrix.b + this.d * matrix.d; - } - - this.tx = tx1 * matrix.a + this.ty * matrix.c + matrix.tx; - this.ty = tx1 * matrix.b + this.ty * matrix.d + matrix.ty; - - return this; - }; - - /** - * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. - * - * @param {PIXI.Transform|PIXI.TransformStatic} transform - The transform to apply the properties to. - * @return {PIXI.Transform|PIXI.TransformStatic} The transform with the newly applied properties - */ - - - Matrix.prototype.decompose = function decompose(transform) { - // sort out rotation / skew.. - var a = this.a; - var b = this.b; - var c = this.c; - var d = this.d; - - var skewX = -Math.atan2(-c, d); - var skewY = Math.atan2(b, a); - - var delta = Math.abs(skewX + skewY); - - if (delta < 0.00001) { - transform.rotation = skewY; - - if (a < 0 && d >= 0) { - transform.rotation += transform.rotation <= 0 ? Math.PI : -Math.PI; - } - - transform.skew.x = transform.skew.y = 0; - } else { - transform.skew.x = skewX; - transform.skew.y = skewY; - } - - // next set scale - transform.scale.x = Math.sqrt(a * a + b * b); - transform.scale.y = Math.sqrt(c * c + d * d); - - // next set position - transform.position.x = this.tx; - transform.position.y = this.ty; - - return transform; - }; - - /** - * Inverts this matrix - * - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. - */ - - - Matrix.prototype.invert = function invert() { - var a1 = this.a; - var b1 = this.b; - var c1 = this.c; - var d1 = this.d; - var tx1 = this.tx; - var n = a1 * d1 - b1 * c1; - - this.a = d1 / n; - this.b = -b1 / n; - this.c = -c1 / n; - this.d = a1 / n; - this.tx = (c1 * this.ty - d1 * tx1) / n; - this.ty = -(a1 * this.ty - b1 * tx1) / n; - - return this; - }; - - /** - * Resets this Matix to an identity (default) matrix. - * - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. - */ - - - Matrix.prototype.identity = function identity() { - this.a = 1; - this.b = 0; - this.c = 0; - this.d = 1; - this.tx = 0; - this.ty = 0; - - return this; - }; - - /** - * Creates a new Matrix object with the same values as this one. - * - * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. - */ - - - Matrix.prototype.clone = function clone() { - var matrix = new Matrix(); - - matrix.a = this.a; - matrix.b = this.b; - matrix.c = this.c; - matrix.d = this.d; - matrix.tx = this.tx; - matrix.ty = this.ty; - - return matrix; - }; - - /** - * Changes the values of the given matrix to be the same as the ones in this matrix - * - * @param {PIXI.Matrix} matrix - The matrix to copy from. - * @return {PIXI.Matrix} The matrix given in parameter with its values updated. - */ - - - Matrix.prototype.copy = function copy(matrix) { - matrix.a = this.a; - matrix.b = this.b; - matrix.c = this.c; - matrix.d = this.d; - matrix.tx = this.tx; - matrix.ty = this.ty; - - return matrix; - }; - - /** - * A default (identity) matrix - * - * @static - * @const - */ - - - _createClass(Matrix, null, [{ - key: 'IDENTITY', - get: function get() { - return new Matrix(); - } - - /** - * A temp matrix - * - * @static - * @const - */ - - }, { - key: 'TEMP_MATRIX', - get: function get() { - return new Matrix(); - } - }]); - - return Matrix; -}(); - -exports.default = Matrix; - -},{"./Point":69}],68:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * The Point object represents a location in a two-dimensional coordinate system, where x represents - * the horizontal axis and y represents the vertical axis. - * An observable point is a point that triggers a callback when the point's position is changed. - * - * @class - * @memberof PIXI - */ -var ObservablePoint = function () { - /** - * @param {Function} cb - callback when changed - * @param {object} scope - owner of callback - * @param {number} [x=0] - position of the point on the x axis - * @param {number} [y=0] - position of the point on the y axis - */ - function ObservablePoint(cb, scope) { - var x = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; - var y = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; - - _classCallCheck(this, ObservablePoint); - - this._x = x; - this._y = y; - - this.cb = cb; - this.scope = scope; - } - - /** - * Sets the point to a new x and y position. - * If y is omitted, both x and y will be set to x. - * - * @param {number} [x=0] - position of the point on the x axis - * @param {number} [y=0] - position of the point on the y axis - */ - - - ObservablePoint.prototype.set = function set(x, y) { - var _x = x || 0; - var _y = y || (y !== 0 ? _x : 0); - - if (this._x !== _x || this._y !== _y) { - this._x = _x; - this._y = _y; - this.cb.call(this.scope); - } - }; - - /** - * Copies the data from another point - * - * @param {PIXI.Point|PIXI.ObservablePoint} point - point to copy from - */ - - - ObservablePoint.prototype.copy = function copy(point) { - if (this._x !== point.x || this._y !== point.y) { - this._x = point.x; - this._y = point.y; - this.cb.call(this.scope); - } - }; - - /** - * The position of the displayObject on the x axis relative to the local coordinates of the parent. - * - * @member {number} - */ - - - _createClass(ObservablePoint, [{ - key: "x", - get: function get() { - return this._x; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - if (this._x !== value) { - this._x = value; - this.cb.call(this.scope); - } - } - - /** - * The position of the displayObject on the x axis relative to the local coordinates of the parent. - * - * @member {number} - */ - - }, { - key: "y", - get: function get() { - return this._y; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - if (this._y !== value) { - this._y = value; - this.cb.call(this.scope); - } - } - }]); - - return ObservablePoint; -}(); - -exports.default = ObservablePoint; - -},{}],69:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * The Point object represents a location in a two-dimensional coordinate system, where x represents - * the horizontal axis and y represents the vertical axis. - * - * @class - * @memberof PIXI - */ -var Point = function () { - /** - * @param {number} [x=0] - position of the point on the x axis - * @param {number} [y=0] - position of the point on the y axis - */ - function Point() { - var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - - _classCallCheck(this, Point); - - /** - * @member {number} - * @default 0 - */ - this.x = x; - - /** - * @member {number} - * @default 0 - */ - this.y = y; - } - - /** - * Creates a clone of this point - * - * @return {PIXI.Point} a copy of the point - */ - - - Point.prototype.clone = function clone() { - return new Point(this.x, this.y); - }; - - /** - * Copies x and y from the given point - * - * @param {PIXI.Point} p - The point to copy. - */ - - - Point.prototype.copy = function copy(p) { - this.set(p.x, p.y); - }; - - /** - * Returns true if the given point is equal to this point - * - * @param {PIXI.Point} p - The point to check - * @returns {boolean} Whether the given point equal to this point - */ - - - Point.prototype.equals = function equals(p) { - return p.x === this.x && p.y === this.y; - }; - - /** - * Sets the point to a new x and y position. - * If y is omitted, both x and y will be set to x. - * - * @param {number} [x=0] - position of the point on the x axis - * @param {number} [y=0] - position of the point on the y axis - */ - - - Point.prototype.set = function set(x, y) { - this.x = x || 0; - this.y = y || (y !== 0 ? this.x : 0); - }; - - return Point; -}(); - -exports.default = Point; - -},{}],70:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _Point = require('./Point'); - -Object.defineProperty(exports, 'Point', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Point).default; - } -}); - -var _ObservablePoint = require('./ObservablePoint'); - -Object.defineProperty(exports, 'ObservablePoint', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_ObservablePoint).default; - } -}); - -var _Matrix = require('./Matrix'); - -Object.defineProperty(exports, 'Matrix', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Matrix).default; - } -}); - -var _GroupD = require('./GroupD8'); - -Object.defineProperty(exports, 'GroupD8', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_GroupD).default; - } -}); - -var _Circle = require('./shapes/Circle'); - -Object.defineProperty(exports, 'Circle', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Circle).default; - } -}); - -var _Ellipse = require('./shapes/Ellipse'); - -Object.defineProperty(exports, 'Ellipse', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Ellipse).default; - } -}); - -var _Polygon = require('./shapes/Polygon'); - -Object.defineProperty(exports, 'Polygon', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Polygon).default; - } -}); - -var _Rectangle = require('./shapes/Rectangle'); - -Object.defineProperty(exports, 'Rectangle', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Rectangle).default; - } -}); - -var _RoundedRectangle = require('./shapes/RoundedRectangle'); - -Object.defineProperty(exports, 'RoundedRectangle', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_RoundedRectangle).default; - } -}); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -},{"./GroupD8":66,"./Matrix":67,"./ObservablePoint":68,"./Point":69,"./shapes/Circle":71,"./shapes/Ellipse":72,"./shapes/Polygon":73,"./shapes/Rectangle":74,"./shapes/RoundedRectangle":75}],71:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _Rectangle = require('./Rectangle'); - -var _Rectangle2 = _interopRequireDefault(_Rectangle); - -var _const = require('../../const'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * The Circle object can be used to specify a hit area for displayObjects - * - * @class - * @memberof PIXI - */ -var Circle = function () { - /** - * @param {number} [x=0] - The X coordinate of the center of this circle - * @param {number} [y=0] - The Y coordinate of the center of this circle - * @param {number} [radius=0] - The radius of the circle - */ - function Circle() { - var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - var radius = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; - - _classCallCheck(this, Circle); - - /** - * @member {number} - * @default 0 - */ - this.x = x; - - /** - * @member {number} - * @default 0 - */ - this.y = y; - - /** - * @member {number} - * @default 0 - */ - this.radius = radius; - - /** - * The type of the object, mainly used to avoid `instanceof` checks - * - * @member {number} - * @readOnly - * @default PIXI.SHAPES.CIRC - * @see PIXI.SHAPES - */ - this.type = _const.SHAPES.CIRC; - } - - /** - * Creates a clone of this Circle instance - * - * @return {PIXI.Circle} a copy of the Circle - */ - - - Circle.prototype.clone = function clone() { - return new Circle(this.x, this.y, this.radius); - }; - - /** - * Checks whether the x and y coordinates given are contained within this circle - * - * @param {number} x - The X coordinate of the point to test - * @param {number} y - The Y coordinate of the point to test - * @return {boolean} Whether the x/y coordinates are within this Circle - */ - - - Circle.prototype.contains = function contains(x, y) { - if (this.radius <= 0) { - return false; - } - - var r2 = this.radius * this.radius; - var dx = this.x - x; - var dy = this.y - y; - - dx *= dx; - dy *= dy; - - return dx + dy <= r2; - }; - - /** - * Returns the framing rectangle of the circle as a Rectangle object - * - * @return {PIXI.Rectangle} the framing rectangle - */ - - - Circle.prototype.getBounds = function getBounds() { - return new _Rectangle2.default(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); - }; - - return Circle; -}(); - -exports.default = Circle; - -},{"../../const":46,"./Rectangle":74}],72:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _Rectangle = require('./Rectangle'); - -var _Rectangle2 = _interopRequireDefault(_Rectangle); - -var _const = require('../../const'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * The Ellipse object can be used to specify a hit area for displayObjects - * - * @class - * @memberof PIXI - */ -var Ellipse = function () { - /** - * @param {number} [x=0] - The X coordinate of the center of this circle - * @param {number} [y=0] - The Y coordinate of the center of this circle - * @param {number} [width=0] - The half width of this ellipse - * @param {number} [height=0] - The half height of this ellipse - */ - function Ellipse() { - var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; - var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; - - _classCallCheck(this, Ellipse); - - /** - * @member {number} - * @default 0 - */ - this.x = x; - - /** - * @member {number} - * @default 0 - */ - this.y = y; - - /** - * @member {number} - * @default 0 - */ - this.width = width; - - /** - * @member {number} - * @default 0 - */ - this.height = height; - - /** - * The type of the object, mainly used to avoid `instanceof` checks - * - * @member {number} - * @readOnly - * @default PIXI.SHAPES.ELIP - * @see PIXI.SHAPES - */ - this.type = _const.SHAPES.ELIP; - } - - /** - * Creates a clone of this Ellipse instance - * - * @return {PIXI.Ellipse} a copy of the ellipse - */ - - - Ellipse.prototype.clone = function clone() { - return new Ellipse(this.x, this.y, this.width, this.height); - }; - - /** - * Checks whether the x and y coordinates given are contained within this ellipse - * - * @param {number} x - The X coordinate of the point to test - * @param {number} y - The Y coordinate of the point to test - * @return {boolean} Whether the x/y coords are within this ellipse - */ - - - Ellipse.prototype.contains = function contains(x, y) { - if (this.width <= 0 || this.height <= 0) { - return false; - } - - // normalize the coords to an ellipse with center 0,0 - var normx = (x - this.x) / this.width; - var normy = (y - this.y) / this.height; - - normx *= normx; - normy *= normy; - - return normx + normy <= 1; - }; - - /** - * Returns the framing rectangle of the ellipse as a Rectangle object - * - * @return {PIXI.Rectangle} the framing rectangle - */ - - - Ellipse.prototype.getBounds = function getBounds() { - return new _Rectangle2.default(this.x - this.width, this.y - this.height, this.width, this.height); - }; - - return Ellipse; -}(); - -exports.default = Ellipse; - -},{"../../const":46,"./Rectangle":74}],73:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _Point = require('../Point'); - -var _Point2 = _interopRequireDefault(_Point); - -var _const = require('../../const'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * @class - * @memberof PIXI - */ -var Polygon = function () { - /** - * @param {PIXI.Point[]|number[]} points - This can be an array of Points - * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or - * the arguments passed can be all the points of the polygon e.g. - * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat - * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. - */ - function Polygon() { - for (var _len = arguments.length, points = Array(_len), _key = 0; _key < _len; _key++) { - points[_key] = arguments[_key]; - } - - _classCallCheck(this, Polygon); - - if (Array.isArray(points[0])) { - points = points[0]; - } - - // if this is an array of points, convert it to a flat array of numbers - if (points[0] instanceof _Point2.default) { - var p = []; - - for (var i = 0, il = points.length; i < il; i++) { - p.push(points[i].x, points[i].y); - } - - points = p; - } - - this.closed = true; - - /** - * An array of the points of this polygon - * - * @member {number[]} - */ - this.points = points; - - /** - * The type of the object, mainly used to avoid `instanceof` checks - * - * @member {number} - * @readOnly - * @default PIXI.SHAPES.POLY - * @see PIXI.SHAPES - */ - this.type = _const.SHAPES.POLY; - } - - /** - * Creates a clone of this polygon - * - * @return {PIXI.Polygon} a copy of the polygon - */ - - - Polygon.prototype.clone = function clone() { - return new Polygon(this.points.slice()); - }; - - /** - * Closes the polygon, adding points if necessary. - * - */ - - - Polygon.prototype.close = function close() { - var points = this.points; - - // close the poly if the value is true! - if (points[0] !== points[points.length - 2] || points[1] !== points[points.length - 1]) { - points.push(points[0], points[1]); - } - }; - - /** - * Checks whether the x and y coordinates passed to this function are contained within this polygon - * - * @param {number} x - The X coordinate of the point to test - * @param {number} y - The Y coordinate of the point to test - * @return {boolean} Whether the x/y coordinates are within this polygon - */ - - - Polygon.prototype.contains = function contains(x, y) { - var inside = false; - - // use some raycasting to test hits - // https://github.com/substack/point-in-polygon/blob/master/index.js - var length = this.points.length / 2; - - for (var i = 0, j = length - 1; i < length; j = i++) { - var xi = this.points[i * 2]; - var yi = this.points[i * 2 + 1]; - var xj = this.points[j * 2]; - var yj = this.points[j * 2 + 1]; - var intersect = yi > y !== yj > y && x < (xj - xi) * ((y - yi) / (yj - yi)) + xi; - - if (intersect) { - inside = !inside; - } - } - - return inside; - }; - - return Polygon; -}(); - -exports.default = Polygon; - -},{"../../const":46,"../Point":69}],74:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _const = require('../../const'); - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * Rectangle object is an area defined by its position, as indicated by its top-left corner - * point (x, y) and by its width and its height. - * - * @class - * @memberof PIXI - */ -var Rectangle = function () { - /** - * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle - * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle - * @param {number} [width=0] - The overall width of this rectangle - * @param {number} [height=0] - The overall height of this rectangle - */ - function Rectangle() { - var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; - var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; - - _classCallCheck(this, Rectangle); - - /** - * @member {number} - * @default 0 - */ - this.x = Number(x); - - /** - * @member {number} - * @default 0 - */ - this.y = Number(y); - - /** - * @member {number} - * @default 0 - */ - this.width = Number(width); - - /** - * @member {number} - * @default 0 - */ - this.height = Number(height); - - /** - * The type of the object, mainly used to avoid `instanceof` checks - * - * @member {number} - * @readOnly - * @default PIXI.SHAPES.RECT - * @see PIXI.SHAPES - */ - this.type = _const.SHAPES.RECT; - } - - /** - * returns the left edge of the rectangle - * - * @member {number} - */ - - - /** - * Creates a clone of this Rectangle - * - * @return {PIXI.Rectangle} a copy of the rectangle - */ - Rectangle.prototype.clone = function clone() { - return new Rectangle(this.x, this.y, this.width, this.height); - }; - - /** - * Copies another rectangle to this one. - * - * @param {PIXI.Rectangle} rectangle - The rectangle to copy. - * @return {PIXI.Rectangle} Returns itself. - */ - - - Rectangle.prototype.copy = function copy(rectangle) { - this.x = rectangle.x; - this.y = rectangle.y; - this.width = rectangle.width; - this.height = rectangle.height; - - return this; - }; - - /** - * Checks whether the x and y coordinates given are contained within this Rectangle - * - * @param {number} x - The X coordinate of the point to test - * @param {number} y - The Y coordinate of the point to test - * @return {boolean} Whether the x/y coordinates are within this Rectangle - */ - - - Rectangle.prototype.contains = function contains(x, y) { - if (this.width <= 0 || this.height <= 0) { - return false; - } - - if (x >= this.x && x < this.x + this.width) { - if (y >= this.y && y < this.y + this.height) { - return true; - } - } - - return false; - }; - - /** - * Pads the rectangle making it grow in all directions. - * - * @param {number} paddingX - The horizontal padding amount. - * @param {number} paddingY - The vertical padding amount. - */ - - - Rectangle.prototype.pad = function pad(paddingX, paddingY) { - paddingX = paddingX || 0; - paddingY = paddingY || (paddingY !== 0 ? paddingX : 0); - - this.x -= paddingX; - this.y -= paddingY; - - this.width += paddingX * 2; - this.height += paddingY * 2; - }; - - /** - * Fits this rectangle around the passed one. - * - * @param {PIXI.Rectangle} rectangle - The rectangle to fit. - */ - - - Rectangle.prototype.fit = function fit(rectangle) { - if (this.x < rectangle.x) { - this.width += this.x; - if (this.width < 0) { - this.width = 0; - } - - this.x = rectangle.x; - } - - if (this.y < rectangle.y) { - this.height += this.y; - if (this.height < 0) { - this.height = 0; - } - this.y = rectangle.y; - } - - if (this.x + this.width > rectangle.x + rectangle.width) { - this.width = rectangle.width - this.x; - if (this.width < 0) { - this.width = 0; - } - } - - if (this.y + this.height > rectangle.y + rectangle.height) { - this.height = rectangle.height - this.y; - if (this.height < 0) { - this.height = 0; - } - } - }; - - /** - * Enlarges this rectangle to include the passed rectangle. - * - * @param {PIXI.Rectangle} rectangle - The rectangle to include. - */ - - - Rectangle.prototype.enlarge = function enlarge(rectangle) { - var x1 = Math.min(this.x, rectangle.x); - var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); - var y1 = Math.min(this.y, rectangle.y); - var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); - - this.x = x1; - this.width = x2 - x1; - this.y = y1; - this.height = y2 - y1; - }; - - _createClass(Rectangle, [{ - key: 'left', - get: function get() { - return this.x; - } - - /** - * returns the right edge of the rectangle - * - * @member {number} - */ - - }, { - key: 'right', - get: function get() { - return this.x + this.width; - } - - /** - * returns the top edge of the rectangle - * - * @member {number} - */ - - }, { - key: 'top', - get: function get() { - return this.y; - } - - /** - * returns the bottom edge of the rectangle - * - * @member {number} - */ - - }, { - key: 'bottom', - get: function get() { - return this.y + this.height; - } - - /** - * A constant empty rectangle. - * - * @static - * @constant - */ - - }], [{ - key: 'EMPTY', - get: function get() { - return new Rectangle(0, 0, 0, 0); - } - }]); - - return Rectangle; -}(); - -exports.default = Rectangle; - -},{"../../const":46}],75:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _const = require('../../const'); - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its - * top-left corner point (x, y) and by its width and its height and its radius. - * - * @class - * @memberof PIXI - */ -var RoundedRectangle = function () { - /** - * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle - * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle - * @param {number} [width=0] - The overall width of this rounded rectangle - * @param {number} [height=0] - The overall height of this rounded rectangle - * @param {number} [radius=20] - Controls the radius of the rounded corners - */ - function RoundedRectangle() { - var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; - var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; - var radius = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 20; - - _classCallCheck(this, RoundedRectangle); - - /** - * @member {number} - * @default 0 - */ - this.x = x; - - /** - * @member {number} - * @default 0 - */ - this.y = y; - - /** - * @member {number} - * @default 0 - */ - this.width = width; - - /** - * @member {number} - * @default 0 - */ - this.height = height; - - /** - * @member {number} - * @default 20 - */ - this.radius = radius; - - /** - * The type of the object, mainly used to avoid `instanceof` checks - * - * @member {number} - * @readonly - * @default PIXI.SHAPES.RREC - * @see PIXI.SHAPES - */ - this.type = _const.SHAPES.RREC; - } - - /** - * Creates a clone of this Rounded Rectangle - * - * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle - */ - - - RoundedRectangle.prototype.clone = function clone() { - return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); - }; - - /** - * Checks whether the x and y coordinates given are contained within this Rounded Rectangle - * - * @param {number} x - The X coordinate of the point to test - * @param {number} y - The Y coordinate of the point to test - * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle - */ - - - RoundedRectangle.prototype.contains = function contains(x, y) { - if (this.width <= 0 || this.height <= 0) { - return false; - } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { - if (y >= this.y + this.radius && y <= this.y + this.height - this.radius || x >= this.x + this.radius && x <= this.x + this.width - this.radius) { - return true; - } - var dx = x - (this.x + this.radius); - var dy = y - (this.y + this.radius); - var radius2 = this.radius * this.radius; - - if (dx * dx + dy * dy <= radius2) { - return true; - } - dx = x - (this.x + this.width - this.radius); - if (dx * dx + dy * dy <= radius2) { - return true; - } - dy = y - (this.y + this.height - this.radius); - if (dx * dx + dy * dy <= radius2) { - return true; - } - dx = x - (this.x + this.radius); - if (dx * dx + dy * dy <= radius2) { - return true; - } - } - } - - return false; - }; - - return RoundedRectangle; -}(); - -exports.default = RoundedRectangle; - -},{"../../const":46}],76:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _utils = require('../utils'); - -var _math = require('../math'); - -var _const = require('../const'); - -var _settings = require('../settings'); - -var _settings2 = _interopRequireDefault(_settings); - -var _Container = require('../display/Container'); - -var _Container2 = _interopRequireDefault(_Container); - -var _RenderTexture = require('../textures/RenderTexture'); - -var _RenderTexture2 = _interopRequireDefault(_RenderTexture); - -var _eventemitter = require('eventemitter3'); - -var _eventemitter2 = _interopRequireDefault(_eventemitter); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -var tempMatrix = new _math.Matrix(); - -/** - * The SystemRenderer is the base for a PixiJS Renderer. It is extended by the {@link PIXI.CanvasRenderer} - * and {@link PIXI.WebGLRenderer} which can be used for rendering a PixiJS scene. - * - * @abstract - * @class - * @extends EventEmitter - * @memberof PIXI - */ - -var SystemRenderer = function (_EventEmitter) { - _inherits(SystemRenderer, _EventEmitter); - - // eslint-disable-next-line valid-jsdoc - /** - * @param {string} system - The name of the system this renderer is for. - * @param {object} [options] - The optional renderer parameters - * @param {number} [options.width=800] - the width of the screen - * @param {number} [options.height=600] - the height of the screen - * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional - * @param {boolean} [options.transparent=false] - If the render view is transparent, default false - * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false - * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) - * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The - * resolution of the renderer retina would be 2. - * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, - * enable this if you need to call toDataUrl on the webgl context. - * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or - * not before the new render pass. - * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area - * (shown if not transparent). - * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, - * stopping pixel interpolation. - */ - function SystemRenderer(system, options, arg2, arg3) { - _classCallCheck(this, SystemRenderer); - - var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); - - (0, _utils.sayHello)(system); - - // Support for constructor(system, screenWidth, screenHeight, options) - if (typeof options === 'number') { - options = Object.assign({ - width: options, - height: arg2 || _settings2.default.RENDER_OPTIONS.height - }, arg3); - } - - // Add the default render options - options = Object.assign({}, _settings2.default.RENDER_OPTIONS, options); - - /** - * The supplied constructor options. - * - * @member {Object} - * @readOnly - */ - _this.options = options; - - /** - * The type of the renderer. - * - * @member {number} - * @default PIXI.RENDERER_TYPE.UNKNOWN - * @see PIXI.RENDERER_TYPE - */ - _this.type = _const.RENDERER_TYPE.UNKNOWN; - - /** - * Measurements of the screen. (0, 0, screenWidth, screenHeight) - * - * Its safe to use as filterArea or hitArea for whole stage - * - * @member {PIXI.Rectangle} - */ - _this.screen = new _math.Rectangle(0, 0, options.width, options.height); - - /** - * The canvas element that everything is drawn to - * - * @member {HTMLCanvasElement} - */ - _this.view = options.view || document.createElement('canvas'); - - /** - * The resolution / device pixel ratio of the renderer - * - * @member {number} - * @default 1 - */ - _this.resolution = options.resolution || _settings2.default.RESOLUTION; - - /** - * Whether the render view is transparent - * - * @member {boolean} - */ - _this.transparent = options.transparent; - - /** - * Whether css dimensions of canvas view should be resized to screen dimensions automatically - * - * @member {boolean} - */ - _this.autoResize = options.autoResize || false; - - /** - * Tracks the blend modes useful for this renderer. - * - * @member {object} - */ - _this.blendModes = null; - - /** - * The value of the preserveDrawingBuffer flag affects whether or not the contents of - * the stencil buffer is retained after rendering. - * - * @member {boolean} - */ - _this.preserveDrawingBuffer = options.preserveDrawingBuffer; - - /** - * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. - * If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every - * frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect - * to clear the canvas every frame. Disable this by setting this to false. For example if - * your game has a canvas filling background image you often don't need this set. - * - * @member {boolean} - * @default - */ - _this.clearBeforeRender = options.clearBeforeRender; - - /** - * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. - * Handy for crisp pixel art and speed on legacy devices. - * - * @member {boolean} - */ - _this.roundPixels = options.roundPixels; - - /** - * The background color as a number. - * - * @member {number} - * @private - */ - _this._backgroundColor = 0x000000; - - /** - * The background color as an [R, G, B] array. - * - * @member {number[]} - * @private - */ - _this._backgroundColorRgba = [0, 0, 0, 0]; - - /** - * The background color as a string. - * - * @member {string} - * @private - */ - _this._backgroundColorString = '#000000'; - - _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter - - /** - * This temporary display object used as the parent of the currently being rendered item - * - * @member {PIXI.DisplayObject} - * @private - */ - _this._tempDisplayObjectParent = new _Container2.default(); - - /** - * The last root object that the renderer tried to render. - * - * @member {PIXI.DisplayObject} - * @private - */ - _this._lastObjectRendered = _this._tempDisplayObjectParent; - return _this; - } - - /** - * Same as view.width, actual number of pixels in the canvas by horizontal - * - * @member {number} - * @readonly - * @default 800 - */ - - - /** - * Resizes the screen and canvas to the specified width and height - * Canvas dimensions are multiplied by resolution - * - * @param {number} screenWidth - the new width of the screen - * @param {number} screenHeight - the new height of the screen - */ - SystemRenderer.prototype.resize = function resize(screenWidth, screenHeight) { - this.screen.width = screenWidth; - this.screen.height = screenHeight; - - this.view.width = screenWidth * this.resolution; - this.view.height = screenHeight * this.resolution; - - if (this.autoResize) { - this.view.style.width = screenWidth + 'px'; - this.view.style.height = screenHeight + 'px'; - } - }; - - /** - * Useful function that returns a texture of the display object that can then be used to create sprites - * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. - * - * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from - * @param {number} scaleMode - Should be one of the scaleMode consts - * @param {number} resolution - The resolution / device pixel ratio of the texture being generated - * @return {PIXI.Texture} a texture of the graphics object - */ - - - SystemRenderer.prototype.generateTexture = function generateTexture(displayObject, scaleMode, resolution) { - var bounds = displayObject.getLocalBounds(); - - var renderTexture = _RenderTexture2.default.create(bounds.width | 0, bounds.height | 0, scaleMode, resolution); - - tempMatrix.tx = -bounds.x; - tempMatrix.ty = -bounds.y; - - this.render(displayObject, renderTexture, false, tempMatrix, true); - - return renderTexture; - }; - - /** - * Removes everything from the renderer and optionally removes the Canvas DOM element. - * - * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. - */ - - - SystemRenderer.prototype.destroy = function destroy(removeView) { - if (removeView && this.view.parentNode) { - this.view.parentNode.removeChild(this.view); - } - - this.type = _const.RENDERER_TYPE.UNKNOWN; - - this.view = null; - - this.screen = null; - - this.resolution = 0; - - this.transparent = false; - - this.autoResize = false; - - this.blendModes = null; - - this.options = null; - - this.preserveDrawingBuffer = false; - this.clearBeforeRender = false; - - this.roundPixels = false; - - this._backgroundColor = 0; - this._backgroundColorRgba = null; - this._backgroundColorString = null; - - this._tempDisplayObjectParent = null; - this._lastObjectRendered = null; - }; - - /** - * The background color to fill if not transparent - * - * @member {number} - */ - - - _createClass(SystemRenderer, [{ - key: 'width', - get: function get() { - return this.view.width; - } - - /** - * Same as view.height, actual number of pixels in the canvas by vertical - * - * @member {number} - * @readonly - * @default 600 - */ - - }, { - key: 'height', - get: function get() { - return this.view.height; - } - }, { - key: 'backgroundColor', - get: function get() { - return this._backgroundColor; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._backgroundColor = value; - this._backgroundColorString = (0, _utils.hex2string)(value); - (0, _utils.hex2rgb)(value, this._backgroundColorRgba); - } - }]); - - return SystemRenderer; -}(_eventemitter2.default); - -exports.default = SystemRenderer; - -},{"../const":46,"../display/Container":48,"../math":70,"../settings":101,"../textures/RenderTexture":113,"../utils":124,"eventemitter3":3}],77:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _SystemRenderer2 = require('../SystemRenderer'); - -var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); - -var _CanvasMaskManager = require('./utils/CanvasMaskManager'); - -var _CanvasMaskManager2 = _interopRequireDefault(_CanvasMaskManager); - -var _CanvasRenderTarget = require('./utils/CanvasRenderTarget'); - -var _CanvasRenderTarget2 = _interopRequireDefault(_CanvasRenderTarget); - -var _mapCanvasBlendModesToPixi = require('./utils/mapCanvasBlendModesToPixi'); - -var _mapCanvasBlendModesToPixi2 = _interopRequireDefault(_mapCanvasBlendModesToPixi); - -var _utils = require('../../utils'); - -var _const = require('../../const'); - -var _settings = require('../../settings'); - -var _settings2 = _interopRequireDefault(_settings); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should - * be used for browsers that do not support WebGL. Don't forget to add the CanvasRenderer.view to - * your DOM or you will not see anything :) - * - * @class - * @memberof PIXI - * @extends PIXI.SystemRenderer - */ -var CanvasRenderer = function (_SystemRenderer) { - _inherits(CanvasRenderer, _SystemRenderer); - - // eslint-disable-next-line valid-jsdoc - /** - * @param {object} [options] - The optional renderer parameters - * @param {number} [options.width=800] - the width of the screen - * @param {number} [options.height=600] - the height of the screen - * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional - * @param {boolean} [options.transparent=false] - If the render view is transparent, default false - * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false - * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) - * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The - * resolution of the renderer retina would be 2. - * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, - * enable this if you need to call toDataUrl on the webgl context. - * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or - * not before the new render pass. - * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area - * (shown if not transparent). - * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, - * stopping pixel interpolation. - */ - function CanvasRenderer(options, arg2, arg3) { - _classCallCheck(this, CanvasRenderer); - - var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'Canvas', options, arg2, arg3)); - - _this.type = _const.RENDERER_TYPE.CANVAS; - - /** - * The root canvas 2d context that everything is drawn with. - * - * @member {CanvasRenderingContext2D} - */ - _this.rootContext = _this.view.getContext('2d', { alpha: _this.transparent }); - - /** - * The currently active canvas 2d context (could change with renderTextures) - * - * @member {CanvasRenderingContext2D} - */ - _this.context = _this.rootContext; - - /** - * Boolean flag controlling canvas refresh. - * - * @member {boolean} - */ - _this.refresh = true; - - /** - * Instance of a CanvasMaskManager, handles masking when using the canvas renderer. - * - * @member {PIXI.CanvasMaskManager} - */ - _this.maskManager = new _CanvasMaskManager2.default(_this); - - /** - * The canvas property used to set the canvas smoothing property. - * - * @member {string} - */ - _this.smoothProperty = 'imageSmoothingEnabled'; - - if (!_this.rootContext.imageSmoothingEnabled) { - if (_this.rootContext.webkitImageSmoothingEnabled) { - _this.smoothProperty = 'webkitImageSmoothingEnabled'; - } else if (_this.rootContext.mozImageSmoothingEnabled) { - _this.smoothProperty = 'mozImageSmoothingEnabled'; - } else if (_this.rootContext.oImageSmoothingEnabled) { - _this.smoothProperty = 'oImageSmoothingEnabled'; - } else if (_this.rootContext.msImageSmoothingEnabled) { - _this.smoothProperty = 'msImageSmoothingEnabled'; - } - } - - _this.initPlugins(); - - _this.blendModes = (0, _mapCanvasBlendModesToPixi2.default)(); - _this._activeBlendMode = null; - - _this.renderingToScreen = false; - - _this.resize(_this.options.width, _this.options.height); - - /** - * Fired after rendering finishes. - * - * @event PIXI.CanvasRenderer#postrender - */ - - /** - * Fired before rendering starts. - * - * @event PIXI.CanvasRenderer#prerender - */ - return _this; - } - - /** - * Renders the object to this canvas view - * - * @param {PIXI.DisplayObject} displayObject - The object to be rendered - * @param {PIXI.RenderTexture} [renderTexture] - A render texture to be rendered to. - * If unset, it will render to the root context. - * @param {boolean} [clear=false] - Whether to clear the canvas before drawing - * @param {PIXI.Transform} [transform] - A transformation to be applied - * @param {boolean} [skipUpdateTransform=false] - Whether to skip the update transform - */ - - - CanvasRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { - if (!this.view) { - return; - } - - // can be handy to know! - this.renderingToScreen = !renderTexture; - - this.emit('prerender'); - - var rootResolution = this.resolution; - - if (renderTexture) { - renderTexture = renderTexture.baseTexture || renderTexture; - - if (!renderTexture._canvasRenderTarget) { - renderTexture._canvasRenderTarget = new _CanvasRenderTarget2.default(renderTexture.width, renderTexture.height, renderTexture.resolution); - renderTexture.source = renderTexture._canvasRenderTarget.canvas; - renderTexture.valid = true; - } - - this.context = renderTexture._canvasRenderTarget.context; - this.resolution = renderTexture._canvasRenderTarget.resolution; - } else { - this.context = this.rootContext; - } - - var context = this.context; - - if (!renderTexture) { - this._lastObjectRendered = displayObject; - } - - if (!skipUpdateTransform) { - // update the scene graph - var cacheParent = displayObject.parent; - var tempWt = this._tempDisplayObjectParent.transform.worldTransform; - - if (transform) { - transform.copy(tempWt); - - // lets not forget to flag the parent transform as dirty... - this._tempDisplayObjectParent.transform._worldID = -1; - } else { - tempWt.identity(); - } - - displayObject.parent = this._tempDisplayObjectParent; - - displayObject.updateTransform(); - displayObject.parent = cacheParent; - // displayObject.hitArea = //TODO add a temp hit area - } - - context.setTransform(1, 0, 0, 1, 0, 0); - context.globalAlpha = 1; - context.globalCompositeOperation = this.blendModes[_const.BLEND_MODES.NORMAL]; - - if (navigator.isCocoonJS && this.view.screencanvas) { - context.fillStyle = 'black'; - context.clear(); - } - - if (clear !== undefined ? clear : this.clearBeforeRender) { - if (this.renderingToScreen) { - if (this.transparent) { - context.clearRect(0, 0, this.width, this.height); - } else { - context.fillStyle = this._backgroundColorString; - context.fillRect(0, 0, this.width, this.height); - } - } // else { - // TODO: implement background for CanvasRenderTarget or RenderTexture? - // } - } - - // TODO RENDER TARGET STUFF HERE.. - var tempContext = this.context; - - this.context = context; - displayObject.renderCanvas(this); - this.context = tempContext; - - this.resolution = rootResolution; - - this.emit('postrender'); - }; - - /** - * Clear the canvas of renderer. - * - * @param {string} [clearColor] - Clear the canvas with this color, except the canvas is transparent. - */ - - - CanvasRenderer.prototype.clear = function clear(clearColor) { - var context = this.context; - - clearColor = clearColor || this._backgroundColorString; - - if (!this.transparent && clearColor) { - context.fillStyle = clearColor; - context.fillRect(0, 0, this.width, this.height); - } else { - context.clearRect(0, 0, this.width, this.height); - } - }; - - /** - * Sets the blend mode of the renderer. - * - * @param {number} blendMode - See {@link PIXI.BLEND_MODES} for valid values. - */ - - - CanvasRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { - if (this._activeBlendMode === blendMode) { - return; - } - - this._activeBlendMode = blendMode; - this.context.globalCompositeOperation = this.blendModes[blendMode]; - }; - - /** - * Removes everything from the renderer and optionally removes the Canvas DOM element. - * - * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. - */ - - - CanvasRenderer.prototype.destroy = function destroy(removeView) { - this.destroyPlugins(); - - // call the base destroy - _SystemRenderer.prototype.destroy.call(this, removeView); - - this.context = null; - - this.refresh = true; - - this.maskManager.destroy(); - this.maskManager = null; - - this.smoothProperty = null; - }; - - /** - * Resizes the canvas view to the specified width and height. - * - * @extends PIXI.SystemRenderer#resize - * - * @param {number} screenWidth - the new width of the screen - * @param {number} screenHeight - the new height of the screen - */ - - - CanvasRenderer.prototype.resize = function resize(screenWidth, screenHeight) { - _SystemRenderer.prototype.resize.call(this, screenWidth, screenHeight); - - // reset the scale mode.. oddly this seems to be reset when the canvas is resized. - // surely a browser bug?? Let PixiJS fix that for you.. - if (this.smoothProperty) { - this.rootContext[this.smoothProperty] = _settings2.default.SCALE_MODE === _const.SCALE_MODES.LINEAR; - } - }; - - return CanvasRenderer; -}(_SystemRenderer3.default); - -/** - * Collection of installed plugins. These are included by default in PIXI, but can be excluded - * by creating a custom build. Consult the README for more information about creating custom - * builds and excluding plugins. - * @name PIXI.CanvasRenderer#plugins - * @type {object} - * @readonly - * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements. - * @property {PIXI.extract.CanvasExtract} extract Extract image data from renderer. - * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events. - * @property {PIXI.prepare.CanvasPrepare} prepare Pre-render display objects. - */ - -/** - * Adds a plugin to the renderer. - * - * @method PIXI.CanvasRenderer#registerPlugin - * @param {string} pluginName - The name of the plugin. - * @param {Function} ctor - The constructor function or class for the plugin. - */ - -exports.default = CanvasRenderer; -_utils.pluginTarget.mixin(CanvasRenderer); - -},{"../../const":46,"../../settings":101,"../../utils":124,"../SystemRenderer":76,"./utils/CanvasMaskManager":78,"./utils/CanvasRenderTarget":79,"./utils/mapCanvasBlendModesToPixi":81}],78:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _const = require('../../../const'); - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * A set of functions used to handle masking. - * - * @class - * @memberof PIXI - */ -var CanvasMaskManager = function () { - /** - * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. - */ - function CanvasMaskManager(renderer) { - _classCallCheck(this, CanvasMaskManager); - - this.renderer = renderer; - } - - /** - * This method adds it to the current stack of masks. - * - * @param {object} maskData - the maskData that will be pushed - */ - - - CanvasMaskManager.prototype.pushMask = function pushMask(maskData) { - var renderer = this.renderer; - - renderer.context.save(); - - var cacheAlpha = maskData.alpha; - var transform = maskData.transform.worldTransform; - var resolution = renderer.resolution; - - renderer.context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); - - // TODO suport sprite alpha masks?? - // lots of effort required. If demand is great enough.. - if (!maskData._texture) { - this.renderGraphicsShape(maskData); - renderer.context.clip(); - } - - maskData.worldAlpha = cacheAlpha; - }; - - /** - * Renders a PIXI.Graphics shape. - * - * @param {PIXI.Graphics} graphics - The object to render. - */ - - - CanvasMaskManager.prototype.renderGraphicsShape = function renderGraphicsShape(graphics) { - var context = this.renderer.context; - var len = graphics.graphicsData.length; - - if (len === 0) { - return; - } - - context.beginPath(); - - for (var i = 0; i < len; i++) { - var data = graphics.graphicsData[i]; - var shape = data.shape; - - if (data.type === _const.SHAPES.POLY) { - var points = shape.points; - - context.moveTo(points[0], points[1]); - - for (var j = 1; j < points.length / 2; j++) { - context.lineTo(points[j * 2], points[j * 2 + 1]); - } - - // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) { - context.closePath(); - } - } else if (data.type === _const.SHAPES.RECT) { - context.rect(shape.x, shape.y, shape.width, shape.height); - context.closePath(); - } else if (data.type === _const.SHAPES.CIRC) { - // TODO - need to be Undefined! - context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); - context.closePath(); - } else if (data.type === _const.SHAPES.ELIP) { - // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas - - var w = shape.width * 2; - var h = shape.height * 2; - - var x = shape.x - w / 2; - var y = shape.y - h / 2; - - var kappa = 0.5522848; - var ox = w / 2 * kappa; // control point offset horizontal - var oy = h / 2 * kappa; // control point offset vertical - var xe = x + w; // x-end - var ye = y + h; // y-end - var xm = x + w / 2; // x-middle - var ym = y + h / 2; // y-middle - - context.moveTo(x, ym); - context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); - context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); - context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); - context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); - context.closePath(); - } else if (data.type === _const.SHAPES.RREC) { - var rx = shape.x; - var ry = shape.y; - var width = shape.width; - var height = shape.height; - var radius = shape.radius; - - var maxRadius = Math.min(width, height) / 2 | 0; - - radius = radius > maxRadius ? maxRadius : radius; - - context.moveTo(rx, ry + radius); - context.lineTo(rx, ry + height - radius); - context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); - context.lineTo(rx + width - radius, ry + height); - context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); - context.lineTo(rx + width, ry + radius); - context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); - context.lineTo(rx + radius, ry); - context.quadraticCurveTo(rx, ry, rx, ry + radius); - context.closePath(); - } - } - }; - - /** - * Restores the current drawing context to the state it was before the mask was applied. - * - * @param {PIXI.CanvasRenderer} renderer - The renderer context to use. - */ - - - CanvasMaskManager.prototype.popMask = function popMask(renderer) { - renderer.context.restore(); - }; - - /** - * Destroys this canvas mask manager. - * - */ - - - CanvasMaskManager.prototype.destroy = function destroy() { - /* empty */ - }; - - return CanvasMaskManager; -}(); - -exports.default = CanvasMaskManager; - -},{"../../../const":46}],79:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _settings = require('../../../settings'); - -var _settings2 = _interopRequireDefault(_settings); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * Creates a Canvas element of the given size. - * - * @class - * @memberof PIXI - */ -var CanvasRenderTarget = function () { - /** - * @param {number} width - the width for the newly created canvas - * @param {number} height - the height for the newly created canvas - * @param {number} [resolution=1] - The resolution / device pixel ratio of the canvas - */ - function CanvasRenderTarget(width, height, resolution) { - _classCallCheck(this, CanvasRenderTarget); - - /** - * The Canvas object that belongs to this CanvasRenderTarget. - * - * @member {HTMLCanvasElement} - */ - this.canvas = document.createElement('canvas'); - - /** - * A CanvasRenderingContext2D object representing a two-dimensional rendering context. - * - * @member {CanvasRenderingContext2D} - */ - this.context = this.canvas.getContext('2d'); - - this.resolution = resolution || _settings2.default.RESOLUTION; - - this.resize(width, height); - } - - /** - * Clears the canvas that was created by the CanvasRenderTarget class. - * - * @private - */ - - - CanvasRenderTarget.prototype.clear = function clear() { - this.context.setTransform(1, 0, 0, 1, 0, 0); - this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); - }; - - /** - * Resizes the canvas to the specified width and height. - * - * @param {number} width - the new width of the canvas - * @param {number} height - the new height of the canvas - */ - - - CanvasRenderTarget.prototype.resize = function resize(width, height) { - this.canvas.width = width * this.resolution; - this.canvas.height = height * this.resolution; - }; - - /** - * Destroys this canvas. - * - */ - - - CanvasRenderTarget.prototype.destroy = function destroy() { - this.context = null; - this.canvas = null; - }; - - /** - * The width of the canvas buffer in pixels. - * - * @member {number} - */ - - - _createClass(CanvasRenderTarget, [{ - key: 'width', - get: function get() { - return this.canvas.width; - }, - set: function set(val) // eslint-disable-line require-jsdoc - { - this.canvas.width = val; - } - - /** - * The height of the canvas buffer in pixels. - * - * @member {number} - */ - - }, { - key: 'height', - get: function get() { - return this.canvas.height; - }, - set: function set(val) // eslint-disable-line require-jsdoc - { - this.canvas.height = val; - } - }]); - - return CanvasRenderTarget; -}(); - -exports.default = CanvasRenderTarget; - -},{"../../../settings":101}],80:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.default = canUseNewCanvasBlendModes; -/** - * Creates a little colored canvas - * - * @ignore - * @param {string} color - The color to make the canvas - * @return {canvas} a small canvas element - */ -function createColoredCanvas(color) { - var canvas = document.createElement('canvas'); - - canvas.width = 6; - canvas.height = 1; - - var context = canvas.getContext('2d'); - - context.fillStyle = color; - context.fillRect(0, 0, 6, 1); - - return canvas; -} - -/** - * Checks whether the Canvas BlendModes are supported by the current browser - * - * @return {boolean} whether they are supported - */ -function canUseNewCanvasBlendModes() { - if (typeof document === 'undefined') { - return false; - } - - var magenta = createColoredCanvas('#ff00ff'); - var yellow = createColoredCanvas('#ffff00'); - - var canvas = document.createElement('canvas'); - - canvas.width = 6; - canvas.height = 1; - - var context = canvas.getContext('2d'); - - context.globalCompositeOperation = 'multiply'; - context.drawImage(magenta, 0, 0); - context.drawImage(yellow, 2, 0); - - var imageData = context.getImageData(2, 0, 1, 1); - - if (!imageData) { - return false; - } - - var data = imageData.data; - - return data[0] === 255 && data[1] === 0 && data[2] === 0; -} - -},{}],81:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.default = mapCanvasBlendModesToPixi; - -var _const = require('../../../const'); - -var _canUseNewCanvasBlendModes = require('./canUseNewCanvasBlendModes'); - -var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Maps blend combinations to Canvas. - * - * @memberof PIXI - * @function mapCanvasBlendModesToPixi - * @private - * @param {string[]} [array=[]] - The array to output into. - * @return {string[]} Mapped modes. - */ -function mapCanvasBlendModesToPixi() { - var array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - - if ((0, _canUseNewCanvasBlendModes2.default)()) { - array[_const.BLEND_MODES.NORMAL] = 'source-over'; - array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? - array[_const.BLEND_MODES.MULTIPLY] = 'multiply'; - array[_const.BLEND_MODES.SCREEN] = 'screen'; - array[_const.BLEND_MODES.OVERLAY] = 'overlay'; - array[_const.BLEND_MODES.DARKEN] = 'darken'; - array[_const.BLEND_MODES.LIGHTEN] = 'lighten'; - array[_const.BLEND_MODES.COLOR_DODGE] = 'color-dodge'; - array[_const.BLEND_MODES.COLOR_BURN] = 'color-burn'; - array[_const.BLEND_MODES.HARD_LIGHT] = 'hard-light'; - array[_const.BLEND_MODES.SOFT_LIGHT] = 'soft-light'; - array[_const.BLEND_MODES.DIFFERENCE] = 'difference'; - array[_const.BLEND_MODES.EXCLUSION] = 'exclusion'; - array[_const.BLEND_MODES.HUE] = 'hue'; - array[_const.BLEND_MODES.SATURATION] = 'saturate'; - array[_const.BLEND_MODES.COLOR] = 'color'; - array[_const.BLEND_MODES.LUMINOSITY] = 'luminosity'; - } else { - // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' - array[_const.BLEND_MODES.NORMAL] = 'source-over'; - array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? - array[_const.BLEND_MODES.MULTIPLY] = 'source-over'; - array[_const.BLEND_MODES.SCREEN] = 'source-over'; - array[_const.BLEND_MODES.OVERLAY] = 'source-over'; - array[_const.BLEND_MODES.DARKEN] = 'source-over'; - array[_const.BLEND_MODES.LIGHTEN] = 'source-over'; - array[_const.BLEND_MODES.COLOR_DODGE] = 'source-over'; - array[_const.BLEND_MODES.COLOR_BURN] = 'source-over'; - array[_const.BLEND_MODES.HARD_LIGHT] = 'source-over'; - array[_const.BLEND_MODES.SOFT_LIGHT] = 'source-over'; - array[_const.BLEND_MODES.DIFFERENCE] = 'source-over'; - array[_const.BLEND_MODES.EXCLUSION] = 'source-over'; - array[_const.BLEND_MODES.HUE] = 'source-over'; - array[_const.BLEND_MODES.SATURATION] = 'source-over'; - array[_const.BLEND_MODES.COLOR] = 'source-over'; - array[_const.BLEND_MODES.LUMINOSITY] = 'source-over'; - } - // not-premultiplied, only for webgl - array[_const.BLEND_MODES.NORMAL_NPM] = array[_const.BLEND_MODES.NORMAL]; - array[_const.BLEND_MODES.ADD_NPM] = array[_const.BLEND_MODES.ADD]; - array[_const.BLEND_MODES.SCREEN_NPM] = array[_const.BLEND_MODES.SCREEN]; - - return array; -} - -},{"../../../const":46,"./canUseNewCanvasBlendModes":80}],82:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _const = require('../../const'); - -var _settings = require('../../settings'); - -var _settings2 = _interopRequireDefault(_settings); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * TextureGarbageCollector. This class manages the GPU and ensures that it does not get clogged - * up with textures that are no longer being used. - * - * @class - * @memberof PIXI - */ -var TextureGarbageCollector = function () { - /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. - */ - function TextureGarbageCollector(renderer) { - _classCallCheck(this, TextureGarbageCollector); - - this.renderer = renderer; - - this.count = 0; - this.checkCount = 0; - this.maxIdle = _settings2.default.GC_MAX_IDLE; - this.checkCountMax = _settings2.default.GC_MAX_CHECK_COUNT; - this.mode = _settings2.default.GC_MODE; - } - - /** - * Checks to see when the last time a texture was used - * if the texture has not been used for a specified amount of time it will be removed from the GPU - */ - - - TextureGarbageCollector.prototype.update = function update() { - this.count++; - - if (this.mode === _const.GC_MODES.MANUAL) { - return; - } - - this.checkCount++; - - if (this.checkCount > this.checkCountMax) { - this.checkCount = 0; - - this.run(); - } - }; - - /** - * Checks to see when the last time a texture was used - * if the texture has not been used for a specified amount of time it will be removed from the GPU - */ - - - TextureGarbageCollector.prototype.run = function run() { - var tm = this.renderer.textureManager; - var managedTextures = tm._managedTextures; - var wasRemoved = false; - - for (var i = 0; i < managedTextures.length; i++) { - var texture = managedTextures[i]; - - // only supports non generated textures at the moment! - if (!texture._glRenderTargets && this.count - texture.touched > this.maxIdle) { - tm.destroyTexture(texture, true); - managedTextures[i] = null; - wasRemoved = true; - } - } - - if (wasRemoved) { - var j = 0; - - for (var _i = 0; _i < managedTextures.length; _i++) { - if (managedTextures[_i] !== null) { - managedTextures[j++] = managedTextures[_i]; - } - } - - managedTextures.length = j; - } - }; - - /** - * Removes all the textures within the specified displayObject and its children from the GPU - * - * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. - */ - - - TextureGarbageCollector.prototype.unload = function unload(displayObject) { - var tm = this.renderer.textureManager; - - // only destroy non generated textures - if (displayObject._texture && displayObject._texture._glRenderTargets) { - tm.destroyTexture(displayObject._texture, true); - } - - for (var i = displayObject.children.length - 1; i >= 0; i--) { - this.unload(displayObject.children[i]); - } - }; - - return TextureGarbageCollector; -}(); - -exports.default = TextureGarbageCollector; - -},{"../../const":46,"../../settings":101}],83:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _pixiGlCore = require('pixi-gl-core'); - -var _const = require('../../const'); - -var _RenderTarget = require('./utils/RenderTarget'); - -var _RenderTarget2 = _interopRequireDefault(_RenderTarget); - -var _utils = require('../../utils'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * Helper class to create a webGL Texture - * - * @class - * @memberof PIXI - */ -var TextureManager = function () { - /** - * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer - */ - function TextureManager(renderer) { - _classCallCheck(this, TextureManager); - - /** - * A reference to the current renderer - * - * @member {PIXI.WebGLRenderer} - */ - this.renderer = renderer; - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = renderer.gl; - - /** - * Track textures in the renderer so we can no longer listen to them on destruction. - * - * @member {Array<*>} - * @private - */ - this._managedTextures = []; - } - - /** - * Binds a texture. - * - */ - - - TextureManager.prototype.bindTexture = function bindTexture() {} - // empty - - - /** - * Gets a texture. - * - */ - ; - - TextureManager.prototype.getTexture = function getTexture() {} - // empty - - - /** - * Updates and/or Creates a WebGL texture for the renderer's context. - * - * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to update - * @param {number} location - the location the texture will be bound to. - * @return {GLTexture} The gl texture. - */ - ; - - TextureManager.prototype.updateTexture = function updateTexture(texture, location) { - // assume it good! - // texture = texture.baseTexture || texture; - - var gl = this.gl; - - var isRenderTexture = !!texture._glRenderTargets; - - if (!texture.hasLoaded) { - return null; - } - - var boundTextures = this.renderer.boundTextures; - - // if the location is undefined then this may have been called by n event. - // this being the case the texture may already be bound to a slot. As a texture can only be bound once - // we need to find its current location if it exists. - if (location === undefined) { - location = 0; - - // TODO maybe we can use texture bound ids later on... - // check if texture is already bound.. - for (var i = 0; i < boundTextures.length; ++i) { - if (boundTextures[i] === texture) { - location = i; - break; - } - } - } - - boundTextures[location] = texture; - - gl.activeTexture(gl.TEXTURE0 + location); - - var glTexture = texture._glTextures[this.renderer.CONTEXT_UID]; - - if (!glTexture) { - if (isRenderTexture) { - var renderTarget = new _RenderTarget2.default(this.gl, texture.width, texture.height, texture.scaleMode, texture.resolution); - - renderTarget.resize(texture.width, texture.height); - texture._glRenderTargets[this.renderer.CONTEXT_UID] = renderTarget; - glTexture = renderTarget.texture; - } else { - glTexture = new _pixiGlCore.GLTexture(this.gl, null, null, null, null); - glTexture.bind(location); - glTexture.premultiplyAlpha = true; - glTexture.upload(texture.source); - } - - texture._glTextures[this.renderer.CONTEXT_UID] = glTexture; - - texture.on('update', this.updateTexture, this); - texture.on('dispose', this.destroyTexture, this); - - this._managedTextures.push(texture); - - if (texture.isPowerOfTwo) { - if (texture.mipmap) { - glTexture.enableMipmap(); - } - - if (texture.wrapMode === _const.WRAP_MODES.CLAMP) { - glTexture.enableWrapClamp(); - } else if (texture.wrapMode === _const.WRAP_MODES.REPEAT) { - glTexture.enableWrapRepeat(); - } else { - glTexture.enableWrapMirrorRepeat(); - } - } else { - glTexture.enableWrapClamp(); - } - - if (texture.scaleMode === _const.SCALE_MODES.NEAREST) { - glTexture.enableNearestScaling(); - } else { - glTexture.enableLinearScaling(); - } - } - // the texture already exists so we only need to update it.. - else if (isRenderTexture) { - texture._glRenderTargets[this.renderer.CONTEXT_UID].resize(texture.width, texture.height); - } else { - glTexture.upload(texture.source); - } - - return glTexture; - }; - - /** - * Deletes the texture from WebGL - * - * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy - * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager. - */ - - - TextureManager.prototype.destroyTexture = function destroyTexture(texture, skipRemove) { - texture = texture.baseTexture || texture; - - if (!texture.hasLoaded) { - return; - } - - var uid = this.renderer.CONTEXT_UID; - var glTextures = texture._glTextures; - var glRenderTargets = texture._glRenderTargets; - - if (glTextures[uid]) { - this.renderer.unbindTexture(texture); - - glTextures[uid].destroy(); - texture.off('update', this.updateTexture, this); - texture.off('dispose', this.destroyTexture, this); - - delete glTextures[uid]; - - if (!skipRemove) { - var i = this._managedTextures.indexOf(texture); - - if (i !== -1) { - (0, _utils.removeItems)(this._managedTextures, i, 1); - } - } - } - - if (glRenderTargets && glRenderTargets[uid]) { - glRenderTargets[uid].destroy(); - delete glRenderTargets[uid]; - } - }; - - /** - * Deletes all the textures from WebGL - */ - - - TextureManager.prototype.removeAll = function removeAll() { - // empty all the old gl textures as they are useless now - for (var i = 0; i < this._managedTextures.length; ++i) { - var texture = this._managedTextures[i]; - - if (texture._glTextures[this.renderer.CONTEXT_UID]) { - delete texture._glTextures[this.renderer.CONTEXT_UID]; - } - } - }; - - /** - * Destroys this manager and removes all its textures - */ - - - TextureManager.prototype.destroy = function destroy() { - // destroy managed textures - for (var i = 0; i < this._managedTextures.length; ++i) { - var texture = this._managedTextures[i]; - - this.destroyTexture(texture, true); - - texture.off('update', this.updateTexture, this); - texture.off('dispose', this.destroyTexture, this); - } - - this._managedTextures = null; - }; - - return TextureManager; -}(); - -exports.default = TextureManager; - -},{"../../const":46,"../../utils":124,"./utils/RenderTarget":96,"pixi-gl-core":12}],84:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _SystemRenderer2 = require('../SystemRenderer'); - -var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); - -var _MaskManager = require('./managers/MaskManager'); - -var _MaskManager2 = _interopRequireDefault(_MaskManager); - -var _StencilManager = require('./managers/StencilManager'); - -var _StencilManager2 = _interopRequireDefault(_StencilManager); - -var _FilterManager = require('./managers/FilterManager'); - -var _FilterManager2 = _interopRequireDefault(_FilterManager); - -var _RenderTarget = require('./utils/RenderTarget'); - -var _RenderTarget2 = _interopRequireDefault(_RenderTarget); - -var _ObjectRenderer = require('./utils/ObjectRenderer'); - -var _ObjectRenderer2 = _interopRequireDefault(_ObjectRenderer); - -var _TextureManager = require('./TextureManager'); - -var _TextureManager2 = _interopRequireDefault(_TextureManager); - -var _BaseTexture = require('../../textures/BaseTexture'); - -var _BaseTexture2 = _interopRequireDefault(_BaseTexture); - -var _TextureGarbageCollector = require('./TextureGarbageCollector'); - -var _TextureGarbageCollector2 = _interopRequireDefault(_TextureGarbageCollector); - -var _WebGLState = require('./WebGLState'); - -var _WebGLState2 = _interopRequireDefault(_WebGLState); - -var _mapWebGLDrawModesToPixi = require('./utils/mapWebGLDrawModesToPixi'); - -var _mapWebGLDrawModesToPixi2 = _interopRequireDefault(_mapWebGLDrawModesToPixi); - -var _validateContext = require('./utils/validateContext'); - -var _validateContext2 = _interopRequireDefault(_validateContext); - -var _utils = require('../../utils'); - -var _pixiGlCore = require('pixi-gl-core'); - -var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); - -var _const = require('../../const'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -var CONTEXT_UID = 0; - -/** - * The WebGLRenderer draws the scene and all its content onto a webGL enabled canvas. This renderer - * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. - * So no need for Sprite Batches or Sprite Clouds. - * Don't forget to add the view to your DOM or you will not see anything :) - * - * @class - * @memberof PIXI - * @extends PIXI.SystemRenderer - */ - -var WebGLRenderer = function (_SystemRenderer) { - _inherits(WebGLRenderer, _SystemRenderer); - - // eslint-disable-next-line valid-jsdoc - /** - * - * @param {object} [options] - The optional renderer parameters - * @param {number} [options.width=800] - the width of the screen - * @param {number} [options.height=600] - the height of the screen - * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional - * @param {boolean} [options.transparent=false] - If the render view is transparent, default false - * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false - * @param {boolean} [options.antialias=false] - sets antialias. If not available natively then FXAA - * antialiasing is used - * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. - * FXAA is faster, but may not always look as great - * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. - * The resolution of the renderer retina would be 2. - * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear - * the canvas or not before the new render pass. If you wish to set this to false, you *must* set - * preserveDrawingBuffer to `true`. - * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, - * enable this if you need to call toDataUrl on the webgl context. - * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when - * rendering, stopping pixel interpolation. - * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area - * (shown if not transparent). - * @param {boolean} [options.legacy=false] - If true PixiJS will aim to ensure compatibility - * with older / less advanced devices. If you experiance unexplained flickering try setting this to true. - */ - function WebGLRenderer(options, arg2, arg3) { - _classCallCheck(this, WebGLRenderer); - - var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'WebGL', options, arg2, arg3)); - - _this.legacy = _this.options.legacy; - - if (_this.legacy) { - _pixiGlCore2.default.VertexArrayObject.FORCE_NATIVE = true; - } - - /** - * The type of this renderer as a standardised const - * - * @member {number} - * @see PIXI.RENDERER_TYPE - */ - _this.type = _const.RENDERER_TYPE.WEBGL; - - _this.handleContextLost = _this.handleContextLost.bind(_this); - _this.handleContextRestored = _this.handleContextRestored.bind(_this); - - _this.view.addEventListener('webglcontextlost', _this.handleContextLost, false); - _this.view.addEventListener('webglcontextrestored', _this.handleContextRestored, false); - - /** - * The options passed in to create a new webgl context. - * - * @member {object} - * @private - */ - _this._contextOptions = { - alpha: _this.transparent, - antialias: _this.options.antialias, - premultipliedAlpha: _this.transparent && _this.transparent !== 'notMultiplied', - stencil: true, - preserveDrawingBuffer: _this.options.preserveDrawingBuffer - }; - - _this._backgroundColorRgba[3] = _this.transparent ? 0 : 1; - - /** - * Manages the masks using the stencil buffer. - * - * @member {PIXI.MaskManager} - */ - _this.maskManager = new _MaskManager2.default(_this); - - /** - * Manages the stencil buffer. - * - * @member {PIXI.StencilManager} - */ - _this.stencilManager = new _StencilManager2.default(_this); - - /** - * An empty renderer. - * - * @member {PIXI.ObjectRenderer} - */ - _this.emptyRenderer = new _ObjectRenderer2.default(_this); - - /** - * The currently active ObjectRenderer. - * - * @member {PIXI.ObjectRenderer} - */ - _this.currentRenderer = _this.emptyRenderer; - - _this.initPlugins(); - - /** - * The current WebGL rendering context, it is created here - * - * @member {WebGLRenderingContext} - */ - // initialize the context so it is ready for the managers. - if (_this.options.context) { - // checks to see if a context is valid.. - (0, _validateContext2.default)(_this.options.context); - } - - _this.gl = _this.options.context || _pixiGlCore2.default.createContext(_this.view, _this._contextOptions); - - _this.CONTEXT_UID = CONTEXT_UID++; - - /** - * The currently active ObjectRenderer. - * - * @member {PIXI.WebGLState} - */ - _this.state = new _WebGLState2.default(_this.gl); - - _this.renderingToScreen = true; - - /** - * Holds the current state of textures bound to the GPU. - * @type {Array} - */ - _this.boundTextures = null; - - /** - * Holds the current shader - * - * @member {PIXI.Shader} - */ - _this._activeShader = null; - - _this._activeVao = null; - - /** - * Holds the current render target - * - * @member {PIXI.RenderTarget} - */ - _this._activeRenderTarget = null; - - _this._initContext(); - - /** - * Manages the filters. - * - * @member {PIXI.FilterManager} - */ - _this.filterManager = new _FilterManager2.default(_this); - // map some webGL blend and drawmodes.. - _this.drawModes = (0, _mapWebGLDrawModesToPixi2.default)(_this.gl); - - _this._nextTextureLocation = 0; - - _this.setBlendMode(0); - - /** - * Fired after rendering finishes. - * - * @event PIXI.WebGLRenderer#postrender - */ - - /** - * Fired before rendering starts. - * - * @event PIXI.WebGLRenderer#prerender - */ - - /** - * Fired when the WebGL context is set. - * - * @event PIXI.WebGLRenderer#context - * @param {WebGLRenderingContext} gl - WebGL context. - */ - return _this; - } - - /** - * Creates the WebGL context - * - * @private - */ - - - WebGLRenderer.prototype._initContext = function _initContext() { - var gl = this.gl; - - // restore a context if it was previously lost - if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { - gl.getExtension('WEBGL_lose_context').restoreContext(); - } - - var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); - - this._activeShader = null; - this._activeVao = null; - - this.boundTextures = new Array(maxTextures); - this.emptyTextures = new Array(maxTextures); - - // create a texture manager... - this.textureManager = new _TextureManager2.default(this); - this.textureGC = new _TextureGarbageCollector2.default(this); - - this.state.resetToDefault(); - - this.rootRenderTarget = new _RenderTarget2.default(gl, this.width, this.height, null, this.resolution, true); - this.rootRenderTarget.clearColor = this._backgroundColorRgba; - - this.bindRenderTarget(this.rootRenderTarget); - - // now lets fill up the textures with empty ones! - var emptyGLTexture = new _pixiGlCore2.default.GLTexture.fromData(gl, null, 1, 1); - - var tempObj = { _glTextures: {} }; - - tempObj._glTextures[this.CONTEXT_UID] = {}; - - for (var i = 0; i < maxTextures; i++) { - var empty = new _BaseTexture2.default(); - - empty._glTextures[this.CONTEXT_UID] = emptyGLTexture; - - this.boundTextures[i] = tempObj; - this.emptyTextures[i] = empty; - this.bindTexture(null, i); - } - - this.emit('context', gl); - - // setup the width/height properties and gl viewport - this.resize(this.screen.width, this.screen.height); - }; - - /** - * Renders the object to its webGL view - * - * @param {PIXI.DisplayObject} displayObject - the object to be rendered - * @param {PIXI.RenderTexture} renderTexture - The render texture to render to. - * @param {boolean} [clear] - Should the canvas be cleared before the new render - * @param {PIXI.Transform} [transform] - A transform to apply to the render texture before rendering. - * @param {boolean} [skipUpdateTransform] - Should we skip the update transform pass? - */ - - - WebGLRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { - // can be handy to know! - this.renderingToScreen = !renderTexture; - - this.emit('prerender'); - - // no point rendering if our context has been blown up! - if (!this.gl || this.gl.isContextLost()) { - return; - } - - this._nextTextureLocation = 0; - - if (!renderTexture) { - this._lastObjectRendered = displayObject; - } - - if (!skipUpdateTransform) { - // update the scene graph - var cacheParent = displayObject.parent; - - displayObject.parent = this._tempDisplayObjectParent; - displayObject.updateTransform(); - displayObject.parent = cacheParent; - // displayObject.hitArea = //TODO add a temp hit area - } - - this.bindRenderTexture(renderTexture, transform); - - this.currentRenderer.start(); - - if (clear !== undefined ? clear : this.clearBeforeRender) { - this._activeRenderTarget.clear(); - } - - displayObject.renderWebGL(this); - - // apply transform.. - this.currentRenderer.flush(); - - // this.setObjectRenderer(this.emptyRenderer); - - this.textureGC.update(); - - this.emit('postrender'); - }; - - /** - * Changes the current renderer to the one given in parameter - * - * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use. - */ - - - WebGLRenderer.prototype.setObjectRenderer = function setObjectRenderer(objectRenderer) { - if (this.currentRenderer === objectRenderer) { - return; - } - - this.currentRenderer.stop(); - this.currentRenderer = objectRenderer; - this.currentRenderer.start(); - }; - - /** - * This should be called if you wish to do some custom rendering - * It will basically render anything that may be batched up such as sprites - * - */ - - - WebGLRenderer.prototype.flush = function flush() { - this.setObjectRenderer(this.emptyRenderer); - }; - - /** - * Resizes the webGL view to the specified width and height. - * - * @param {number} screenWidth - the new width of the screen - * @param {number} screenHeight - the new height of the screen - */ - - - WebGLRenderer.prototype.resize = function resize(screenWidth, screenHeight) { - // if(width * this.resolution === this.width && height * this.resolution === this.height)return; - - _SystemRenderer3.default.prototype.resize.call(this, screenWidth, screenHeight); - - this.rootRenderTarget.resize(screenWidth, screenHeight); - - if (this._activeRenderTarget === this.rootRenderTarget) { - this.rootRenderTarget.activate(); - - if (this._activeShader) { - this._activeShader.uniforms.projectionMatrix = this.rootRenderTarget.projectionMatrix.toArray(true); - } - } - }; - - /** - * Resizes the webGL view to the specified width and height. - * - * @param {number} blendMode - the desired blend mode - */ - - - WebGLRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { - this.state.setBlendMode(blendMode); - }; - - /** - * Erases the active render target and fills the drawing area with a colour - * - * @param {number} [clearColor] - The colour - */ - - - WebGLRenderer.prototype.clear = function clear(clearColor) { - this._activeRenderTarget.clear(clearColor); - }; - - /** - * Sets the transform of the active render target to the given matrix - * - * @param {PIXI.Matrix} matrix - The transformation matrix - */ - - - WebGLRenderer.prototype.setTransform = function setTransform(matrix) { - this._activeRenderTarget.transform = matrix; - }; - - /** - * Erases the render texture and fills the drawing area with a colour - * - * @param {PIXI.RenderTexture} renderTexture - The render texture to clear - * @param {number} [clearColor] - The colour - * @return {PIXI.WebGLRenderer} Returns itself. - */ - - - WebGLRenderer.prototype.clearRenderTexture = function clearRenderTexture(renderTexture, clearColor) { - var baseTexture = renderTexture.baseTexture; - var renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; - - if (renderTarget) { - renderTarget.clear(clearColor); - } - - return this; - }; - - /** - * Binds a render texture for rendering - * - * @param {PIXI.RenderTexture} renderTexture - The render texture to render - * @param {PIXI.Transform} transform - The transform to be applied to the render texture - * @return {PIXI.WebGLRenderer} Returns itself. - */ - - - WebGLRenderer.prototype.bindRenderTexture = function bindRenderTexture(renderTexture, transform) { - var renderTarget = void 0; - - if (renderTexture) { - var baseTexture = renderTexture.baseTexture; - - if (!baseTexture._glRenderTargets[this.CONTEXT_UID]) { - // bind the current texture - this.textureManager.updateTexture(baseTexture, 0); - } - - this.unbindTexture(baseTexture); - - renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; - renderTarget.setFrame(renderTexture.frame); - } else { - renderTarget = this.rootRenderTarget; - } - - renderTarget.transform = transform; - this.bindRenderTarget(renderTarget); - - return this; - }; - - /** - * Changes the current render target to the one given in parameter - * - * @param {PIXI.RenderTarget} renderTarget - the new render target - * @return {PIXI.WebGLRenderer} Returns itself. - */ - - - WebGLRenderer.prototype.bindRenderTarget = function bindRenderTarget(renderTarget) { - if (renderTarget !== this._activeRenderTarget) { - this._activeRenderTarget = renderTarget; - renderTarget.activate(); - - if (this._activeShader) { - this._activeShader.uniforms.projectionMatrix = renderTarget.projectionMatrix.toArray(true); - } - - this.stencilManager.setMaskStack(renderTarget.stencilMaskStack); - } - - return this; - }; - - /** - * Changes the current shader to the one given in parameter - * - * @param {PIXI.Shader} shader - the new shader - * @param {boolean} [autoProject=true] - Whether automatically set the projection matrix - * @return {PIXI.WebGLRenderer} Returns itself. - */ - - - WebGLRenderer.prototype.bindShader = function bindShader(shader, autoProject) { - // TODO cache - if (this._activeShader !== shader) { - this._activeShader = shader; - shader.bind(); - - // `autoProject` normally would be a default parameter set to true - // but because of how Babel transpiles default parameters - // it hinders the performance of this method. - if (autoProject !== false) { - // automatically set the projection matrix - shader.uniforms.projectionMatrix = this._activeRenderTarget.projectionMatrix.toArray(true); - } - } - - return this; - }; - - /** - * Binds the texture. This will return the location of the bound texture. - * It may not be the same as the one you pass in. This is due to optimisation that prevents - * needless binding of textures. For example if the texture is already bound it will return the - * current location of the texture instead of the one provided. To bypass this use force location - * - * @param {PIXI.Texture} texture - the new texture - * @param {number} location - the suggested texture location - * @param {boolean} forceLocation - force the location - * @return {number} bound texture location - */ - - - WebGLRenderer.prototype.bindTexture = function bindTexture(texture, location, forceLocation) { - texture = texture || this.emptyTextures[location]; - texture = texture.baseTexture || texture; - texture.touched = this.textureGC.count; - - if (!forceLocation) { - // TODO - maybe look into adding boundIds.. save us the loop? - for (var i = 0; i < this.boundTextures.length; i++) { - if (this.boundTextures[i] === texture) { - return i; - } - } - - if (location === undefined) { - this._nextTextureLocation++; - this._nextTextureLocation %= this.boundTextures.length; - location = this.boundTextures.length - this._nextTextureLocation - 1; - } - } else { - location = location || 0; - } - - var gl = this.gl; - var glTexture = texture._glTextures[this.CONTEXT_UID]; - - if (!glTexture) { - // this will also bind the texture.. - this.textureManager.updateTexture(texture, location); - } else { - // bind the current texture - this.boundTextures[location] = texture; - gl.activeTexture(gl.TEXTURE0 + location); - gl.bindTexture(gl.TEXTURE_2D, glTexture.texture); - } - - return location; - }; - - /** - * unbinds the texture ... - * - * @param {PIXI.Texture} texture - the texture to unbind - * @return {PIXI.WebGLRenderer} Returns itself. - */ - - - WebGLRenderer.prototype.unbindTexture = function unbindTexture(texture) { - var gl = this.gl; - - texture = texture.baseTexture || texture; - - for (var i = 0; i < this.boundTextures.length; i++) { - if (this.boundTextures[i] === texture) { - this.boundTextures[i] = this.emptyTextures[i]; - - gl.activeTexture(gl.TEXTURE0 + i); - gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[i]._glTextures[this.CONTEXT_UID].texture); - } - } - - return this; - }; - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - - - WebGLRenderer.prototype.createVao = function createVao() { - return new _pixiGlCore2.default.VertexArrayObject(this.gl, this.state.attribState); - }; - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - - - WebGLRenderer.prototype.bindVao = function bindVao(vao) { - if (this._activeVao === vao) { - return this; - } - - if (vao) { - vao.bind(); - } else if (this._activeVao) { - // TODO this should always be true i think? - this._activeVao.unbind(); - } - - this._activeVao = vao; - - return this; - }; - - /** - * Resets the WebGL state so you can render things however you fancy! - * - * @return {PIXI.WebGLRenderer} Returns itself. - */ - - - WebGLRenderer.prototype.reset = function reset() { - this.setObjectRenderer(this.emptyRenderer); - - this._activeShader = null; - this._activeRenderTarget = this.rootRenderTarget; - - // bind the main frame buffer (the screen); - this.rootRenderTarget.activate(); - - this.state.resetToDefault(); - - return this; - }; - - /** - * Handles a lost webgl context - * - * @private - * @param {WebGLContextEvent} event - The context lost event. - */ - - - WebGLRenderer.prototype.handleContextLost = function handleContextLost(event) { - event.preventDefault(); - }; - - /** - * Handles a restored webgl context - * - * @private - */ - - - WebGLRenderer.prototype.handleContextRestored = function handleContextRestored() { - this.textureManager.removeAll(); - this._initContext(); - }; - - /** - * Removes everything from the renderer (event listeners, spritebatch, etc...) - * - * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. - * See: https://github.com/pixijs/pixi.js/issues/2233 - */ - - - WebGLRenderer.prototype.destroy = function destroy(removeView) { - this.destroyPlugins(); - - // remove listeners - this.view.removeEventListener('webglcontextlost', this.handleContextLost); - this.view.removeEventListener('webglcontextrestored', this.handleContextRestored); - - this.textureManager.destroy(); - - // call base destroy - _SystemRenderer.prototype.destroy.call(this, removeView); - - this.uid = 0; - - // destroy the managers - this.maskManager.destroy(); - this.stencilManager.destroy(); - this.filterManager.destroy(); - - this.maskManager = null; - this.filterManager = null; - this.textureManager = null; - this.currentRenderer = null; - - this.handleContextLost = null; - this.handleContextRestored = null; - - this._contextOptions = null; - this.gl.useProgram(null); - - if (this.gl.getExtension('WEBGL_lose_context')) { - this.gl.getExtension('WEBGL_lose_context').loseContext(); - } - - this.gl = null; - - // this = null; - }; - - return WebGLRenderer; -}(_SystemRenderer3.default); - -/** - * Collection of installed plugins. These are included by default in PIXI, but can be excluded - * by creating a custom build. Consult the README for more information about creating custom - * builds and excluding plugins. - * @name PIXI.WebGLRenderer#plugins - * @type {object} - * @readonly - * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements. - * @property {PIXI.extract.WebGLExtract} extract Extract image data from renderer. - * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events. - * @property {PIXI.prepare.WebGLPrepare} prepare Pre-render display objects. - */ - -/** - * Adds a plugin to the renderer. - * - * @method PIXI.WebGLRenderer#registerPlugin - * @param {string} pluginName - The name of the plugin. - * @param {Function} ctor - The constructor function or class for the plugin. - */ - -exports.default = WebGLRenderer; -_utils.pluginTarget.mixin(WebGLRenderer); - -},{"../../const":46,"../../textures/BaseTexture":112,"../../utils":124,"../SystemRenderer":76,"./TextureGarbageCollector":82,"./TextureManager":83,"./WebGLState":85,"./managers/FilterManager":90,"./managers/MaskManager":91,"./managers/StencilManager":92,"./utils/ObjectRenderer":94,"./utils/RenderTarget":96,"./utils/mapWebGLDrawModesToPixi":99,"./utils/validateContext":100,"pixi-gl-core":12}],85:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _mapWebGLBlendModesToPixi = require('./utils/mapWebGLBlendModesToPixi'); - -var _mapWebGLBlendModesToPixi2 = _interopRequireDefault(_mapWebGLBlendModesToPixi); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var BLEND = 0; -var DEPTH_TEST = 1; -var FRONT_FACE = 2; -var CULL_FACE = 3; -var BLEND_FUNC = 4; - -/** - * A WebGL state machines - * - * @memberof PIXI - * @class - */ - -var WebGLState = function () { - /** - * @param {WebGLRenderingContext} gl - The current WebGL rendering context - */ - function WebGLState(gl) { - _classCallCheck(this, WebGLState); - - /** - * The current active state - * - * @member {Uint8Array} - */ - this.activeState = new Uint8Array(16); - - /** - * The default state - * - * @member {Uint8Array} - */ - this.defaultState = new Uint8Array(16); - - // default blend mode.. - this.defaultState[0] = 1; - - /** - * The current state index in the stack - * - * @member {number} - * @private - */ - this.stackIndex = 0; - - /** - * The stack holding all the different states - * - * @member {Array<*>} - * @private - */ - this.stack = []; - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - this.maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - this.attribState = { - tempAttribState: new Array(this.maxAttribs), - attribState: new Array(this.maxAttribs) - }; - - this.blendModes = (0, _mapWebGLBlendModesToPixi2.default)(gl); - - // check we have vao.. - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || gl.getExtension('MOZ_OES_vertex_array_object') || gl.getExtension('WEBKIT_OES_vertex_array_object'); - } - - /** - * Pushes a new active state - */ - - - WebGLState.prototype.push = function push() { - // next state.. - var state = this.stack[this.stackIndex]; - - if (!state) { - state = this.stack[this.stackIndex] = new Uint8Array(16); - } - - ++this.stackIndex; - - // copy state.. - // set active state so we can force overrides of gl state - for (var i = 0; i < this.activeState.length; i++) { - state[i] = this.activeState[i]; - } - }; - - /** - * Pops a state out - */ - - - WebGLState.prototype.pop = function pop() { - var state = this.stack[--this.stackIndex]; - - this.setState(state); - }; - - /** - * Sets the current state - * - * @param {*} state - The state to set. - */ - - - WebGLState.prototype.setState = function setState(state) { - this.setBlend(state[BLEND]); - this.setDepthTest(state[DEPTH_TEST]); - this.setFrontFace(state[FRONT_FACE]); - this.setCullFace(state[CULL_FACE]); - this.setBlendMode(state[BLEND_FUNC]); - }; - - /** - * Enables or disabled blending. - * - * @param {boolean} value - Turn on or off webgl blending. - */ - - - WebGLState.prototype.setBlend = function setBlend(value) { - value = value ? 1 : 0; - - if (this.activeState[BLEND] === value) { - return; - } - - this.activeState[BLEND] = value; - this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); - }; - - /** - * Sets the blend mode. - * - * @param {number} value - The blend mode to set to. - */ - - - WebGLState.prototype.setBlendMode = function setBlendMode(value) { - if (value === this.activeState[BLEND_FUNC]) { - return; - } - - this.activeState[BLEND_FUNC] = value; - - var mode = this.blendModes[value]; - - if (mode.length === 2) { - this.gl.blendFunc(mode[0], mode[1]); - } else { - this.gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]); - } - }; - - /** - * Sets whether to enable or disable depth test. - * - * @param {boolean} value - Turn on or off webgl depth testing. - */ - - - WebGLState.prototype.setDepthTest = function setDepthTest(value) { - value = value ? 1 : 0; - - if (this.activeState[DEPTH_TEST] === value) { - return; - } - - this.activeState[DEPTH_TEST] = value; - this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); - }; - - /** - * Sets whether to enable or disable cull face. - * - * @param {boolean} value - Turn on or off webgl cull face. - */ - - - WebGLState.prototype.setCullFace = function setCullFace(value) { - value = value ? 1 : 0; - - if (this.activeState[CULL_FACE] === value) { - return; - } - - this.activeState[CULL_FACE] = value; - this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); - }; - - /** - * Sets the gl front face. - * - * @param {boolean} value - true is clockwise and false is counter-clockwise - */ - - - WebGLState.prototype.setFrontFace = function setFrontFace(value) { - value = value ? 1 : 0; - - if (this.activeState[FRONT_FACE] === value) { - return; - } - - this.activeState[FRONT_FACE] = value; - this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); - }; - - /** - * Disables all the vaos in use - * - */ - - - WebGLState.prototype.resetAttributes = function resetAttributes() { - for (var i = 0; i < this.attribState.tempAttribState.length; i++) { - this.attribState.tempAttribState[i] = 0; - } - - for (var _i = 0; _i < this.attribState.attribState.length; _i++) { - this.attribState.attribState[_i] = 0; - } - - // im going to assume one is always active for performance reasons. - for (var _i2 = 1; _i2 < this.maxAttribs; _i2++) { - this.gl.disableVertexAttribArray(_i2); - } - }; - - // used - /** - * Resets all the logic and disables the vaos - */ - - - WebGLState.prototype.resetToDefault = function resetToDefault() { - // unbind any VAO if they exist.. - if (this.nativeVaoExtension) { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - // reset all attributes.. - this.resetAttributes(); - - // set active state so we can force overrides of gl state - for (var i = 0; i < this.activeState.length; ++i) { - this.activeState[i] = 32; - } - - this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); - - this.setState(this.defaultState); - }; - - return WebGLState; -}(); - -exports.default = WebGLState; - -},{"./utils/mapWebGLBlendModesToPixi":98}],86:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _extractUniformsFromSrc = require('./extractUniformsFromSrc'); - -var _extractUniformsFromSrc2 = _interopRequireDefault(_extractUniformsFromSrc); - -var _utils = require('../../../utils'); - -var _const = require('../../../const'); - -var _settings = require('../../../settings'); - -var _settings2 = _interopRequireDefault(_settings); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var SOURCE_KEY_MAP = {}; - -// let math = require('../../../math'); -/** - * @class - * @memberof PIXI - * @extends PIXI.Shader - */ - -var Filter = function () { - /** - * @param {string} [vertexSrc] - The source of the vertex shader. - * @param {string} [fragmentSrc] - The source of the fragment shader. - * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. - */ - function Filter(vertexSrc, fragmentSrc, uniforms) { - _classCallCheck(this, Filter); - - /** - * The vertex shader. - * - * @member {string} - */ - this.vertexSrc = vertexSrc || Filter.defaultVertexSrc; - - /** - * The fragment shader. - * - * @member {string} - */ - this.fragmentSrc = fragmentSrc || Filter.defaultFragmentSrc; - - this._blendMode = _const.BLEND_MODES.NORMAL; - - this.uniformData = uniforms || (0, _extractUniformsFromSrc2.default)(this.vertexSrc, this.fragmentSrc, 'projectionMatrix|uSampler'); - - /** - * An object containing the current values of custom uniforms. - * @example Updating the value of a custom uniform - * filter.uniforms.time = performance.now(); - * - * @member {object} - */ - this.uniforms = {}; - - for (var i in this.uniformData) { - this.uniforms[i] = this.uniformData[i].value; - } - - // this is where we store shader references.. - // TODO we could cache this! - this.glShaders = {}; - - // used for cacheing.. sure there is a better way! - if (!SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]) { - SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc] = (0, _utils.uid)(); - } - - this.glShaderKey = SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]; - - /** - * The padding of the filter. Some filters require extra space to breath such as a blur. - * Increasing this will add extra width and height to the bounds of the object that the - * filter is applied to. - * - * @member {number} - */ - this.padding = 4; - - /** - * The resolution of the filter. Setting this to be lower will lower the quality but - * increase the performance of the filter. - * - * @member {number} - */ - this.resolution = _settings2.default.RESOLUTION; - - /** - * If enabled is true the filter is applied, if false it will not. - * - * @member {boolean} - */ - this.enabled = true; - - /** - * If enabled, PixiJS will fit the filter area into boundaries for better performance. - * Switch it off if it does not work for specific shader. - * - * @member {boolean} - */ - this.autoFit = true; - } - - /** - * Applies the filter - * - * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from - * @param {PIXI.RenderTarget} input - The input render target. - * @param {PIXI.RenderTarget} output - The target to output to. - * @param {boolean} clear - Should the output be cleared before rendering to it - * @param {object} [currentState] - It's current state of filter. - * There are some useful properties in the currentState : - * target, filters, sourceFrame, destinationFrame, renderTarget, resolution - */ - - - Filter.prototype.apply = function apply(filterManager, input, output, clear, currentState) // eslint-disable-line no-unused-vars - { - // --- // - // this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(tempMatrix, window.panda ); - - // do as you please! - - filterManager.applyFilter(this, input, output, clear); - - // or just do a regular render.. - }; - - /** - * Sets the blendmode of the filter - * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL - */ - - - _createClass(Filter, [{ - key: 'blendMode', - get: function get() { - return this._blendMode; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._blendMode = value; - } - - /** - * The default vertex shader source - * - * @static - * @constant - */ - - }], [{ - key: 'defaultVertexSrc', - get: function get() { - return ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform mat3 projectionMatrix;', 'uniform mat3 filterMatrix;', 'varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;', ' vTextureCoord = aTextureCoord ;', '}'].join('\n'); - } - - /** - * The default fragment shader source - * - * @static - * @constant - */ - - }, { - key: 'defaultFragmentSrc', - get: function get() { - return ['varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'uniform sampler2D uSampler;', 'uniform sampler2D filterSampler;', 'void main(void){', ' vec4 masky = texture2D(filterSampler, vFilterCoord);', ' vec4 sample = texture2D(uSampler, vTextureCoord);', ' vec4 color;', ' if(mod(vFilterCoord.x, 1.0) > 0.5)', ' {', ' color = vec4(1.0, 0.0, 0.0, 1.0);', ' }', ' else', ' {', ' color = vec4(0.0, 1.0, 0.0, 1.0);', ' }', - // ' gl_FragColor = vec4(mod(vFilterCoord.x, 1.5), vFilterCoord.y,0.0,1.0);', - ' gl_FragColor = mix(sample, masky, 0.5);', ' gl_FragColor *= sample.a;', '}'].join('\n'); - } - }]); - - return Filter; -}(); - -exports.default = Filter; - -},{"../../../const":46,"../../../settings":101,"../../../utils":124,"./extractUniformsFromSrc":87}],87:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.default = extractUniformsFromSrc; - -var _pixiGlCore = require('pixi-gl-core'); - -var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var defaultValue = _pixiGlCore2.default.shader.defaultValue; - -function extractUniformsFromSrc(vertexSrc, fragmentSrc, mask) { - var vertUniforms = extractUniformsFromString(vertexSrc, mask); - var fragUniforms = extractUniformsFromString(fragmentSrc, mask); - - return Object.assign(vertUniforms, fragUniforms); -} - -function extractUniformsFromString(string) { - var maskRegex = new RegExp('^(projectionMatrix|uSampler|filterArea|filterClamp)$'); - - var uniforms = {}; - var nameSplit = void 0; - - // clean the lines a little - remove extra spaces / tabs etc - // then split along ';' - var lines = string.replace(/\s+/g, ' ').split(/\s*;\s*/); - - // loop through.. - for (var i = 0; i < lines.length; i++) { - var line = lines[i].trim(); - - if (line.indexOf('uniform') > -1) { - var splitLine = line.split(' '); - var type = splitLine[1]; - - var name = splitLine[2]; - var size = 1; - - if (name.indexOf('[') > -1) { - // array! - nameSplit = name.split(/\[|]/); - name = nameSplit[0]; - size *= Number(nameSplit[1]); - } - - if (!name.match(maskRegex)) { - uniforms[name] = { - value: defaultValue(type, size), - name: name, - type: type - }; - } - } - } - - return uniforms; -} - -},{"pixi-gl-core":12}],88:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.calculateScreenSpaceMatrix = calculateScreenSpaceMatrix; -exports.calculateNormalizedScreenSpaceMatrix = calculateNormalizedScreenSpaceMatrix; -exports.calculateSpriteMatrix = calculateSpriteMatrix; - -var _math = require('../../../math'); - -/** - * Calculates the mapped matrix - * @param filterArea {Rectangle} The filter area - * @param sprite {Sprite} the target sprite - * @param outputMatrix {Matrix} @alvin - */ -// TODO playing around here.. this is temporary - (will end up in the shader) -// this returns a matrix that will normalise map filter cords in the filter to screen space -function calculateScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { - // let worldTransform = sprite.worldTransform.copy(Matrix.TEMP_MATRIX), - // let texture = {width:1136, height:700};//sprite._texture.baseTexture; - - // TODO unwrap? - var mappedMatrix = outputMatrix.identity(); - - mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); - - mappedMatrix.scale(textureSize.width, textureSize.height); - - return mappedMatrix; -} - -function calculateNormalizedScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { - var mappedMatrix = outputMatrix.identity(); - - mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); - - var translateScaleX = textureSize.width / filterArea.width; - var translateScaleY = textureSize.height / filterArea.height; - - mappedMatrix.scale(translateScaleX, translateScaleY); - - return mappedMatrix; -} - -// this will map the filter coord so that a texture can be used based on the transform of a sprite -function calculateSpriteMatrix(outputMatrix, filterArea, textureSize, sprite) { - var worldTransform = sprite.worldTransform.copy(_math.Matrix.TEMP_MATRIX); - var texture = sprite._texture.baseTexture; - - // TODO unwrap? - var mappedMatrix = outputMatrix.identity(); - - // scale.. - var ratio = textureSize.height / textureSize.width; - - mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); - - mappedMatrix.scale(1, ratio); - - var translateScaleX = textureSize.width / texture.width; - var translateScaleY = textureSize.height / texture.height; - - worldTransform.tx /= texture.width * translateScaleX; - - // this...? free beer for anyone who can explain why this makes sense! - worldTransform.ty /= texture.width * translateScaleX; - // worldTransform.ty /= texture.height * translateScaleY; - - worldTransform.invert(); - mappedMatrix.prepend(worldTransform); - - // apply inverse scale.. - mappedMatrix.scale(1, 1 / ratio); - - mappedMatrix.scale(translateScaleX, translateScaleY); - - mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); - - return mappedMatrix; -} - -},{"../../../math":70}],89:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _Filter2 = require('../Filter'); - -var _Filter3 = _interopRequireDefault(_Filter2); - -var _math = require('../../../../math'); - -var _path = require('path'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * The SpriteMaskFilter class - * - * @class - * @extends PIXI.Filter - * @memberof PIXI - */ -var SpriteMaskFilter = function (_Filter) { - _inherits(SpriteMaskFilter, _Filter); - - /** - * @param {PIXI.Sprite} sprite - the target sprite - */ - function SpriteMaskFilter(sprite) { - _classCallCheck(this, SpriteMaskFilter); - - var maskMatrix = new _math.Matrix(); - - var _this = _possibleConstructorReturn(this, _Filter.call(this, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n', 'varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n')); - - sprite.renderable = false; - - _this.maskSprite = sprite; - _this.maskMatrix = maskMatrix; - return _this; - } - - /** - * Applies the filter - * - * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from - * @param {PIXI.RenderTarget} input - The input render target. - * @param {PIXI.RenderTarget} output - The target to output to. - */ - - - SpriteMaskFilter.prototype.apply = function apply(filterManager, input, output) { - var maskSprite = this.maskSprite; - - this.uniforms.mask = maskSprite._texture; - this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite); - this.uniforms.alpha = maskSprite.worldAlpha; - - filterManager.applyFilter(this, input, output); - }; - - return SpriteMaskFilter; -}(_Filter3.default); - -exports.default = SpriteMaskFilter; - -},{"../../../../math":70,"../Filter":86,"path":23}],90:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _WebGLManager2 = require('./WebGLManager'); - -var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); - -var _RenderTarget = require('../utils/RenderTarget'); - -var _RenderTarget2 = _interopRequireDefault(_RenderTarget); - -var _Quad = require('../utils/Quad'); - -var _Quad2 = _interopRequireDefault(_Quad); - -var _math = require('../../../math'); - -var _Shader = require('../../../Shader'); - -var _Shader2 = _interopRequireDefault(_Shader); - -var _filterTransforms = require('../filters/filterTransforms'); - -var filterTransforms = _interopRequireWildcard(_filterTransforms); - -var _bitTwiddle = require('bit-twiddle'); - -var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * @ignore - * @class - */ -var FilterState = -/** - * - */ -function FilterState() { - _classCallCheck(this, FilterState); - - this.renderTarget = null; - this.sourceFrame = new _math.Rectangle(); - this.destinationFrame = new _math.Rectangle(); - this.filters = []; - this.target = null; - this.resolution = 1; -}; - -/** - * @class - * @memberof PIXI - * @extends PIXI.WebGLManager - */ - - -var FilterManager = function (_WebGLManager) { - _inherits(FilterManager, _WebGLManager); - - /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. - */ - function FilterManager(renderer) { - _classCallCheck(this, FilterManager); - - var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); - - _this.gl = _this.renderer.gl; - // know about sprites! - _this.quad = new _Quad2.default(_this.gl, renderer.state.attribState); - - _this.shaderCache = {}; - // todo add default! - _this.pool = {}; - - _this.filterData = null; - return _this; - } - - /** - * Adds a new filter to the manager. - * - * @param {PIXI.DisplayObject} target - The target of the filter to render. - * @param {PIXI.Filter[]} filters - The filters to apply. - */ - - - FilterManager.prototype.pushFilter = function pushFilter(target, filters) { - var renderer = this.renderer; - - var filterData = this.filterData; - - if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; - - // add new stack - var filterState = new FilterState(); - - filterState.sourceFrame = filterState.destinationFrame = this.renderer._activeRenderTarget.size; - filterState.renderTarget = renderer._activeRenderTarget; - - this.renderer._activeRenderTarget.filterData = filterData = { - index: 0, - stack: [filterState] - }; - - this.filterData = filterData; - } - - // get the current filter state.. - var currentState = filterData.stack[++filterData.index]; - - if (!currentState) { - currentState = filterData.stack[filterData.index] = new FilterState(); - } - - // for now we go off the filter of the first resolution.. - var resolution = filters[0].resolution; - var padding = filters[0].padding | 0; - var targetBounds = target.filterArea || target.getBounds(true); - var sourceFrame = currentState.sourceFrame; - var destinationFrame = currentState.destinationFrame; - - sourceFrame.x = (targetBounds.x * resolution | 0) / resolution; - sourceFrame.y = (targetBounds.y * resolution | 0) / resolution; - sourceFrame.width = (targetBounds.width * resolution | 0) / resolution; - sourceFrame.height = (targetBounds.height * resolution | 0) / resolution; - - if (filterData.stack[0].renderTarget.transform) {// - - // TODO we should fit the rect around the transform.. - } else if (filters[0].autoFit) { - sourceFrame.fit(filterData.stack[0].destinationFrame); - } - - // lets apply the padding After we fit the element to the screen. - // this should stop the strange side effects that can occur when cropping to the edges - sourceFrame.pad(padding); - - destinationFrame.width = sourceFrame.width; - destinationFrame.height = sourceFrame.height; - - // lets play the padding after we fit the element to the screen. - // this should stop the strange side effects that can occur when cropping to the edges - - var renderTarget = this.getPotRenderTarget(renderer.gl, sourceFrame.width, sourceFrame.height, resolution); - - currentState.target = target; - currentState.filters = filters; - currentState.resolution = resolution; - currentState.renderTarget = renderTarget; - - // bind the render target to draw the shape in the top corner.. - - renderTarget.setFrame(destinationFrame, sourceFrame); - - // bind the render target - renderer.bindRenderTarget(renderTarget); - renderTarget.clear(); - }; - - /** - * Pops off the filter and applies it. - * - */ - - - FilterManager.prototype.popFilter = function popFilter() { - var filterData = this.filterData; - - var lastState = filterData.stack[filterData.index - 1]; - var currentState = filterData.stack[filterData.index]; - - this.quad.map(currentState.renderTarget.size, currentState.sourceFrame).upload(); - - var filters = currentState.filters; - - if (filters.length === 1) { - filters[0].apply(this, currentState.renderTarget, lastState.renderTarget, false, currentState); - this.freePotRenderTarget(currentState.renderTarget); - } else { - var flip = currentState.renderTarget; - var flop = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, currentState.resolution); - - flop.setFrame(currentState.destinationFrame, currentState.sourceFrame); - - // finally lets clear the render target before drawing to it.. - flop.clear(); - - var i = 0; - - for (i = 0; i < filters.length - 1; ++i) { - filters[i].apply(this, flip, flop, true, currentState); - - var t = flip; - - flip = flop; - flop = t; - } - - filters[i].apply(this, flip, lastState.renderTarget, false, currentState); - - this.freePotRenderTarget(flip); - this.freePotRenderTarget(flop); - } - - filterData.index--; - - if (filterData.index === 0) { - this.filterData = null; - } - }; - - /** - * Draws a filter. - * - * @param {PIXI.Filter} filter - The filter to draw. - * @param {PIXI.RenderTarget} input - The input render target. - * @param {PIXI.RenderTarget} output - The target to output to. - * @param {boolean} clear - Should the output be cleared before rendering to it - */ - - - FilterManager.prototype.applyFilter = function applyFilter(filter, input, output, clear) { - var renderer = this.renderer; - var gl = renderer.gl; - - var shader = filter.glShaders[renderer.CONTEXT_UID]; - - // cacheing.. - if (!shader) { - if (filter.glShaderKey) { - shader = this.shaderCache[filter.glShaderKey]; - - if (!shader) { - shader = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); - - filter.glShaders[renderer.CONTEXT_UID] = this.shaderCache[filter.glShaderKey] = shader; - } - } else { - shader = filter.glShaders[renderer.CONTEXT_UID] = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); - } - - // TODO - this only needs to be done once? - renderer.bindVao(null); - - this.quad.initVao(shader); - } - - renderer.bindVao(this.quad.vao); - - renderer.bindRenderTarget(output); - - if (clear) { - gl.disable(gl.SCISSOR_TEST); - renderer.clear(); // [1, 1, 1, 1]); - gl.enable(gl.SCISSOR_TEST); - } - - // in case the render target is being masked using a scissor rect - if (output === renderer.maskManager.scissorRenderTarget) { - renderer.maskManager.pushScissorMask(null, renderer.maskManager.scissorData); - } - - renderer.bindShader(shader); - - // free unit 0 for us, doesn't matter what was there - // don't try to restore it, because syncUniforms can upload it to another slot - // and it'll be a problem - var tex = this.renderer.emptyTextures[0]; - - this.renderer.boundTextures[0] = tex; - // this syncs the PixiJS filters uniforms with glsl uniforms - this.syncUniforms(shader, filter); - - renderer.state.setBlendMode(filter.blendMode); - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, input.texture.texture); - - this.quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); - - gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); - }; - - /** - * Uploads the uniforms of the filter. - * - * @param {GLShader} shader - The underlying gl shader. - * @param {PIXI.Filter} filter - The filter we are synchronizing. - */ - - - FilterManager.prototype.syncUniforms = function syncUniforms(shader, filter) { - var uniformData = filter.uniformData; - var uniforms = filter.uniforms; - - // 0 is reserved for the PixiJS texture so we start at 1! - var textureCount = 1; - var currentState = void 0; - - // filterArea and filterClamp that are handled by FilterManager directly - // they must not appear in uniformData - - if (shader.uniforms.filterArea) { - currentState = this.filterData.stack[this.filterData.index]; - - var filterArea = shader.uniforms.filterArea; - - filterArea[0] = currentState.renderTarget.size.width; - filterArea[1] = currentState.renderTarget.size.height; - filterArea[2] = currentState.sourceFrame.x; - filterArea[3] = currentState.sourceFrame.y; - - shader.uniforms.filterArea = filterArea; - } - - // use this to clamp displaced texture coords so they belong to filterArea - // see displacementFilter fragment shader for an example - if (shader.uniforms.filterClamp) { - currentState = currentState || this.filterData.stack[this.filterData.index]; - - var filterClamp = shader.uniforms.filterClamp; - - filterClamp[0] = 0; - filterClamp[1] = 0; - filterClamp[2] = (currentState.sourceFrame.width - 1) / currentState.renderTarget.size.width; - filterClamp[3] = (currentState.sourceFrame.height - 1) / currentState.renderTarget.size.height; - - shader.uniforms.filterClamp = filterClamp; - } - - // TODO Cacheing layer.. - for (var i in uniformData) { - if (uniformData[i].type === 'sampler2D' && uniforms[i] !== 0) { - if (uniforms[i].baseTexture) { - shader.uniforms[i] = this.renderer.bindTexture(uniforms[i].baseTexture, textureCount); - } else { - shader.uniforms[i] = textureCount; - - // TODO - // this is helpful as renderTargets can also be set. - // Although thinking about it, we could probably - // make the filter texture cache return a RenderTexture - // rather than a renderTarget - var gl = this.renderer.gl; - - this.renderer.boundTextures[textureCount] = this.renderer.emptyTextures[textureCount]; - gl.activeTexture(gl.TEXTURE0 + textureCount); - - uniforms[i].texture.bind(); - } - - textureCount++; - } else if (uniformData[i].type === 'mat3') { - // check if its PixiJS matrix.. - if (uniforms[i].a !== undefined) { - shader.uniforms[i] = uniforms[i].toArray(true); - } else { - shader.uniforms[i] = uniforms[i]; - } - } else if (uniformData[i].type === 'vec2') { - // check if its a point.. - if (uniforms[i].x !== undefined) { - var val = shader.uniforms[i] || new Float32Array(2); - - val[0] = uniforms[i].x; - val[1] = uniforms[i].y; - shader.uniforms[i] = val; - } else { - shader.uniforms[i] = uniforms[i]; - } - } else if (uniformData[i].type === 'float') { - if (shader.uniforms.data[i].value !== uniformData[i]) { - shader.uniforms[i] = uniforms[i]; - } - } else { - shader.uniforms[i] = uniforms[i]; - } - } - }; - - /** - * Gets a render target from the pool, or creates a new one. - * - * @param {boolean} clear - Should we clear the render texture when we get it? - * @param {number} resolution - The resolution of the target. - * @return {PIXI.RenderTarget} The new render target - */ - - - FilterManager.prototype.getRenderTarget = function getRenderTarget(clear, resolution) { - var currentState = this.filterData.stack[this.filterData.index]; - var renderTarget = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, resolution || currentState.resolution); - - renderTarget.setFrame(currentState.destinationFrame, currentState.sourceFrame); - - return renderTarget; - }; - - /** - * Returns a render target to the pool. - * - * @param {PIXI.RenderTarget} renderTarget - The render target to return. - */ - - - FilterManager.prototype.returnRenderTarget = function returnRenderTarget(renderTarget) { - this.freePotRenderTarget(renderTarget); - }; - - /** - * Calculates the mapped matrix. - * - * TODO playing around here.. this is temporary - (will end up in the shader) - * this returns a matrix that will normalise map filter cords in the filter to screen space - * - * @param {PIXI.Matrix} outputMatrix - the matrix to output to. - * @return {PIXI.Matrix} The mapped matrix. - */ - - - FilterManager.prototype.calculateScreenSpaceMatrix = function calculateScreenSpaceMatrix(outputMatrix) { - var currentState = this.filterData.stack[this.filterData.index]; - - return filterTransforms.calculateScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size); - }; - - /** - * Multiply vTextureCoord to this matrix to achieve (0,0,1,1) for filterArea - * - * @param {PIXI.Matrix} outputMatrix - The matrix to output to. - * @return {PIXI.Matrix} The mapped matrix. - */ - - - FilterManager.prototype.calculateNormalizedScreenSpaceMatrix = function calculateNormalizedScreenSpaceMatrix(outputMatrix) { - var currentState = this.filterData.stack[this.filterData.index]; - - return filterTransforms.calculateNormalizedScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, currentState.destinationFrame); - }; - - /** - * This will map the filter coord so that a texture can be used based on the transform of a sprite - * - * @param {PIXI.Matrix} outputMatrix - The matrix to output to. - * @param {PIXI.Sprite} sprite - The sprite to map to. - * @return {PIXI.Matrix} The mapped matrix. - */ - - - FilterManager.prototype.calculateSpriteMatrix = function calculateSpriteMatrix(outputMatrix, sprite) { - var currentState = this.filterData.stack[this.filterData.index]; - - return filterTransforms.calculateSpriteMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, sprite); - }; - - /** - * Destroys this Filter Manager. - * - */ - - - FilterManager.prototype.destroy = function destroy() { - this.shaderCache = {}; - this.emptyPool(); - }; - - /** - * Gets a Power-of-Two render texture. - * - * TODO move to a seperate class could be on renderer? - * also - could cause issue with multiple contexts? - * - * @private - * @param {WebGLRenderingContext} gl - The webgl rendering context - * @param {number} minWidth - The minimum width of the render target. - * @param {number} minHeight - The minimum height of the render target. - * @param {number} resolution - The resolution of the render target. - * @return {PIXI.RenderTarget} The new render target. - */ - - - FilterManager.prototype.getPotRenderTarget = function getPotRenderTarget(gl, minWidth, minHeight, resolution) { - // TODO you could return a bigger texture if there is not one in the pool? - minWidth = _bitTwiddle2.default.nextPow2(minWidth * resolution); - minHeight = _bitTwiddle2.default.nextPow2(minHeight * resolution); - - var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; - - if (!this.pool[key]) { - this.pool[key] = []; - } - - var renderTarget = this.pool[key].pop(); - - // creating render target will cause texture to be bound! - if (!renderTarget) { - // temporary bypass cache.. - var tex = this.renderer.boundTextures[0]; - - gl.activeTexture(gl.TEXTURE0); - - // internally - this will cause a texture to be bound.. - renderTarget = new _RenderTarget2.default(gl, minWidth, minHeight, null, 1); - - // set the current one back - gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); - } - - // manually tweak the resolution... - // this will not modify the size of the frame buffer, just its resolution. - renderTarget.resolution = resolution; - renderTarget.defaultFrame.width = renderTarget.size.width = minWidth / resolution; - renderTarget.defaultFrame.height = renderTarget.size.height = minHeight / resolution; - - return renderTarget; - }; - - /** - * Empties the texture pool. - * - */ - - - FilterManager.prototype.emptyPool = function emptyPool() { - for (var i in this.pool) { - var textures = this.pool[i]; - - if (textures) { - for (var j = 0; j < textures.length; j++) { - textures[j].destroy(true); - } - } - } - - this.pool = {}; - }; - - /** - * Frees a render target back into the pool. - * - * @param {PIXI.RenderTarget} renderTarget - The renderTarget to free - */ - - - FilterManager.prototype.freePotRenderTarget = function freePotRenderTarget(renderTarget) { - var minWidth = renderTarget.size.width * renderTarget.resolution; - var minHeight = renderTarget.size.height * renderTarget.resolution; - var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; - - this.pool[key].push(renderTarget); - }; - - return FilterManager; -}(_WebGLManager3.default); - -exports.default = FilterManager; - -},{"../../../Shader":44,"../../../math":70,"../filters/filterTransforms":88,"../utils/Quad":95,"../utils/RenderTarget":96,"./WebGLManager":93,"bit-twiddle":1}],91:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _WebGLManager2 = require('./WebGLManager'); - -var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); - -var _SpriteMaskFilter = require('../filters/spriteMask/SpriteMaskFilter'); - -var _SpriteMaskFilter2 = _interopRequireDefault(_SpriteMaskFilter); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * @class - * @extends PIXI.WebGLManager - * @memberof PIXI - */ -var MaskManager = function (_WebGLManager) { - _inherits(MaskManager, _WebGLManager); - - /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. - */ - function MaskManager(renderer) { - _classCallCheck(this, MaskManager); - - // TODO - we don't need both! - var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); - - _this.scissor = false; - _this.scissorData = null; - _this.scissorRenderTarget = null; - - _this.enableScissor = true; - - _this.alphaMaskPool = []; - _this.alphaMaskIndex = 0; - return _this; - } - - /** - * Applies the Mask and adds it to the current filter stack. - * - * @param {PIXI.DisplayObject} target - Display Object to push the mask to - * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. - */ - - - MaskManager.prototype.pushMask = function pushMask(target, maskData) { - // TODO the root check means scissor rect will not - // be used on render textures more info here: - // https://github.com/pixijs/pixi.js/pull/3545 - - if (maskData.texture) { - this.pushSpriteMask(target, maskData); - } else if (this.enableScissor && !this.scissor && this.renderer._activeRenderTarget.root && !this.renderer.stencilManager.stencilMaskStack.length && maskData.isFastRect()) { - var matrix = maskData.worldTransform; - - var rot = Math.atan2(matrix.b, matrix.a); - - // use the nearest degree! - rot = Math.round(rot * (180 / Math.PI)); - - if (rot % 90) { - this.pushStencilMask(maskData); - } else { - this.pushScissorMask(target, maskData); - } - } else { - this.pushStencilMask(maskData); - } - }; - - /** - * Removes the last mask from the mask stack and doesn't return it. - * - * @param {PIXI.DisplayObject} target - Display Object to pop the mask from - * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. - */ - - - MaskManager.prototype.popMask = function popMask(target, maskData) { - if (maskData.texture) { - this.popSpriteMask(target, maskData); - } else if (this.enableScissor && !this.renderer.stencilManager.stencilMaskStack.length) { - this.popScissorMask(target, maskData); - } else { - this.popStencilMask(target, maskData); - } - }; - - /** - * Applies the Mask and adds it to the current filter stack. - * - * @param {PIXI.RenderTarget} target - Display Object to push the sprite mask to - * @param {PIXI.Sprite} maskData - Sprite to be used as the mask - */ - - - MaskManager.prototype.pushSpriteMask = function pushSpriteMask(target, maskData) { - var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; - - if (!alphaMaskFilter) { - alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new _SpriteMaskFilter2.default(maskData)]; - } - - alphaMaskFilter[0].resolution = this.renderer.resolution; - alphaMaskFilter[0].maskSprite = maskData; - - // TODO - may cause issues! - target.filterArea = maskData.getBounds(true); - - this.renderer.filterManager.pushFilter(target, alphaMaskFilter); - - this.alphaMaskIndex++; - }; - - /** - * Removes the last filter from the filter stack and doesn't return it. - * - */ - - - MaskManager.prototype.popSpriteMask = function popSpriteMask() { - this.renderer.filterManager.popFilter(); - this.alphaMaskIndex--; - }; - - /** - * Applies the Mask and adds it to the current filter stack. - * - * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. - */ - - - MaskManager.prototype.pushStencilMask = function pushStencilMask(maskData) { - this.renderer.currentRenderer.stop(); - this.renderer.stencilManager.pushStencil(maskData); - }; - - /** - * Removes the last filter from the filter stack and doesn't return it. - * - */ - - - MaskManager.prototype.popStencilMask = function popStencilMask() { - this.renderer.currentRenderer.stop(); - this.renderer.stencilManager.popStencil(); - }; - - /** - * - * @param {PIXI.DisplayObject} target - Display Object to push the mask to - * @param {PIXI.Graphics} maskData - The masking data. - */ - - - MaskManager.prototype.pushScissorMask = function pushScissorMask(target, maskData) { - maskData.renderable = true; - - var renderTarget = this.renderer._activeRenderTarget; - - var bounds = maskData.getBounds(); - - bounds.fit(renderTarget.size); - maskData.renderable = false; - - this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); - - var resolution = this.renderer.resolution; - - this.renderer.gl.scissor(bounds.x * resolution, (renderTarget.root ? renderTarget.size.height - bounds.y - bounds.height : bounds.y) * resolution, bounds.width * resolution, bounds.height * resolution); - - this.scissorRenderTarget = renderTarget; - this.scissorData = maskData; - this.scissor = true; - }; - - /** - * - * - */ - - - MaskManager.prototype.popScissorMask = function popScissorMask() { - this.scissorRenderTarget = null; - this.scissorData = null; - this.scissor = false; - - // must be scissor! - var gl = this.renderer.gl; - - gl.disable(gl.SCISSOR_TEST); - }; - - return MaskManager; -}(_WebGLManager3.default); - -exports.default = MaskManager; - -},{"../filters/spriteMask/SpriteMaskFilter":89,"./WebGLManager":93}],92:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _WebGLManager2 = require('./WebGLManager'); - -var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * @class - * @extends PIXI.WebGLManager - * @memberof PIXI - */ -var StencilManager = function (_WebGLManager) { - _inherits(StencilManager, _WebGLManager); - - /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. - */ - function StencilManager(renderer) { - _classCallCheck(this, StencilManager); - - var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); - - _this.stencilMaskStack = null; - return _this; - } - - /** - * Changes the mask stack that is used by this manager. - * - * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack - */ - - - StencilManager.prototype.setMaskStack = function setMaskStack(stencilMaskStack) { - this.stencilMaskStack = stencilMaskStack; - - var gl = this.renderer.gl; - - if (stencilMaskStack.length === 0) { - gl.disable(gl.STENCIL_TEST); - } else { - gl.enable(gl.STENCIL_TEST); - } - }; - - /** - * Applies the Mask and adds it to the current filter stack. @alvin - * - * @param {PIXI.Graphics} graphics - The mask - */ - - - StencilManager.prototype.pushStencil = function pushStencil(graphics) { - this.renderer.setObjectRenderer(this.renderer.plugins.graphics); - - this.renderer._activeRenderTarget.attachStencilBuffer(); - - var gl = this.renderer.gl; - var sms = this.stencilMaskStack; - - if (sms.length === 0) { - gl.enable(gl.STENCIL_TEST); - gl.clear(gl.STENCIL_BUFFER_BIT); - gl.stencilFunc(gl.ALWAYS, 1, 1); - } - - sms.push(graphics); - - gl.colorMask(false, false, false, false); - gl.stencilFunc(gl.EQUAL, 0, sms.length); - gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); - - this.renderer.plugins.graphics.render(graphics); - - gl.colorMask(true, true, true, true); - gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); - gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); - }; - - /** - * TODO @alvin - */ - - - StencilManager.prototype.popStencil = function popStencil() { - this.renderer.setObjectRenderer(this.renderer.plugins.graphics); - - var gl = this.renderer.gl; - var sms = this.stencilMaskStack; - - var graphics = sms.pop(); - - if (sms.length === 0) { - // the stack is empty! - gl.disable(gl.STENCIL_TEST); - } else { - gl.colorMask(false, false, false, false); - gl.stencilFunc(gl.EQUAL, 0, sms.length); - gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); - - this.renderer.plugins.graphics.render(graphics); - - gl.colorMask(true, true, true, true); - gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); - gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); - } - }; - - /** - * Destroys the mask stack. - * - */ - - - StencilManager.prototype.destroy = function destroy() { - _WebGLManager3.default.prototype.destroy.call(this); - - this.stencilMaskStack.stencilStack = null; - }; - - return StencilManager; -}(_WebGLManager3.default); - -exports.default = StencilManager; - -},{"./WebGLManager":93}],93:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * @class - * @memberof PIXI - */ -var WebGLManager = function () { - /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. - */ - function WebGLManager(renderer) { - _classCallCheck(this, WebGLManager); - - /** - * The renderer this manager works for. - * - * @member {PIXI.WebGLRenderer} - */ - this.renderer = renderer; - - this.renderer.on('context', this.onContextChange, this); - } - - /** - * Generic method called when there is a WebGL context change. - * - */ - - - WebGLManager.prototype.onContextChange = function onContextChange() {} - // do some codes init! - - - /** - * Generic destroy methods to be overridden by the subclass - * - */ - ; - - WebGLManager.prototype.destroy = function destroy() { - this.renderer.off('context', this.onContextChange, this); - - this.renderer = null; - }; - - return WebGLManager; -}(); - -exports.default = WebGLManager; - -},{}],94:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _WebGLManager2 = require('../managers/WebGLManager'); - -var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * Base for a common object renderer that can be used as a system renderer plugin. - * - * @class - * @extends PIXI.WebGLManager - * @memberof PIXI - */ -var ObjectRenderer = function (_WebGLManager) { - _inherits(ObjectRenderer, _WebGLManager); - - function ObjectRenderer() { - _classCallCheck(this, ObjectRenderer); - - return _possibleConstructorReturn(this, _WebGLManager.apply(this, arguments)); - } - - /** - * Starts the renderer and sets the shader - * - */ - ObjectRenderer.prototype.start = function start() {} - // set the shader.. - - - /** - * Stops the renderer - * - */ - ; - - ObjectRenderer.prototype.stop = function stop() { - this.flush(); - }; - - /** - * Stub method for rendering content and emptying the current batch. - * - */ - - - ObjectRenderer.prototype.flush = function flush() {} - // flush! - - - /** - * Renders an object - * - * @param {PIXI.DisplayObject} object - The object to render. - */ - ; - - ObjectRenderer.prototype.render = function render(object) // eslint-disable-line no-unused-vars - { - // render the object - }; - - return ObjectRenderer; -}(_WebGLManager3.default); - -exports.default = ObjectRenderer; - -},{"../managers/WebGLManager":93}],95:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _pixiGlCore = require('pixi-gl-core'); - -var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); - -var _createIndicesForQuads = require('../../../utils/createIndicesForQuads'); - -var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * Helper class to create a quad - * - * @class - * @memberof PIXI - */ -var Quad = function () { - /** - * @param {WebGLRenderingContext} gl - The gl context for this quad to use. - * @param {object} state - TODO: Description - */ - function Quad(gl, state) { - _classCallCheck(this, Quad); - - /** - * the current WebGL drawing context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of vertices - * - * @member {Float32Array} - */ - this.vertices = new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]); - - /** - * The Uvs of the quad - * - * @member {Float32Array} - */ - this.uvs = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); - - this.interleaved = new Float32Array(8 * 2); - - for (var i = 0; i < 4; i++) { - this.interleaved[i * 4] = this.vertices[i * 2]; - this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; - this.interleaved[i * 4 + 2] = this.uvs[i * 2]; - this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; - } - - /** - * An array containing the indices of the vertices - * - * @member {Uint16Array} - */ - this.indices = (0, _createIndicesForQuads2.default)(1); - - /** - * The vertex buffer - * - * @member {glCore.GLBuffer} - */ - this.vertexBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.interleaved, gl.STATIC_DRAW); - - /** - * The index buffer - * - * @member {glCore.GLBuffer} - */ - this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); - - /** - * The vertex array object - * - * @member {glCore.VertexArrayObject} - */ - this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, state); - } - - /** - * Initialises the vaos and uses the shader. - * - * @param {PIXI.Shader} shader - the shader to use - */ - - - Quad.prototype.initVao = function initVao(shader) { - this.vao.clear().addIndex(this.indexBuffer).addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0).addAttribute(this.vertexBuffer, shader.attributes.aTextureCoord, this.gl.FLOAT, false, 4 * 4, 2 * 4); - }; - - /** - * Maps two Rectangle to the quad. - * - * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle - * @param {PIXI.Rectangle} destinationFrame - the second rectangle - * @return {PIXI.Quad} Returns itself. - */ - - - Quad.prototype.map = function map(targetTextureFrame, destinationFrame) { - var x = 0; // destinationFrame.x / targetTextureFrame.width; - var y = 0; // destinationFrame.y / targetTextureFrame.height; - - this.uvs[0] = x; - this.uvs[1] = y; - - this.uvs[2] = x + destinationFrame.width / targetTextureFrame.width; - this.uvs[3] = y; - - this.uvs[4] = x + destinationFrame.width / targetTextureFrame.width; - this.uvs[5] = y + destinationFrame.height / targetTextureFrame.height; - - this.uvs[6] = x; - this.uvs[7] = y + destinationFrame.height / targetTextureFrame.height; - - x = destinationFrame.x; - y = destinationFrame.y; - - this.vertices[0] = x; - this.vertices[1] = y; - - this.vertices[2] = x + destinationFrame.width; - this.vertices[3] = y; - - this.vertices[4] = x + destinationFrame.width; - this.vertices[5] = y + destinationFrame.height; - - this.vertices[6] = x; - this.vertices[7] = y + destinationFrame.height; - - return this; - }; - - /** - * Binds the buffer and uploads the data - * - * @return {PIXI.Quad} Returns itself. - */ - - - Quad.prototype.upload = function upload() { - for (var i = 0; i < 4; i++) { - this.interleaved[i * 4] = this.vertices[i * 2]; - this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; - this.interleaved[i * 4 + 2] = this.uvs[i * 2]; - this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; - } - - this.vertexBuffer.upload(this.interleaved); - - return this; - }; - - /** - * Removes this quad from WebGL - */ - - - Quad.prototype.destroy = function destroy() { - var gl = this.gl; - - gl.deleteBuffer(this.vertexBuffer); - gl.deleteBuffer(this.indexBuffer); - }; - - return Quad; -}(); - -exports.default = Quad; - -},{"../../../utils/createIndicesForQuads":122,"pixi-gl-core":12}],96:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _math = require('../../../math'); - -var _const = require('../../../const'); - -var _settings = require('../../../settings'); - -var _settings2 = _interopRequireDefault(_settings); - -var _pixiGlCore = require('pixi-gl-core'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * @class - * @memberof PIXI - */ -var RenderTarget = function () { - /** - * @param {WebGLRenderingContext} gl - The current WebGL drawing context - * @param {number} [width=0] - the horizontal range of the filter - * @param {number} [height=0] - the vertical range of the filter - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [resolution=1] - The current resolution / device pixel ratio - * @param {boolean} [root=false] - Whether this object is the root element or not - */ - function RenderTarget(gl, width, height, scaleMode, resolution, root) { - _classCallCheck(this, RenderTarget); - - // TODO Resolution could go here ( eg low res blurs ) - - /** - * The current WebGL drawing context. - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - // next time to create a frame buffer and texture - - /** - * A frame buffer - * - * @member {PIXI.glCore.GLFramebuffer} - */ - this.frameBuffer = null; - - /** - * The texture - * - * @member {PIXI.glCore.GLTexture} - */ - this.texture = null; - - /** - * The background colour of this render target, as an array of [r,g,b,a] values - * - * @member {number[]} - */ - this.clearColor = [0, 0, 0, 0]; - - /** - * The size of the object as a rectangle - * - * @member {PIXI.Rectangle} - */ - this.size = new _math.Rectangle(0, 0, 1, 1); - - /** - * The current resolution / device pixel ratio - * - * @member {number} - * @default 1 - */ - this.resolution = resolution || _settings2.default.RESOLUTION; - - /** - * The projection matrix - * - * @member {PIXI.Matrix} - */ - this.projectionMatrix = new _math.Matrix(); - - /** - * The object's transform - * - * @member {PIXI.Matrix} - */ - this.transform = null; - - /** - * The frame. - * - * @member {PIXI.Rectangle} - */ - this.frame = null; - - /** - * The stencil buffer stores masking data for the render target - * - * @member {glCore.GLBuffer} - */ - this.defaultFrame = new _math.Rectangle(); - this.destinationFrame = null; - this.sourceFrame = null; - - /** - * The stencil buffer stores masking data for the render target - * - * @member {glCore.GLBuffer} - */ - this.stencilBuffer = null; - - /** - * The data structure for the stencil masks - * - * @member {PIXI.Graphics[]} - */ - this.stencilMaskStack = []; - - /** - * Stores filter data for the render target - * - * @member {object[]} - */ - this.filterData = null; - - /** - * The scale mode. - * - * @member {number} - * @default PIXI.settings.SCALE_MODE - * @see PIXI.SCALE_MODES - */ - this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; - - /** - * Whether this object is the root element or not - * - * @member {boolean} - */ - this.root = root; - - if (!this.root) { - this.frameBuffer = _pixiGlCore.GLFramebuffer.createRGBA(gl, 100, 100); - - if (this.scaleMode === _const.SCALE_MODES.NEAREST) { - this.frameBuffer.texture.enableNearestScaling(); - } else { - this.frameBuffer.texture.enableLinearScaling(); - } - /* - A frame buffer needs a target to render to.. - create a texture and bind it attach it to the framebuffer.. - */ - - // this is used by the base texture - this.texture = this.frameBuffer.texture; - } else { - // make it a null framebuffer.. - this.frameBuffer = new _pixiGlCore.GLFramebuffer(gl, 100, 100); - this.frameBuffer.framebuffer = null; - } - - this.setFrame(); - - this.resize(width, height); - } - - /** - * Clears the filter texture. - * - * @param {number[]} [clearColor=this.clearColor] - Array of [r,g,b,a] to clear the framebuffer - */ - - - RenderTarget.prototype.clear = function clear(clearColor) { - var cc = clearColor || this.clearColor; - - this.frameBuffer.clear(cc[0], cc[1], cc[2], cc[3]); // r,g,b,a); - }; - - /** - * Binds the stencil buffer. - * - */ - - - RenderTarget.prototype.attachStencilBuffer = function attachStencilBuffer() { - // TODO check if stencil is done? - /** - * The stencil buffer is used for masking in pixi - * lets create one and then add attach it to the framebuffer.. - */ - if (!this.root) { - this.frameBuffer.enableStencil(); - } - }; - - /** - * Sets the frame of the render target. - * - * @param {Rectangle} destinationFrame - The destination frame. - * @param {Rectangle} sourceFrame - The source frame. - */ - - - RenderTarget.prototype.setFrame = function setFrame(destinationFrame, sourceFrame) { - this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; - this.sourceFrame = sourceFrame || this.sourceFrame || this.destinationFrame; - }; - - /** - * Binds the buffers and initialises the viewport. - * - */ - - - RenderTarget.prototype.activate = function activate() { - // TOOD refactor usage of frame.. - var gl = this.gl; - - // make sure the texture is unbound! - this.frameBuffer.bind(); - - this.calculateProjection(this.destinationFrame, this.sourceFrame); - - if (this.transform) { - this.projectionMatrix.append(this.transform); - } - - // TODO add a check as them may be the same! - if (this.destinationFrame !== this.sourceFrame) { - gl.enable(gl.SCISSOR_TEST); - gl.scissor(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); - } else { - gl.disable(gl.SCISSOR_TEST); - } - - // TODO - does not need to be updated all the time?? - gl.viewport(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); - }; - - /** - * Updates the projection matrix based on a projection frame (which is a rectangle) - * - * @param {Rectangle} destinationFrame - The destination frame. - * @param {Rectangle} sourceFrame - The source frame. - */ - - - RenderTarget.prototype.calculateProjection = function calculateProjection(destinationFrame, sourceFrame) { - var pm = this.projectionMatrix; - - sourceFrame = sourceFrame || destinationFrame; - - pm.identity(); - - // TODO: make dest scale source - if (!this.root) { - pm.a = 1 / destinationFrame.width * 2; - pm.d = 1 / destinationFrame.height * 2; - - pm.tx = -1 - sourceFrame.x * pm.a; - pm.ty = -1 - sourceFrame.y * pm.d; - } else { - pm.a = 1 / destinationFrame.width * 2; - pm.d = -1 / destinationFrame.height * 2; - - pm.tx = -1 - sourceFrame.x * pm.a; - pm.ty = 1 - sourceFrame.y * pm.d; - } - }; - - /** - * Resizes the texture to the specified width and height - * - * @param {number} width - the new width of the texture - * @param {number} height - the new height of the texture - */ - - - RenderTarget.prototype.resize = function resize(width, height) { - width = width | 0; - height = height | 0; - - if (this.size.width === width && this.size.height === height) { - return; - } - - this.size.width = width; - this.size.height = height; - - this.defaultFrame.width = width; - this.defaultFrame.height = height; - - this.frameBuffer.resize(width * this.resolution, height * this.resolution); - - var projectionFrame = this.frame || this.size; - - this.calculateProjection(projectionFrame); - }; - - /** - * Destroys the render target. - * - */ - - - RenderTarget.prototype.destroy = function destroy() { - this.frameBuffer.destroy(); - - this.frameBuffer = null; - this.texture = null; - }; - - return RenderTarget; -}(); - -exports.default = RenderTarget; - -},{"../../../const":46,"../../../math":70,"../../../settings":101,"pixi-gl-core":12}],97:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.default = checkMaxIfStatmentsInShader; - -var _pixiGlCore = require('pixi-gl-core'); - -var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var fragTemplate = ['precision mediump float;', 'void main(void){', 'float test = 0.1;', '%forloop%', 'gl_FragColor = vec4(0.0);', '}'].join('\n'); - -function checkMaxIfStatmentsInShader(maxIfs, gl) { - var createTempContext = !gl; - - if (maxIfs === 0) { - throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); - } - - if (createTempContext) { - var tinyCanvas = document.createElement('canvas'); - - tinyCanvas.width = 1; - tinyCanvas.height = 1; - - gl = _pixiGlCore2.default.createContext(tinyCanvas); - } - - var shader = gl.createShader(gl.FRAGMENT_SHADER); - - while (true) // eslint-disable-line no-constant-condition - { - var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); - - gl.shaderSource(shader, fragmentSrc); - gl.compileShader(shader); - - if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - maxIfs = maxIfs / 2 | 0; - } else { - // valid! - break; - } - } - - if (createTempContext) { - // get rid of context - if (gl.getExtension('WEBGL_lose_context')) { - gl.getExtension('WEBGL_lose_context').loseContext(); - } - } - - return maxIfs; -} - -function generateIfTestSrc(maxIfs) { - var src = ''; - - for (var i = 0; i < maxIfs; ++i) { - if (i > 0) { - src += '\nelse '; - } - - if (i < maxIfs - 1) { - src += 'if(test == ' + i + '.0){}'; - } - } - - return src; -} - -},{"pixi-gl-core":12}],98:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.default = mapWebGLBlendModesToPixi; - -var _const = require('../../../const'); - -/** - * Maps gl blend combinations to WebGL. - * - * @memberof PIXI - * @function mapWebGLBlendModesToPixi - * @private - * @param {WebGLRenderingContext} gl - The rendering context. - * @param {string[]} [array=[]] - The array to output into. - * @return {string[]} Mapped modes. - */ -function mapWebGLBlendModesToPixi(gl) { - var array = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; - - // TODO - premultiply alpha would be different. - // add a boolean for that! - array[_const.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[_const.BLEND_MODES.ADD] = [gl.ONE, gl.DST_ALPHA]; - array[_const.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; - array[_const.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR]; - array[_const.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[_const.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[_const.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[_const.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[_const.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[_const.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[_const.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[_const.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[_const.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[_const.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[_const.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[_const.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[_const.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - - // not-premultiplied blend modes - array[_const.BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[_const.BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.DST_ALPHA, gl.ONE, gl.DST_ALPHA]; - array[_const.BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_COLOR]; - - return array; -} - -},{"../../../const":46}],99:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.default = mapWebGLDrawModesToPixi; - -var _const = require('../../../const'); - -/** - * Generic Mask Stack data structure. - * - * @memberof PIXI - * @function mapWebGLDrawModesToPixi - * @private - * @param {WebGLRenderingContext} gl - The current WebGL drawing context - * @param {object} [object={}] - The object to map into - * @return {object} The mapped draw modes. - */ -function mapWebGLDrawModesToPixi(gl) { - var object = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - object[_const.DRAW_MODES.POINTS] = gl.POINTS; - object[_const.DRAW_MODES.LINES] = gl.LINES; - object[_const.DRAW_MODES.LINE_LOOP] = gl.LINE_LOOP; - object[_const.DRAW_MODES.LINE_STRIP] = gl.LINE_STRIP; - object[_const.DRAW_MODES.TRIANGLES] = gl.TRIANGLES; - object[_const.DRAW_MODES.TRIANGLE_STRIP] = gl.TRIANGLE_STRIP; - object[_const.DRAW_MODES.TRIANGLE_FAN] = gl.TRIANGLE_FAN; - - return object; -} - -},{"../../../const":46}],100:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.default = validateContext; -function validateContext(gl) { - var attributes = gl.getContextAttributes(); - - // this is going to be fairly simple for now.. but at least we have room to grow! - if (!attributes.stencil) { - /* eslint-disable no-console */ - console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); - /* eslint-enable no-console */ - } -} - -},{}],101:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _maxRecommendedTextures = require('./utils/maxRecommendedTextures'); - -var _maxRecommendedTextures2 = _interopRequireDefault(_maxRecommendedTextures); - -var _canUploadSameBuffer = require('./utils/canUploadSameBuffer'); - -var _canUploadSameBuffer2 = _interopRequireDefault(_canUploadSameBuffer); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * User's customizable globals for overriding the default PIXI settings, such - * as a renderer's default resolution, framerate, float percision, etc. - * @example - * // Use the native window resolution as the default resolution - * // will support high-density displays when rendering - * PIXI.settings.RESOLUTION = window.devicePixelRatio. - * - * // Disable interpolation when scaling, will make texture be pixelated - * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; - * @namespace PIXI.settings - */ -exports.default = { - - /** - * Target frames per millisecond. - * - * @static - * @memberof PIXI.settings - * @type {number} - * @default 0.06 - */ - TARGET_FPMS: 0.06, - - /** - * If set to true WebGL will attempt make textures mimpaped by default. - * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. - * - * @static - * @memberof PIXI.settings - * @type {boolean} - * @default true - */ - MIPMAP_TEXTURES: true, - - /** - * Default resolution / device pixel ratio of the renderer. - * - * @static - * @memberof PIXI.settings - * @type {number} - * @default 1 - */ - RESOLUTION: 1, - - /** - * Default filter resolution. - * - * @static - * @memberof PIXI.settings - * @type {number} - * @default 1 - */ - FILTER_RESOLUTION: 1, - - /** - * The maximum textures that this device supports. - * - * @static - * @memberof PIXI.settings - * @type {number} - * @default 32 - */ - SPRITE_MAX_TEXTURES: (0, _maxRecommendedTextures2.default)(32), - - // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 - // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 - - /** - * The default sprite batch size. - * - * The default aims to balance desktop and mobile devices. - * - * @static - * @memberof PIXI.settings - * @type {number} - * @default 4096 - */ - SPRITE_BATCH_SIZE: 4096, - - /** - * The prefix that denotes a URL is for a retina asset. - * - * @static - * @memberof PIXI.settings - * @type {RegExp} - * @example `@2x` - * @default /@([0-9\.]+)x/ - */ - RETINA_PREFIX: /@([0-9\.]+)x/, - - /** - * The default render options if none are supplied to {@link PIXI.WebGLRenderer} - * or {@link PIXI.CanvasRenderer}. - * - * @static - * @constant - * @memberof PIXI.settings - * @type {object} - * @property {HTMLCanvasElement} view=null - * @property {number} resolution=1 - * @property {boolean} antialias=false - * @property {boolean} forceFXAA=false - * @property {boolean} autoResize=false - * @property {boolean} transparent=false - * @property {number} backgroundColor=0x000000 - * @property {boolean} clearBeforeRender=true - * @property {boolean} preserveDrawingBuffer=false - * @property {boolean} roundPixels=false - * @property {number} width=800 - * @property {number} height=600 - * @property {boolean} legacy=false - */ - RENDER_OPTIONS: { - view: null, - antialias: false, - forceFXAA: false, - autoResize: false, - transparent: false, - backgroundColor: 0x000000, - clearBeforeRender: true, - preserveDrawingBuffer: false, - roundPixels: false, - width: 800, - height: 600, - legacy: false - }, - - /** - * Default transform type. - * - * @static - * @memberof PIXI.settings - * @type {PIXI.TRANSFORM_MODE} - * @default PIXI.TRANSFORM_MODE.STATIC - */ - TRANSFORM_MODE: 0, - - /** - * Default Garbage Collection mode. - * - * @static - * @memberof PIXI.settings - * @type {PIXI.GC_MODES} - * @default PIXI.GC_MODES.AUTO - */ - GC_MODE: 0, - - /** - * Default Garbage Collection max idle. - * - * @static - * @memberof PIXI.settings - * @type {number} - * @default 3600 - */ - GC_MAX_IDLE: 60 * 60, - - /** - * Default Garbage Collection maximum check count. - * - * @static - * @memberof PIXI.settings - * @type {number} - * @default 600 - */ - GC_MAX_CHECK_COUNT: 60 * 10, - - /** - * Default wrap modes that are supported by pixi. - * - * @static - * @memberof PIXI.settings - * @type {PIXI.WRAP_MODES} - * @default PIXI.WRAP_MODES.CLAMP - */ - WRAP_MODE: 0, - - /** - * The scale modes that are supported by pixi. - * - * @static - * @memberof PIXI.settings - * @type {PIXI.SCALE_MODES} - * @default PIXI.SCALE_MODES.LINEAR - */ - SCALE_MODE: 0, - - /** - * Default specify float precision in vertex shader. - * - * @static - * @memberof PIXI.settings - * @type {PIXI.PRECISION} - * @default PIXI.PRECISION.HIGH - */ - PRECISION_VERTEX: 'highp', - - /** - * Default specify float precision in fragment shader. - * - * @static - * @memberof PIXI.settings - * @type {PIXI.PRECISION} - * @default PIXI.PRECISION.MEDIUM - */ - PRECISION_FRAGMENT: 'mediump', - - /** - * Can we upload the same buffer in a single frame? - * - * @static - * @constant - * @memberof PIXI - * @type {boolean} - */ - CAN_UPLOAD_SAME_BUFFER: (0, _canUploadSameBuffer2.default)() - -}; - -},{"./utils/canUploadSameBuffer":121,"./utils/maxRecommendedTextures":126}],102:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _math = require('../math'); - -var _utils = require('../utils'); - -var _const = require('../const'); - -var _Texture = require('../textures/Texture'); - -var _Texture2 = _interopRequireDefault(_Texture); - -var _Container2 = require('../display/Container'); - -var _Container3 = _interopRequireDefault(_Container2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -var tempPoint = new _math.Point(); - -/** - * The Sprite object is the base for all textured objects that are rendered to the screen - * - * A sprite can be created directly from an image like this: - * - * ```js - * let sprite = new PIXI.Sprite.fromImage('assets/image.png'); - * ``` - * - * @class - * @extends PIXI.Container - * @memberof PIXI - */ - -var Sprite = function (_Container) { - _inherits(Sprite, _Container); - - /** - * @param {PIXI.Texture} texture - The texture for this sprite - */ - function Sprite(texture) { - _classCallCheck(this, Sprite); - - /** - * The anchor sets the origin point of the texture. - * The default is 0,0 this means the texture's origin is the top left - * Setting the anchor to 0.5,0.5 means the texture's origin is centered - * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner - * - * @member {PIXI.ObservablePoint} - * @private - */ - var _this = _possibleConstructorReturn(this, _Container.call(this)); - - _this._anchor = new _math.ObservablePoint(_this._onAnchorUpdate, _this); - - /** - * The texture that the sprite is using - * - * @private - * @member {PIXI.Texture} - */ - _this._texture = null; - - /** - * The width of the sprite (this is initially set by the texture) - * - * @private - * @member {number} - */ - _this._width = 0; - - /** - * The height of the sprite (this is initially set by the texture) - * - * @private - * @member {number} - */ - _this._height = 0; - - /** - * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. - * - * @private - * @member {number} - * @default 0xFFFFFF - */ - _this._tint = null; - _this._tintRGB = null; - _this.tint = 0xFFFFFF; - - /** - * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. - * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL - * @see PIXI.BLEND_MODES - */ - _this.blendMode = _const.BLEND_MODES.NORMAL; - - /** - * The shader that will be used to render the sprite. Set to null to remove a current shader. - * - * @member {PIXI.Filter|PIXI.Shader} - */ - _this.shader = null; - - /** - * An internal cached value of the tint. - * - * @private - * @member {number} - * @default 0xFFFFFF - */ - _this.cachedTint = 0xFFFFFF; - - // call texture setter - _this.texture = texture || _Texture2.default.EMPTY; - - /** - * this is used to store the vertex data of the sprite (basically a quad) - * - * @private - * @member {Float32Array} - */ - _this.vertexData = new Float32Array(8); - - /** - * This is used to calculate the bounds of the object IF it is a trimmed sprite - * - * @private - * @member {Float32Array} - */ - _this.vertexTrimmedData = null; - - _this._transformID = -1; - _this._textureID = -1; - - _this._transformTrimmedID = -1; - _this._textureTrimmedID = -1; - - /** - * Plugin that is responsible for rendering this element. - * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. - * - * @member {string} - * @default 'sprite' - */ - _this.pluginName = 'sprite'; - return _this; - } - - /** - * When the texture is updated, this event will fire to update the scale and frame - * - * @private - */ - - - Sprite.prototype._onTextureUpdate = function _onTextureUpdate() { - this._textureID = -1; - this._textureTrimmedID = -1; - - // so if _width is 0 then width was not set.. - if (this._width) { - this.scale.x = (0, _utils.sign)(this.scale.x) * this._width / this._texture.orig.width; - } - - if (this._height) { - this.scale.y = (0, _utils.sign)(this.scale.y) * this._height / this._texture.orig.height; - } - }; - - /** - * Called when the anchor position updates. - * - * @private - */ - - - Sprite.prototype._onAnchorUpdate = function _onAnchorUpdate() { - this._transformID = -1; - this._transformTrimmedID = -1; - }; - - /** - * calculates worldTransform * vertices, store it in vertexData - */ - - - Sprite.prototype.calculateVertices = function calculateVertices() { - if (this._transformID === this.transform._worldID && this._textureID === this._texture._updateID) { - return; - } - - this._transformID = this.transform._worldID; - this._textureID = this._texture._updateID; - - // set the vertex data - - var texture = this._texture; - var wt = this.transform.worldTransform; - var a = wt.a; - var b = wt.b; - var c = wt.c; - var d = wt.d; - var tx = wt.tx; - var ty = wt.ty; - var vertexData = this.vertexData; - var trim = texture.trim; - var orig = texture.orig; - var anchor = this._anchor; - - var w0 = 0; - var w1 = 0; - var h0 = 0; - var h1 = 0; - - if (trim) { - // if the sprite is trimmed and is not a tilingsprite then we need to add the extra - // space before transforming the sprite coords. - w1 = trim.x - anchor._x * orig.width; - w0 = w1 + trim.width; - - h1 = trim.y - anchor._y * orig.height; - h0 = h1 + trim.height; - } else { - w1 = -anchor._x * orig.width; - w0 = w1 + orig.width; - - h1 = -anchor._y * orig.height; - h0 = h1 + orig.height; - } - - // xy - vertexData[0] = a * w1 + c * h1 + tx; - vertexData[1] = d * h1 + b * w1 + ty; - - // xy - vertexData[2] = a * w0 + c * h1 + tx; - vertexData[3] = d * h1 + b * w0 + ty; - - // xy - vertexData[4] = a * w0 + c * h0 + tx; - vertexData[5] = d * h0 + b * w0 + ty; - - // xy - vertexData[6] = a * w1 + c * h0 + tx; - vertexData[7] = d * h0 + b * w1 + ty; - }; - - /** - * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData - * This is used to ensure that the true width and height of a trimmed texture is respected - */ - - - Sprite.prototype.calculateTrimmedVertices = function calculateTrimmedVertices() { - if (!this.vertexTrimmedData) { - this.vertexTrimmedData = new Float32Array(8); - } else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { - return; - } - - this._transformTrimmedID = this.transform._worldID; - this._textureTrimmedID = this._texture._updateID; - - // lets do some special trim code! - var texture = this._texture; - var vertexData = this.vertexTrimmedData; - var orig = texture.orig; - var anchor = this._anchor; - - // lets calculate the new untrimmed bounds.. - var wt = this.transform.worldTransform; - var a = wt.a; - var b = wt.b; - var c = wt.c; - var d = wt.d; - var tx = wt.tx; - var ty = wt.ty; - - var w1 = -anchor._x * orig.width; - var w0 = w1 + orig.width; - - var h1 = -anchor._y * orig.height; - var h0 = h1 + orig.height; - - // xy - vertexData[0] = a * w1 + c * h1 + tx; - vertexData[1] = d * h1 + b * w1 + ty; - - // xy - vertexData[2] = a * w0 + c * h1 + tx; - vertexData[3] = d * h1 + b * w0 + ty; - - // xy - vertexData[4] = a * w0 + c * h0 + tx; - vertexData[5] = d * h0 + b * w0 + ty; - - // xy - vertexData[6] = a * w1 + c * h0 + tx; - vertexData[7] = d * h0 + b * w1 + ty; - }; - - /** - * - * Renders the object using the WebGL renderer - * - * @private - * @param {PIXI.WebGLRenderer} renderer - The webgl renderer to use. - */ - - - Sprite.prototype._renderWebGL = function _renderWebGL(renderer) { - this.calculateVertices(); - - renderer.setObjectRenderer(renderer.plugins[this.pluginName]); - renderer.plugins[this.pluginName].render(this); - }; - - /** - * Renders the object using the Canvas renderer - * - * @private - * @param {PIXI.CanvasRenderer} renderer - The renderer - */ - - - Sprite.prototype._renderCanvas = function _renderCanvas(renderer) { - renderer.plugins[this.pluginName].render(this); - }; - - /** - * Updates the bounds of the sprite. - * - * @private - */ - - - Sprite.prototype._calculateBounds = function _calculateBounds() { - var trim = this._texture.trim; - var orig = this._texture.orig; - - // First lets check to see if the current texture has a trim.. - if (!trim || trim.width === orig.width && trim.height === orig.height) { - // no trim! lets use the usual calculations.. - this.calculateVertices(); - this._bounds.addQuad(this.vertexData); - } else { - // lets calculate a special trimmed bounds... - this.calculateTrimmedVertices(); - this._bounds.addQuad(this.vertexTrimmedData); - } - }; - - /** - * Gets the local bounds of the sprite object. - * - * @param {PIXI.Rectangle} rect - The output rectangle. - * @return {PIXI.Rectangle} The bounds. - */ - - - Sprite.prototype.getLocalBounds = function getLocalBounds(rect) { - // we can do a fast local bounds if the sprite has no children! - if (this.children.length === 0) { - this._bounds.minX = this._texture.orig.width * -this._anchor._x; - this._bounds.minY = this._texture.orig.height * -this._anchor._y; - this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x); - this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._x); - - if (!rect) { - if (!this._localBoundsRect) { - this._localBoundsRect = new _math.Rectangle(); - } - - rect = this._localBoundsRect; - } - - return this._bounds.getRectangle(rect); - } - - return _Container.prototype.getLocalBounds.call(this, rect); - }; - - /** - * Tests if a point is inside this sprite - * - * @param {PIXI.Point} point - the point to test - * @return {boolean} the result of the test - */ - - - Sprite.prototype.containsPoint = function containsPoint(point) { - this.worldTransform.applyInverse(point, tempPoint); - - var width = this._texture.orig.width; - var height = this._texture.orig.height; - var x1 = -width * this.anchor.x; - var y1 = 0; - - if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { - y1 = -height * this.anchor.y; - - if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { - return true; - } - } - - return false; - }; - - /** - * Destroys this sprite and optionally its texture and children - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy - * method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well - * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well - */ - - - Sprite.prototype.destroy = function destroy(options) { - _Container.prototype.destroy.call(this, options); - - this._anchor = null; - - var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; - - if (destroyTexture) { - var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; - - this._texture.destroy(!!destroyBaseTexture); - } - - this._texture = null; - this.shader = null; - }; - - // some helper functions.. - - /** - * Helper function that creates a new sprite based on the source you provide. - * The source can be - frame id, image url, video url, canvas element, video element, base texture - * - * @static - * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from - * @return {PIXI.Sprite} The newly created sprite - */ - - - Sprite.from = function from(source) { - return new Sprite(_Texture2.default.from(source)); - }; - - /** - * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId - * The frame ids are created when a Texture packer file has been loaded - * - * @static - * @param {string} frameId - The frame Id of the texture in the cache - * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the frameId - */ - - - Sprite.fromFrame = function fromFrame(frameId) { - var texture = _utils.TextureCache[frameId]; - - if (!texture) { - throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); - } - - return new Sprite(texture); - }; - - /** - * Helper function that creates a sprite that will contain a texture based on an image url - * If the image is not in the texture cache it will be loaded - * - * @static - * @param {string} imageId - The image url of the texture - * @param {boolean} [crossorigin=(auto)] - if you want to specify the cross-origin parameter - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, - * see {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the image id - */ - - - Sprite.fromImage = function fromImage(imageId, crossorigin, scaleMode) { - return new Sprite(_Texture2.default.fromImage(imageId, crossorigin, scaleMode)); - }; - - /** - * The width of the sprite, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - - - _createClass(Sprite, [{ - key: 'width', - get: function get() { - return Math.abs(this.scale.x) * this._texture.orig.width; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - var s = (0, _utils.sign)(this.scale.x) || 1; - - this.scale.x = s * value / this._texture.orig.width; - this._width = value; - } - - /** - * The height of the sprite, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - - }, { - key: 'height', - get: function get() { - return Math.abs(this.scale.y) * this._texture.orig.height; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - var s = (0, _utils.sign)(this.scale.y) || 1; - - this.scale.y = s * value / this._texture.orig.height; - this._height = value; - } - - /** - * The anchor sets the origin point of the texture. - * The default is 0,0 this means the texture's origin is the top left - * Setting the anchor to 0.5,0.5 means the texture's origin is centered - * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner - * - * @member {PIXI.ObservablePoint} - */ - - }, { - key: 'anchor', - get: function get() { - return this._anchor; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._anchor.copy(value); - } - - /** - * The tint applied to the sprite. This is a hex value. - * A value of 0xFFFFFF will remove any tint effect. - * - * @member {number} - * @default 0xFFFFFF - */ - - }, { - key: 'tint', - get: function get() { - return this._tint; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._tint = value; - this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); - } - - /** - * The texture that the sprite is using - * - * @member {PIXI.Texture} - */ - - }, { - key: 'texture', - get: function get() { - return this._texture; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - if (this._texture === value) { - return; - } - - this._texture = value; - this.cachedTint = 0xFFFFFF; - - this._textureID = -1; - this._textureTrimmedID = -1; - - if (value) { - // wait for the texture to load - if (value.baseTexture.hasLoaded) { - this._onTextureUpdate(); - } else { - value.once('update', this._onTextureUpdate, this); - } - } - } - }]); - - return Sprite; -}(_Container3.default); - -exports.default = Sprite; - -},{"../const":46,"../display/Container":48,"../math":70,"../textures/Texture":115,"../utils":124}],103:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); - -var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); - -var _const = require('../../const'); - -var _math = require('../../math'); - -var _CanvasTinter = require('./CanvasTinter'); - -var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var canvasRenderWorldTransform = new _math.Matrix(); - -/** - * @author Mat Groves - * - * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ - * for creating the original PixiJS version! - * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now - * share 4 bytes on the vertex buffer - * - * Heavily inspired by LibGDX's CanvasSpriteRenderer: - * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasSpriteRenderer.java - */ - -/** - * Renderer dedicated to drawing and batching sprites. - * - * @class - * @private - * @memberof PIXI - */ - -var CanvasSpriteRenderer = function () { - /** - * @param {PIXI.WebGLRenderer} renderer -The renderer sprite this batch works for. - */ - function CanvasSpriteRenderer(renderer) { - _classCallCheck(this, CanvasSpriteRenderer); - - this.renderer = renderer; - } - - /** - * Renders the sprite object. - * - * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch - */ - - - CanvasSpriteRenderer.prototype.render = function render(sprite) { - var texture = sprite._texture; - var renderer = this.renderer; - - var width = texture._frame.width; - var height = texture._frame.height; - - var wt = sprite.transform.worldTransform; - var dx = 0; - var dy = 0; - - if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.baseTexture.source) { - return; - } - - renderer.setBlendMode(sprite.blendMode); - - // Ignore null sources - if (texture.valid) { - renderer.context.globalAlpha = sprite.worldAlpha; - - // If smoothingEnabled is supported and we need to change the smoothing property for sprite texture - var smoothingEnabled = texture.baseTexture.scaleMode === _const.SCALE_MODES.LINEAR; - - if (renderer.smoothProperty && renderer.context[renderer.smoothProperty] !== smoothingEnabled) { - renderer.context[renderer.smoothProperty] = smoothingEnabled; - } - - if (texture.trim) { - dx = texture.trim.width / 2 + texture.trim.x - sprite.anchor.x * texture.orig.width; - dy = texture.trim.height / 2 + texture.trim.y - sprite.anchor.y * texture.orig.height; - } else { - dx = (0.5 - sprite.anchor.x) * texture.orig.width; - dy = (0.5 - sprite.anchor.y) * texture.orig.height; - } - - if (texture.rotate) { - wt.copy(canvasRenderWorldTransform); - wt = canvasRenderWorldTransform; - _math.GroupD8.matrixAppendRotationInv(wt, texture.rotate, dx, dy); - // the anchor has already been applied above, so lets set it to zero - dx = 0; - dy = 0; - } - - dx -= width / 2; - dy -= height / 2; - - // Allow for pixel rounding - if (renderer.roundPixels) { - renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution | 0, wt.ty * renderer.resolution | 0); - - dx = dx | 0; - dy = dy | 0; - } else { - renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution, wt.ty * renderer.resolution); - } - - var resolution = texture.baseTexture.resolution; - - if (sprite.tint !== 0xFFFFFF) { - if (sprite.cachedTint !== sprite.tint || sprite.tintedTexture.tintId !== sprite._texture._updateID) { - sprite.cachedTint = sprite.tint; - - // TODO clean up caching - how to clean up the caches? - sprite.tintedTexture = _CanvasTinter2.default.getTintedTexture(sprite, sprite.tint); - } - - renderer.context.drawImage(sprite.tintedTexture, 0, 0, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); - } else { - renderer.context.drawImage(texture.baseTexture.source, texture._frame.x * resolution, texture._frame.y * resolution, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); - } - } - }; - - /** - * destroy the sprite object. - * - */ - - - CanvasSpriteRenderer.prototype.destroy = function destroy() { - this.renderer = null; - }; - - return CanvasSpriteRenderer; -}(); - -exports.default = CanvasSpriteRenderer; - - -_CanvasRenderer2.default.registerPlugin('sprite', CanvasSpriteRenderer); - -},{"../../const":46,"../../math":70,"../../renderers/canvas/CanvasRenderer":77,"./CanvasTinter":104}],104:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _utils = require('../../utils'); - -var _canUseNewCanvasBlendModes = require('../../renderers/canvas/utils/canUseNewCanvasBlendModes'); - -var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Utility methods for Sprite/Texture tinting. - * - * @class - * @memberof PIXI - */ -var CanvasTinter = { - /** - * Basically this method just needs a sprite and a color and tints the sprite with the given color. - * - * @memberof PIXI.CanvasTinter - * @param {PIXI.Sprite} sprite - the sprite to tint - * @param {number} color - the color to use to tint the sprite with - * @return {HTMLCanvasElement} The tinted canvas - */ - getTintedTexture: function getTintedTexture(sprite, color) { - var texture = sprite._texture; - - color = CanvasTinter.roundColor(color); - - var stringColor = '#' + ('00000' + (color | 0).toString(16)).substr(-6); - - texture.tintCache = texture.tintCache || {}; - - var cachedTexture = texture.tintCache[stringColor]; - - var canvas = void 0; - - if (cachedTexture) { - if (cachedTexture.tintId === texture._updateID) { - return texture.tintCache[stringColor]; - } - - canvas = texture.tintCache[stringColor]; - } else { - canvas = CanvasTinter.canvas || document.createElement('canvas'); - } - - CanvasTinter.tintMethod(texture, color, canvas); - - canvas.tintId = texture._updateID; - - if (CanvasTinter.convertTintToImage) { - // is this better? - var tintImage = new Image(); - - tintImage.src = canvas.toDataURL(); - - texture.tintCache[stringColor] = tintImage; - } else { - texture.tintCache[stringColor] = canvas; - // if we are not converting the texture to an image then we need to lose the reference to the canvas - CanvasTinter.canvas = null; - } - - return canvas; - }, - - /** - * Tint a texture using the 'multiply' operation. - * - * @memberof PIXI.CanvasTinter - * @param {PIXI.Texture} texture - the texture to tint - * @param {number} color - the color to use to tint the sprite with - * @param {HTMLCanvasElement} canvas - the current canvas - */ - tintWithMultiply: function tintWithMultiply(texture, color, canvas) { - var context = canvas.getContext('2d'); - var crop = texture._frame.clone(); - var resolution = texture.baseTexture.resolution; - - crop.x *= resolution; - crop.y *= resolution; - crop.width *= resolution; - crop.height *= resolution; - - canvas.width = Math.ceil(crop.width); - canvas.height = Math.ceil(crop.height); - - context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); - - context.fillRect(0, 0, crop.width, crop.height); - - context.globalCompositeOperation = 'multiply'; - - context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); - - context.globalCompositeOperation = 'destination-atop'; - - context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); - }, - - /** - * Tint a texture using the 'overlay' operation. - * - * @memberof PIXI.CanvasTinter - * @param {PIXI.Texture} texture - the texture to tint - * @param {number} color - the color to use to tint the sprite with - * @param {HTMLCanvasElement} canvas - the current canvas - */ - tintWithOverlay: function tintWithOverlay(texture, color, canvas) { - var context = canvas.getContext('2d'); - var crop = texture._frame.clone(); - var resolution = texture.baseTexture.resolution; - - crop.x *= resolution; - crop.y *= resolution; - crop.width *= resolution; - crop.height *= resolution; - - canvas.width = Math.ceil(crop.width); - canvas.height = Math.ceil(crop.height); - - context.globalCompositeOperation = 'copy'; - context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); - context.fillRect(0, 0, crop.width, crop.height); - - context.globalCompositeOperation = 'destination-atop'; - context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); - - // context.globalCompositeOperation = 'copy'; - }, - - - /** - * Tint a texture pixel per pixel. - * - * @memberof PIXI.CanvasTinter - * @param {PIXI.Texture} texture - the texture to tint - * @param {number} color - the color to use to tint the sprite with - * @param {HTMLCanvasElement} canvas - the current canvas - */ - tintWithPerPixel: function tintWithPerPixel(texture, color, canvas) { - var context = canvas.getContext('2d'); - var crop = texture._frame.clone(); - var resolution = texture.baseTexture.resolution; - - crop.x *= resolution; - crop.y *= resolution; - crop.width *= resolution; - crop.height *= resolution; - - canvas.width = Math.ceil(crop.width); - canvas.height = Math.ceil(crop.height); - - context.globalCompositeOperation = 'copy'; - context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); - - var rgbValues = (0, _utils.hex2rgb)(color); - var r = rgbValues[0]; - var g = rgbValues[1]; - var b = rgbValues[2]; - - var pixelData = context.getImageData(0, 0, crop.width, crop.height); - - var pixels = pixelData.data; - - for (var i = 0; i < pixels.length; i += 4) { - pixels[i + 0] *= r; - pixels[i + 1] *= g; - pixels[i + 2] *= b; - } - - context.putImageData(pixelData, 0, 0); - }, - - /** - * Rounds the specified color according to the CanvasTinter.cacheStepsPerColorChannel. - * - * @memberof PIXI.CanvasTinter - * @param {number} color - the color to round, should be a hex color - * @return {number} The rounded color. - */ - roundColor: function roundColor(color) { - var step = CanvasTinter.cacheStepsPerColorChannel; - - var rgbValues = (0, _utils.hex2rgb)(color); - - rgbValues[0] = Math.min(255, rgbValues[0] / step * step); - rgbValues[1] = Math.min(255, rgbValues[1] / step * step); - rgbValues[2] = Math.min(255, rgbValues[2] / step * step); - - return (0, _utils.rgb2hex)(rgbValues); - }, - - /** - * Number of steps which will be used as a cap when rounding colors. - * - * @memberof PIXI.CanvasTinter - * @type {number} - */ - cacheStepsPerColorChannel: 8, - - /** - * Tint cache boolean flag. - * - * @memberof PIXI.CanvasTinter - * @type {boolean} - */ - convertTintToImage: false, - - /** - * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method. - * - * @memberof PIXI.CanvasTinter - * @type {boolean} - */ - canUseMultiply: (0, _canUseNewCanvasBlendModes2.default)(), - - /** - * The tinting method that will be used. - * - * @memberof PIXI.CanvasTinter - * @type {tintMethodFunctionType} - */ - tintMethod: 0 -}; - -CanvasTinter.tintMethod = CanvasTinter.canUseMultiply ? CanvasTinter.tintWithMultiply : CanvasTinter.tintWithPerPixel; - -/** - * The tintMethod type. - * - * @memberof PIXI.CanvasTinter - * @callback tintMethodFunctionType - * @param texture {PIXI.Texture} the texture to tint - * @param color {number} the color to use to tint the sprite with - * @param canvas {HTMLCanvasElement} the current canvas - */ - -exports.default = CanvasTinter; - -},{"../../renderers/canvas/utils/canUseNewCanvasBlendModes":80,"../../utils":124}],105:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * @class - * @memberof PIXI - */ -var Buffer = function () { - /** - * @param {number} size - The size of the buffer in bytes. - */ - function Buffer(size) { - _classCallCheck(this, Buffer); - - this.vertices = new ArrayBuffer(size); - - /** - * View on the vertices as a Float32Array for positions - * - * @member {Float32Array} - */ - this.float32View = new Float32Array(this.vertices); - - /** - * View on the vertices as a Uint32Array for uvs - * - * @member {Float32Array} - */ - this.uint32View = new Uint32Array(this.vertices); - } - - /** - * Destroys the buffer. - * - */ - - - Buffer.prototype.destroy = function destroy() { - this.vertices = null; - this.positions = null; - this.uvs = null; - this.colors = null; - }; - - return Buffer; -}(); - -exports.default = Buffer; - -},{}],106:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); - -var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); - -var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); - -var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); - -var _createIndicesForQuads = require('../../utils/createIndicesForQuads'); - -var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); - -var _generateMultiTextureShader = require('./generateMultiTextureShader'); - -var _generateMultiTextureShader2 = _interopRequireDefault(_generateMultiTextureShader); - -var _checkMaxIfStatmentsInShader = require('../../renderers/webgl/utils/checkMaxIfStatmentsInShader'); - -var _checkMaxIfStatmentsInShader2 = _interopRequireDefault(_checkMaxIfStatmentsInShader); - -var _BatchBuffer = require('./BatchBuffer'); - -var _BatchBuffer2 = _interopRequireDefault(_BatchBuffer); - -var _settings = require('../../settings'); - -var _settings2 = _interopRequireDefault(_settings); - -var _utils = require('../../utils'); - -var _pixiGlCore = require('pixi-gl-core'); - -var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); - -var _bitTwiddle = require('bit-twiddle'); - -var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -var TICK = 0; -var TEXTURE_TICK = 0; - -/** - * Renderer dedicated to drawing and batching sprites. - * - * @class - * @private - * @memberof PIXI - * @extends PIXI.ObjectRenderer - */ - -var SpriteRenderer = function (_ObjectRenderer) { - _inherits(SpriteRenderer, _ObjectRenderer); - - /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. - */ - function SpriteRenderer(renderer) { - _classCallCheck(this, SpriteRenderer); - - /** - * Number of values sent in the vertex buffer. - * aVertexPosition(2), aTextureCoord(1), aColor(1), aTextureId(1) = 5 - * - * @member {number} - */ - var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); - - _this.vertSize = 5; - - /** - * The size of the vertex information in bytes. - * - * @member {number} - */ - _this.vertByteSize = _this.vertSize * 4; - - /** - * The number of images in the SpriteRenderer before it flushes. - * - * @member {number} - */ - _this.size = _settings2.default.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop - - // the total number of bytes in our batch - // let numVerts = this.size * 4 * this.vertByteSize; - - _this.buffers = []; - for (var i = 1; i <= _bitTwiddle2.default.nextPow2(_this.size); i *= 2) { - _this.buffers.push(new _BatchBuffer2.default(i * 4 * _this.vertByteSize)); - } - - /** - * Holds the indices of the geometry (quads) to draw - * - * @member {Uint16Array} - */ - _this.indices = (0, _createIndicesForQuads2.default)(_this.size); - - /** - * The default shaders that is used if a sprite doesn't have a more specific one. - * there is a shader for each number of textures that can be rendererd. - * These shaders will also be generated on the fly as required. - * @member {PIXI.Shader[]} - */ - _this.shader = null; - - _this.currentIndex = 0; - _this.groups = []; - - for (var k = 0; k < _this.size; k++) { - _this.groups[k] = { textures: [], textureCount: 0, ids: [], size: 0, start: 0, blend: 0 }; - } - - _this.sprites = []; - - _this.vertexBuffers = []; - _this.vaos = []; - - _this.vaoMax = 2; - _this.vertexCount = 0; - - _this.renderer.on('prerender', _this.onPrerender, _this); - return _this; - } - - /** - * Sets up the renderer context and necessary buffers. - * - * @private - */ - - - SpriteRenderer.prototype.onContextChange = function onContextChange() { - var gl = this.renderer.gl; - - if (this.renderer.legacy) { - this.MAX_TEXTURES = 1; - } else { - // step 1: first check max textures the GPU can handle. - this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), _settings2.default.SPRITE_MAX_TEXTURES); - - // step 2: check the maximum number of if statements the shader can have too.. - this.MAX_TEXTURES = (0, _checkMaxIfStatmentsInShader2.default)(this.MAX_TEXTURES, gl); - } - - this.shader = (0, _generateMultiTextureShader2.default)(gl, this.MAX_TEXTURES); - - // create a couple of buffers - this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); - - // we use the second shader as the first one depending on your browser may omit aTextureId - // as it is not used by the shader so is optimized out. - - this.renderer.bindVao(null); - - var attrs = this.shader.attributes; - - for (var i = 0; i < this.vaoMax; i++) { - /* eslint-disable max-len */ - var vertexBuffer = this.vertexBuffers[i] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); - /* eslint-enable max-len */ - - // build the vao object that will render.. - var vao = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(vertexBuffer, attrs.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(vertexBuffer, attrs.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(vertexBuffer, attrs.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); - - if (attrs.aTextureId) { - vao.addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); - } - - this.vaos[i] = vao; - } - - this.vao = this.vaos[0]; - this.currentBlendMode = 99999; - - this.boundTextures = new Array(this.MAX_TEXTURES); - }; - - /** - * Called before the renderer starts rendering. - * - */ - - - SpriteRenderer.prototype.onPrerender = function onPrerender() { - this.vertexCount = 0; - }; - - /** - * Renders the sprite object. - * - * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch - */ - - - SpriteRenderer.prototype.render = function render(sprite) { - // TODO set blend modes.. - // check texture.. - if (this.currentIndex >= this.size) { - this.flush(); - } - - // get the uvs for the texture - - // if the uvs have not updated then no point rendering just yet! - if (!sprite._texture._uvs) { - return; - } - - // push a texture. - // increment the batchsize - this.sprites[this.currentIndex++] = sprite; - }; - - /** - * Renders the content and empties the current batch. - * - */ - - - SpriteRenderer.prototype.flush = function flush() { - if (this.currentIndex === 0) { - return; - } - - var gl = this.renderer.gl; - var MAX_TEXTURES = this.MAX_TEXTURES; - - var np2 = _bitTwiddle2.default.nextPow2(this.currentIndex); - var log2 = _bitTwiddle2.default.log2(np2); - var buffer = this.buffers[log2]; - - var sprites = this.sprites; - var groups = this.groups; - - var float32View = buffer.float32View; - var uint32View = buffer.uint32View; - - var boundTextures = this.boundTextures; - var rendererBoundTextures = this.renderer.boundTextures; - var touch = this.renderer.textureGC.count; - - var index = 0; - var nextTexture = void 0; - var currentTexture = void 0; - var groupCount = 1; - var textureCount = 0; - var currentGroup = groups[0]; - var vertexData = void 0; - var uvs = void 0; - var blendMode = _utils.premultiplyBlendMode[sprites[0]._texture.baseTexture.premultipliedAlpha ? 1 : 0][sprites[0].blendMode]; - - currentGroup.textureCount = 0; - currentGroup.start = 0; - currentGroup.blend = blendMode; - - TICK++; - - var i = void 0; - - // copy textures.. - for (i = 0; i < MAX_TEXTURES; ++i) { - boundTextures[i] = rendererBoundTextures[i]; - boundTextures[i]._virtalBoundId = i; - } - - for (i = 0; i < this.currentIndex; ++i) { - // upload the sprite elemetns... - // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; - - nextTexture = sprite._texture.baseTexture; - - var spriteBlendMode = _utils.premultiplyBlendMode[Number(nextTexture.premultipliedAlpha)][sprite.blendMode]; - - if (blendMode !== spriteBlendMode) { - // finish a group.. - blendMode = spriteBlendMode; - - // force the batch to break! - currentTexture = null; - textureCount = MAX_TEXTURES; - TICK++; - } - - if (currentTexture !== nextTexture) { - currentTexture = nextTexture; - - if (nextTexture._enabled !== TICK) { - if (textureCount === MAX_TEXTURES) { - TICK++; - - currentGroup.size = i - currentGroup.start; - - textureCount = 0; - - currentGroup = groups[groupCount++]; - currentGroup.blend = blendMode; - currentGroup.textureCount = 0; - currentGroup.start = i; - } - - nextTexture.touched = touch; - - if (nextTexture._virtalBoundId === -1) { - for (var j = 0; j < MAX_TEXTURES; ++j) { - var tIndex = (j + TEXTURE_TICK) % MAX_TEXTURES; - - var t = boundTextures[tIndex]; - - if (t._enabled !== TICK) { - TEXTURE_TICK++; - - t._virtalBoundId = -1; - - nextTexture._virtalBoundId = tIndex; - - boundTextures[tIndex] = nextTexture; - break; - } - } - } - - nextTexture._enabled = TICK; - - currentGroup.textureCount++; - currentGroup.ids[textureCount] = nextTexture._virtalBoundId; - currentGroup.textures[textureCount++] = nextTexture; - } - } - - vertexData = sprite.vertexData; - - // TODO this sum does not need to be set each frame.. - uvs = sprite._texture._uvs.uvsUint32; - - if (this.renderer.roundPixels) { - var resolution = this.renderer.resolution; - - // xy - float32View[index] = (vertexData[0] * resolution | 0) / resolution; - float32View[index + 1] = (vertexData[1] * resolution | 0) / resolution; - - // xy - float32View[index + 5] = (vertexData[2] * resolution | 0) / resolution; - float32View[index + 6] = (vertexData[3] * resolution | 0) / resolution; - - // xy - float32View[index + 10] = (vertexData[4] * resolution | 0) / resolution; - float32View[index + 11] = (vertexData[5] * resolution | 0) / resolution; - - // xy - float32View[index + 15] = (vertexData[6] * resolution | 0) / resolution; - float32View[index + 16] = (vertexData[7] * resolution | 0) / resolution; - } else { - // xy - float32View[index] = vertexData[0]; - float32View[index + 1] = vertexData[1]; - - // xy - float32View[index + 5] = vertexData[2]; - float32View[index + 6] = vertexData[3]; - - // xy - float32View[index + 10] = vertexData[4]; - float32View[index + 11] = vertexData[5]; - - // xy - float32View[index + 15] = vertexData[6]; - float32View[index + 16] = vertexData[7]; - } - - uint32View[index + 2] = uvs[0]; - uint32View[index + 7] = uvs[1]; - uint32View[index + 12] = uvs[2]; - uint32View[index + 17] = uvs[3]; - /* eslint-disable max-len */ - var alpha = Math.min(sprite.worldAlpha, 1.0); - // we dont call extra function if alpha is 1.0, that's faster - var argb = alpha < 1.0 && nextTexture.premultipliedAlpha ? (0, _utils.premultiplyTint)(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); - - uint32View[index + 3] = uint32View[index + 8] = uint32View[index + 13] = uint32View[index + 18] = argb; - float32View[index + 4] = float32View[index + 9] = float32View[index + 14] = float32View[index + 19] = nextTexture._virtalBoundId; - /* eslint-enable max-len */ - - index += 20; - } - - currentGroup.size = i - currentGroup.start; - - if (!_settings2.default.CAN_UPLOAD_SAME_BUFFER) { - // this is still needed for IOS performance.. - // it really does not like uploading to the same buffer in a single frame! - if (this.vaoMax <= this.vertexCount) { - this.vaoMax++; - - var attrs = this.shader.attributes; - - /* eslint-disable max-len */ - var vertexBuffer = this.vertexBuffers[this.vertexCount] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); - /* eslint-enable max-len */ - - // build the vao object that will render.. - var vao = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(vertexBuffer, attrs.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(vertexBuffer, attrs.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(vertexBuffer, attrs.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); - - if (attrs.aTextureId) { - vao.addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); - } - - this.vaos[this.vertexCount] = vao; - } - - this.renderer.bindVao(this.vaos[this.vertexCount]); - - this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, false); - - this.vertexCount++; - } else { - // lets use the faster option, always use buffer number 0 - this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, true); - } - - for (i = 0; i < MAX_TEXTURES; ++i) { - rendererBoundTextures[i]._virtalBoundId = -1; - } - - // render the groups.. - for (i = 0; i < groupCount; ++i) { - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var _j = 0; _j < groupTextureCount; _j++) { - currentTexture = group.textures[_j]; - - // reset virtual ids.. - // lets do a quick check.. - if (rendererBoundTextures[group.ids[_j]] !== currentTexture) { - this.renderer.bindTexture(currentTexture, group.ids[_j], true); - } - - // reset the virtualId.. - currentTexture._virtalBoundId = -1; - } - - // set the blend mode.. - this.renderer.state.setBlendMode(group.blend); - - gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); - } - - // reset elements for the next flush - this.currentIndex = 0; - }; - - /** - * Starts a new sprite batch. - */ - - - SpriteRenderer.prototype.start = function start() { - this.renderer.bindShader(this.shader); - - if (_settings2.default.CAN_UPLOAD_SAME_BUFFER) { - // bind buffer #0, we don't need others - this.renderer.bindVao(this.vaos[this.vertexCount]); - - this.vertexBuffers[this.vertexCount].bind(); - } - }; - - /** - * Stops and flushes the current batch. - * - */ - - - SpriteRenderer.prototype.stop = function stop() { - this.flush(); - }; - - /** - * Destroys the SpriteRenderer. - * - */ - - - SpriteRenderer.prototype.destroy = function destroy() { - for (var i = 0; i < this.vaoMax; i++) { - if (this.vertexBuffers[i]) { - this.vertexBuffers[i].destroy(); - } - if (this.vaos[i]) { - this.vaos[i].destroy(); - } - } - - if (this.indexBuffer) { - this.indexBuffer.destroy(); - } - - this.renderer.off('prerender', this.onPrerender, this); - - _ObjectRenderer.prototype.destroy.call(this); - - if (this.shader) { - this.shader.destroy(); - this.shader = null; - } - - this.vertexBuffers = null; - this.vaos = null; - this.indexBuffer = null; - this.indices = null; - - this.sprites = null; - - for (var _i = 0; _i < this.buffers.length; ++_i) { - this.buffers[_i].destroy(); - } - }; - - return SpriteRenderer; -}(_ObjectRenderer3.default); - -exports.default = SpriteRenderer; - - -_WebGLRenderer2.default.registerPlugin('sprite', SpriteRenderer); - -},{"../../renderers/webgl/WebGLRenderer":84,"../../renderers/webgl/utils/ObjectRenderer":94,"../../renderers/webgl/utils/checkMaxIfStatmentsInShader":97,"../../settings":101,"../../utils":124,"../../utils/createIndicesForQuads":122,"./BatchBuffer":105,"./generateMultiTextureShader":107,"bit-twiddle":1,"pixi-gl-core":12}],107:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.default = generateMultiTextureShader; - -var _Shader = require('../../Shader'); - -var _Shader2 = _interopRequireDefault(_Shader); - -var _path = require('path'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var fragTemplate = ['varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'varying float vTextureId;', 'uniform sampler2D uSamplers[%count%];', 'void main(void){', 'vec4 color;', 'float textureId = floor(vTextureId+0.5);', '%forloop%', 'gl_FragColor = color * vColor;', '}'].join('\n'); - -function generateMultiTextureShader(gl, maxTextures) { - var vertexSrc = 'precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor;\n}\n'; - var fragmentSrc = fragTemplate; - - fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); - fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - - var shader = new _Shader2.default(gl, vertexSrc, fragmentSrc); - - var sampleValues = []; - - for (var i = 0; i < maxTextures; i++) { - sampleValues[i] = i; - } - - shader.bind(); - shader.uniforms.uSamplers = sampleValues; - - return shader; -} - -function generateSampleSrc(maxTextures) { - var src = ''; - - src += '\n'; - src += '\n'; - - for (var i = 0; i < maxTextures; i++) { - if (i > 0) { - src += '\nelse '; - } - - if (i < maxTextures - 1) { - src += 'if(textureId == ' + i + '.0)'; - } - - src += '\n{'; - src += '\n\tcolor = texture2D(uSamplers[' + i + '], vTextureCoord);'; - src += '\n}'; - } - - src += '\n'; - src += '\n'; - - return src; -} - -},{"../../Shader":44,"path":23}],108:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _Sprite2 = require('../sprites/Sprite'); - -var _Sprite3 = _interopRequireDefault(_Sprite2); - -var _Texture = require('../textures/Texture'); - -var _Texture2 = _interopRequireDefault(_Texture); - -var _math = require('../math'); - -var _utils = require('../utils'); - -var _const = require('../const'); - -var _settings = require('../settings'); - -var _settings2 = _interopRequireDefault(_settings); - -var _TextStyle = require('./TextStyle'); - -var _TextStyle2 = _interopRequireDefault(_TextStyle); - -var _TextMetrics = require('./TextMetrics'); - -var _TextMetrics2 = _interopRequireDefault(_TextMetrics); - -var _trimCanvas = require('../utils/trimCanvas'); - -var _trimCanvas2 = _interopRequireDefault(_trimCanvas); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint max-depth: [2, 8] */ - - -var defaultDestroyOptions = { - texture: true, - children: false, - baseTexture: true -}; - -/** - * A Text Object will create a line or multiple lines of text. To split a line you can use '\n' in your text string, - * or add a wordWrap property set to true and and wordWrapWidth property with a value in the style object. - * - * A Text can be created directly from a string and a style object - * - * ```js - * let text = new PIXI.Text('This is a PixiJS text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); - * ``` - * - * @class - * @extends PIXI.Sprite - * @memberof PIXI - */ - -var Text = function (_Sprite) { - _inherits(Text, _Sprite); - - /** - * @param {string} text - The string that you would like the text to display - * @param {object|PIXI.TextStyle} [style] - The style parameters - * @param {HTMLCanvasElement} [canvas] - The canvas element for drawing text - */ - function Text(text, style, canvas) { - _classCallCheck(this, Text); - - canvas = canvas || document.createElement('canvas'); - - canvas.width = 3; - canvas.height = 3; - - var texture = _Texture2.default.fromCanvas(canvas, _settings2.default.SCALE_MODE, 'text'); - - texture.orig = new _math.Rectangle(); - texture.trim = new _math.Rectangle(); - - // base texture is already automatically added to the cache, now adding the actual texture - var _this = _possibleConstructorReturn(this, _Sprite.call(this, texture)); - - _Texture2.default.addToCache(_this._texture, _this._texture.baseTexture.textureCacheIds[0]); - - /** - * The canvas element that everything is drawn to - * - * @member {HTMLCanvasElement} - */ - _this.canvas = canvas; - - /** - * The canvas 2d context that everything is drawn with - * @member {CanvasRenderingContext2D} - */ - _this.context = _this.canvas.getContext('2d'); - - /** - * The resolution / device pixel ratio of the canvas. This is set automatically by the renderer. - * @member {number} - * @default 1 - */ - _this.resolution = _settings2.default.RESOLUTION; - - /** - * Private tracker for the current text. - * - * @member {string} - * @private - */ - _this._text = null; - - /** - * Private tracker for the current style. - * - * @member {object} - * @private - */ - _this._style = null; - /** - * Private listener to track style changes. - * - * @member {Function} - * @private - */ - _this._styleListener = null; - - /** - * Private tracker for the current font. - * - * @member {string} - * @private - */ - _this._font = ''; - - _this.text = text; - _this.style = style; - - _this.localStyleID = -1; - return _this; - } - - /** - * Renders text and updates it when needed. - * - * @private - * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. - */ - - - Text.prototype.updateText = function updateText(respectDirty) { - var style = this._style; - - // check if style has changed.. - if (this.localStyleID !== style.styleID) { - this.dirty = true; - this.localStyleID = style.styleID; - } - - if (!this.dirty && respectDirty) { - return; - } - - this._font = this._style.toFontString(); - - var context = this.context; - var measured = _TextMetrics2.default.measureText(this._text, this._style, this._style.wordWrap, this.canvas); - var width = measured.width; - var height = measured.height; - var lines = measured.lines; - var lineHeight = measured.lineHeight; - var lineWidths = measured.lineWidths; - var maxLineWidth = measured.maxLineWidth; - var fontProperties = measured.fontProperties; - - this.canvas.width = Math.ceil((width + style.padding * 2) * this.resolution); - this.canvas.height = Math.ceil((height + style.padding * 2) * this.resolution); - - context.scale(this.resolution, this.resolution); - - context.clearRect(0, 0, this.canvas.width, this.canvas.height); - - context.font = this._font; - context.strokeStyle = style.stroke; - context.lineWidth = style.strokeThickness; - context.textBaseline = style.textBaseline; - context.lineJoin = style.lineJoin; - context.miterLimit = style.miterLimit; - - var linePositionX = void 0; - var linePositionY = void 0; - - if (style.dropShadow) { - context.fillStyle = style.dropShadowColor; - context.globalAlpha = style.dropShadowAlpha; - context.shadowBlur = style.dropShadowBlur; - - if (style.dropShadowBlur > 0) { - context.shadowColor = style.dropShadowColor; - } - - var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; - var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance; - - for (var i = 0; i < lines.length; i++) { - linePositionX = style.strokeThickness / 2; - linePositionY = style.strokeThickness / 2 + i * lineHeight + fontProperties.ascent; - - if (style.align === 'right') { - linePositionX += maxLineWidth - lineWidths[i]; - } else if (style.align === 'center') { - linePositionX += (maxLineWidth - lineWidths[i]) / 2; - } - - if (style.fill) { - this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding); - - if (style.stroke && style.strokeThickness) { - context.strokeStyle = style.dropShadowColor; - this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding, true); - context.strokeStyle = style.stroke; - } - } - } - } - - // reset the shadow blur and alpha that was set by the drop shadow, for the regular text - context.shadowBlur = 0; - context.globalAlpha = 1; - - // set canvas text styles - context.fillStyle = this._generateFillStyle(style, lines); - - // draw lines line by line - for (var _i = 0; _i < lines.length; _i++) { - linePositionX = style.strokeThickness / 2; - linePositionY = style.strokeThickness / 2 + _i * lineHeight + fontProperties.ascent; - - if (style.align === 'right') { - linePositionX += maxLineWidth - lineWidths[_i]; - } else if (style.align === 'center') { - linePositionX += (maxLineWidth - lineWidths[_i]) / 2; - } - - if (style.stroke && style.strokeThickness) { - this.drawLetterSpacing(lines[_i], linePositionX + style.padding, linePositionY + style.padding, true); - } - - if (style.fill) { - this.drawLetterSpacing(lines[_i], linePositionX + style.padding, linePositionY + style.padding); - } - } - - this.updateTexture(); - }; - - /** - * Render the text with letter-spacing. - * @param {string} text - The text to draw - * @param {number} x - Horizontal position to draw the text - * @param {number} y - Vertical position to draw the text - * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the - * text? If not, it's for the inside fill - * @private - */ - - - Text.prototype.drawLetterSpacing = function drawLetterSpacing(text, x, y) { - var isStroke = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - - var style = this._style; - - // letterSpacing of 0 means normal - var letterSpacing = style.letterSpacing; - - if (letterSpacing === 0) { - if (isStroke) { - this.context.strokeText(text, x, y); - } else { - this.context.fillText(text, x, y); - } - - return; - } - - var characters = String.prototype.split.call(text, ''); - var currentPosition = x; - var index = 0; - var current = ''; - - while (index < text.length) { - current = characters[index++]; - if (isStroke) { - this.context.strokeText(current, currentPosition, y); - } else { - this.context.fillText(current, currentPosition, y); - } - currentPosition += this.context.measureText(current).width + letterSpacing; - } - }; - - /** - * Updates texture size based on canvas size - * - * @private - */ - - - Text.prototype.updateTexture = function updateTexture() { - var canvas = this.canvas; - - if (this._style.trim) { - var trimmed = (0, _trimCanvas2.default)(canvas); - - canvas.width = trimmed.width; - canvas.height = trimmed.height; - this.context.putImageData(trimmed.data, 0, 0); - } - - var texture = this._texture; - var style = this._style; - var padding = style.trim ? 0 : style.padding; - var baseTexture = texture.baseTexture; - - baseTexture.hasLoaded = true; - baseTexture.resolution = this.resolution; - - baseTexture.realWidth = canvas.width; - baseTexture.realHeight = canvas.height; - baseTexture.width = canvas.width / this.resolution; - baseTexture.height = canvas.height / this.resolution; - - texture.trim.width = texture._frame.width = canvas.width / this.resolution; - texture.trim.height = texture._frame.height = canvas.height / this.resolution; - texture.trim.x = -padding; - texture.trim.y = -padding; - - texture.orig.width = texture._frame.width - padding * 2; - texture.orig.height = texture._frame.height - padding * 2; - - // call sprite onTextureUpdate to update scale if _width or _height were set - this._onTextureUpdate(); - - baseTexture.emit('update', baseTexture); - - this.dirty = false; - }; - - /** - * Renders the object using the WebGL renderer - * - * @param {PIXI.WebGLRenderer} renderer - The renderer - */ - - - Text.prototype.renderWebGL = function renderWebGL(renderer) { - if (this.resolution !== renderer.resolution) { - this.resolution = renderer.resolution; - this.dirty = true; - } - - this.updateText(true); - - _Sprite.prototype.renderWebGL.call(this, renderer); - }; - - /** - * Renders the object using the Canvas renderer - * - * @private - * @param {PIXI.CanvasRenderer} renderer - The renderer - */ - - - Text.prototype._renderCanvas = function _renderCanvas(renderer) { - if (this.resolution !== renderer.resolution) { - this.resolution = renderer.resolution; - this.dirty = true; - } - - this.updateText(true); - - _Sprite.prototype._renderCanvas.call(this, renderer); - }; - - /** - * Gets the local bounds of the text object. - * - * @param {Rectangle} rect - The output rectangle. - * @return {Rectangle} The bounds. - */ - - - Text.prototype.getLocalBounds = function getLocalBounds(rect) { - this.updateText(true); - - return _Sprite.prototype.getLocalBounds.call(this, rect); - }; - - /** - * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. - */ - - - Text.prototype._calculateBounds = function _calculateBounds() { - this.updateText(true); - this.calculateVertices(); - // if we have already done this on THIS frame. - this._bounds.addQuad(this.vertexData); - }; - - /** - * Method to be called upon a TextStyle change. - * @private - */ - - - Text.prototype._onStyleChange = function _onStyleChange() { - this.dirty = true; - }; - - /** - * Generates the fill style. Can automatically generate a gradient based on the fill style being an array - * - * @private - * @param {object} style - The style. - * @param {string[]} lines - The lines of text. - * @return {string|number|CanvasGradient} The fill style - */ - - - Text.prototype._generateFillStyle = function _generateFillStyle(style, lines) { - if (!Array.isArray(style.fill)) { - return style.fill; - } - - // cocoon on canvas+ cannot generate textures, so use the first colour instead - if (navigator.isCocoonJS) { - return style.fill[0]; - } - - // the gradient will be evenly spaced out according to how large the array is. - // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 - var gradient = void 0; - var totalIterations = void 0; - var currentIteration = void 0; - var stop = void 0; - - var width = this.canvas.width / this.resolution; - var height = this.canvas.height / this.resolution; - - // make a copy of the style settings, so we can manipulate them later - var fill = style.fill.slice(); - var fillGradientStops = style.fillGradientStops.slice(); - - // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 - if (!fillGradientStops.length) { - var lengthPlus1 = fill.length + 1; - - for (var i = 1; i < lengthPlus1; ++i) { - fillGradientStops.push(i / lengthPlus1); - } - } - - // stop the bleeding of the last gradient on the line above to the top gradient of the this line - // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 - fill.unshift(style.fill[0]); - fillGradientStops.unshift(0); - - fill.push(style.fill[style.fill.length - 1]); - fillGradientStops.push(1); - - if (style.fillGradientType === _const.TEXT_GRADIENT.LINEAR_VERTICAL) { - // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas - gradient = this.context.createLinearGradient(width / 2, 0, width / 2, height); - - // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect - // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 - totalIterations = (fill.length + 1) * lines.length; - currentIteration = 0; - for (var _i2 = 0; _i2 < lines.length; _i2++) { - currentIteration += 1; - for (var j = 0; j < fill.length; j++) { - if (typeof fillGradientStops[j] === 'number') { - stop = fillGradientStops[j] / lines.length + _i2 / lines.length; - } else { - stop = currentIteration / totalIterations; - } - gradient.addColorStop(stop, fill[j]); - currentIteration++; - } - } - } else { - // start the gradient at the center left of the canvas, and end at the center right of the canvas - gradient = this.context.createLinearGradient(0, height / 2, width, height / 2); - - // can just evenly space out the gradients in this case, as multiple lines makes no difference - // to an even left to right gradient - totalIterations = fill.length + 1; - currentIteration = 1; - - for (var _i3 = 0; _i3 < fill.length; _i3++) { - if (typeof fillGradientStops[_i3] === 'number') { - stop = fillGradientStops[_i3]; - } else { - stop = currentIteration / totalIterations; - } - gradient.addColorStop(stop, fill[_i3]); - currentIteration++; - } - } - - return gradient; - }; - - /** - * Destroys this text object. - * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as - * the majority of the time the texture will not be shared with any other Sprites. - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their - * destroy method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well - * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well - */ - - - Text.prototype.destroy = function destroy(options) { - if (typeof options === 'boolean') { - options = { children: options }; - } - - options = Object.assign({}, defaultDestroyOptions, options); - - _Sprite.prototype.destroy.call(this, options); - - // make sure to reset the the context and canvas.. dont want this hanging around in memory! - this.context = null; - this.canvas = null; - - this._style = null; - }; - - /** - * The width of the Text, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - - - _createClass(Text, [{ - key: 'width', - get: function get() { - this.updateText(true); - - return Math.abs(this.scale.x) * this._texture.orig.width; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.updateText(true); - - var s = (0, _utils.sign)(this.scale.x) || 1; - - this.scale.x = s * value / this._texture.orig.width; - this._width = value; - } - - /** - * The height of the Text, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - - }, { - key: 'height', - get: function get() { - this.updateText(true); - - return Math.abs(this.scale.y) * this._texture.orig.height; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.updateText(true); - - var s = (0, _utils.sign)(this.scale.y) || 1; - - this.scale.y = s * value / this._texture.orig.height; - this._height = value; - } - - /** - * Set the style of the text. Set up an event listener to listen for changes on the style - * object and mark the text as dirty. - * - * @member {object|PIXI.TextStyle} - */ - - }, { - key: 'style', - get: function get() { - return this._style; - }, - set: function set(style) // eslint-disable-line require-jsdoc - { - style = style || {}; - - if (style instanceof _TextStyle2.default) { - this._style = style; - } else { - this._style = new _TextStyle2.default(style); - } - - this.localStyleID = -1; - this.dirty = true; - } - - /** - * Set the copy for the text object. To split a line you can use '\n'. - * - * @member {string} - */ - - }, { - key: 'text', - get: function get() { - return this._text; - }, - set: function set(text) // eslint-disable-line require-jsdoc - { - text = String(text === '' || text === null || text === undefined ? ' ' : text); - - if (this._text === text) { - return; - } - this._text = text; - this.dirty = true; - } - }]); - - return Text; -}(_Sprite3.default); - -exports.default = Text; - -},{"../const":46,"../math":70,"../settings":101,"../sprites/Sprite":102,"../textures/Texture":115,"../utils":124,"../utils/trimCanvas":129,"./TextMetrics":109,"./TextStyle":110}],109:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * The TextMetrics object represents the measurement of a block of text with a specified style. - * - * @class - * @memberOf PIXI - */ -var TextMetrics = function () { - /** - * @param {string} text - the text that was measured - * @param {PIXI.TextStyle} style - the style that was measured - * @param {number} width - the measured width of the text - * @param {number} height - the measured height of the text - * @param {array} lines - an array of the lines of text broken by new lines and wrapping if specified in style - * @param {array} lineWidths - an array of the line widths for each line matched to `lines` - * @param {number} lineHeight - the measured line height for this style - * @param {number} maxLineWidth - the maximum line width for all measured lines - * @param {Object} fontProperties - the font properties object from TextMetrics.measureFont - */ - function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) { - _classCallCheck(this, TextMetrics); - - this.text = text; - this.style = style; - this.width = width; - this.height = height; - this.lines = lines; - this.lineWidths = lineWidths; - this.lineHeight = lineHeight; - this.maxLineWidth = maxLineWidth; - this.fontProperties = fontProperties; - } - - /** - * Measures the supplied string of text and returns a Rectangle. - * - * @param {string} text - the text to measure. - * @param {PIXI.TextStyle} style - the text style to use for measuring - * @param {boolean} [wordWrap] - optional override for if word-wrap should be applied to the text. - * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. - * @return {PIXI.TextMetrics} measured width and height of the text. - */ - - - TextMetrics.measureText = function measureText(text, style, wordWrap) { - var canvas = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : TextMetrics._canvas; - - wordWrap = wordWrap || style.wordWrap; - var font = style.toFontString(); - var fontProperties = TextMetrics.measureFont(font); - var context = canvas.getContext('2d'); - - context.font = font; - - var outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text; - var lines = outputText.split(/(?:\r\n|\r|\n)/); - var lineWidths = new Array(lines.length); - var maxLineWidth = 0; - - for (var i = 0; i < lines.length; i++) { - var lineWidth = context.measureText(lines[i]).width + (lines[i].length - 1) * style.letterSpacing; - - lineWidths[i] = lineWidth; - maxLineWidth = Math.max(maxLineWidth, lineWidth); - } - var width = maxLineWidth + style.strokeThickness; - - if (style.dropShadow) { - width += style.dropShadowDistance; - } - - var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; - var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + (lines.length - 1) * lineHeight; - - if (style.dropShadow) { - height += style.dropShadowDistance; - } - - return new TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties); - }; - - /** - * Applies newlines to a string to have it optimally fit into the horizontal - * bounds set by the Text object's wordWrapWidth property. - * - * @private - * @param {string} text - String to apply word wrapping to - * @param {PIXI.TextStyle} style - the style to use when wrapping - * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. - * @return {string} New string with new lines applied where required - */ - - - TextMetrics.wordWrap = function wordWrap(text, style) { - var canvas = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : TextMetrics._canvas; - - var context = canvas.getContext('2d'); - - // Greedy wrapping algorithm that will wrap words as the line grows longer - // than its horizontal bounds. - var result = ''; - var lines = text.split('\n'); - var wordWrapWidth = style.wordWrapWidth; - var characterCache = {}; - - for (var i = 0; i < lines.length; i++) { - var spaceLeft = wordWrapWidth; - var words = lines[i].split(' '); - - for (var j = 0; j < words.length; j++) { - var wordWidth = context.measureText(words[j]).width; - - if (style.breakWords && wordWidth > wordWrapWidth) { - // Word should be split in the middle - var characters = words[j].split(''); - - for (var c = 0; c < characters.length; c++) { - var character = characters[c]; - var characterWidth = characterCache[character]; - - if (characterWidth === undefined) { - characterWidth = context.measureText(character).width; - characterCache[character] = characterWidth; - } - - if (characterWidth > spaceLeft) { - result += '\n' + character; - spaceLeft = wordWrapWidth - characterWidth; - } else { - if (c === 0) { - result += ' '; - } - - result += character; - spaceLeft -= characterWidth; - } - } - } else { - var wordWidthWithSpace = wordWidth + context.measureText(' ').width; - - if (j === 0 || wordWidthWithSpace > spaceLeft) { - // Skip printing the newline if it's the first word of the line that is - // greater than the word wrap width. - if (j > 0) { - result += '\n'; - } - result += words[j]; - spaceLeft = wordWrapWidth - wordWidth; - } else { - spaceLeft -= wordWidthWithSpace; - result += ' ' + words[j]; - } - } - } - - if (i < lines.length - 1) { - result += '\n'; - } - } - - return result; - }; - - /** - * Calculates the ascent, descent and fontSize of a given font-style - * - * @static - * @param {string} font - String representing the style of the font - * @return {PIXI.TextMetrics~FontMetrics} Font properties object - */ - - - TextMetrics.measureFont = function measureFont(font) { - // as this method is used for preparing assets, don't recalculate things if we don't need to - if (TextMetrics._fonts[font]) { - return TextMetrics._fonts[font]; - } - - var properties = {}; - - var canvas = TextMetrics._canvas; - var context = TextMetrics._context; - - context.font = font; - - var width = Math.ceil(context.measureText('|MÉq').width); - var baseline = Math.ceil(context.measureText('M').width); - var height = 2 * baseline; - - baseline = baseline * 1.4 | 0; - - canvas.width = width; - canvas.height = height; - - context.fillStyle = '#f00'; - context.fillRect(0, 0, width, height); - - context.font = font; - - context.textBaseline = 'alphabetic'; - context.fillStyle = '#000'; - context.fillText('|MÉq', 0, baseline); - - var imagedata = context.getImageData(0, 0, width, height).data; - var pixels = imagedata.length; - var line = width * 4; - - var i = 0; - var idx = 0; - var stop = false; - - // ascent. scan from top to bottom until we find a non red pixel - for (i = 0; i < baseline; ++i) { - for (var j = 0; j < line; j += 4) { - if (imagedata[idx + j] !== 255) { - stop = true; - break; - } - } - if (!stop) { - idx += line; - } else { - break; - } - } - - properties.ascent = baseline - i; - - idx = pixels - line; - stop = false; - - // descent. scan from bottom to top until we find a non red pixel - for (i = height; i > baseline; --i) { - for (var _j = 0; _j < line; _j += 4) { - if (imagedata[idx + _j] !== 255) { - stop = true; - break; - } - } - - if (!stop) { - idx -= line; - } else { - break; - } - } - - properties.descent = i - baseline; - properties.fontSize = properties.ascent + properties.descent; - - TextMetrics._fonts[font] = properties; - - return properties; - }; - - return TextMetrics; -}(); - -/** - * Internal return object for {@link PIXI.TextMetrics.measureFont `TextMetrics.measureFont`}. - * @class FontMetrics - * @memberof PIXI.TextMetrics~ - * @property {number} ascent - The ascent distance - * @property {number} descent - The descent distance - * @property {number} fontSize - Font size from ascent to descent - */ - -exports.default = TextMetrics; -var canvas = document.createElement('canvas'); - -canvas.width = canvas.height = 10; - -/** - * Cached canvas element for measuring text - * @memberof PIXI.TextMetrics - * @type {HTMLCanvasElement} - * @private - */ -TextMetrics._canvas = canvas; - -/** - * Cache for context to use. - * @memberof PIXI.TextMetrics - * @type {CanvasRenderingContext2D} - * @private - */ -TextMetrics._context = canvas.getContext('2d'); - -/** - * Cache of PIXI.TextMetrics~FontMetrics objects. - * @memberof PIXI.TextMetrics - * @type {Object} - * @private - */ -TextMetrics._fonts = {}; - -},{}],110:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // disabling eslint for now, going to rewrite this in v5 -/* eslint-disable */ - -var _const = require('../const'); - -var _utils = require('../utils'); - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var defaultStyle = { - align: 'left', - breakWords: false, - dropShadow: false, - dropShadowAlpha: 1, - dropShadowAngle: Math.PI / 6, - dropShadowBlur: 0, - dropShadowColor: 'black', - dropShadowDistance: 5, - fill: 'black', - fillGradientType: _const.TEXT_GRADIENT.LINEAR_VERTICAL, - fillGradientStops: [], - fontFamily: 'Arial', - fontSize: 26, - fontStyle: 'normal', - fontVariant: 'normal', - fontWeight: 'normal', - letterSpacing: 0, - lineHeight: 0, - lineJoin: 'miter', - miterLimit: 10, - padding: 0, - stroke: 'black', - strokeThickness: 0, - textBaseline: 'alphabetic', - trim: false, - wordWrap: false, - wordWrapWidth: 100 -}; - -/** - * A TextStyle Object decorates a Text Object. It can be shared between - * multiple Text objects. Changing the style will update all text objects using it. - * - * @class - * @memberof PIXI - */ - -var TextStyle = function () { - /** - * @param {object} [style] - The style parameters - * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), - * does not affect single line text - * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it - * needs wordWrap to be set to true - * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text - * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow - * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow - * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius - * @param {string} [style.dropShadowColor='black'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' - * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow - * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas - * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient - * eg ['#000000','#FFFFFF'] - * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} - * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours - * to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} - * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set - * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. - * @param {string|string[]} [style.fontFamily='Arial'] - The font family - * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, - * equivalents are '26px','20pt','160%' or '1.6em') - * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') - * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') - * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', - * '200', '300', '400', '500', '600', '700', 800' or '900') - * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 - * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses - * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve - * spiked text issues. Default is 'miter' (creates a sharp corner). - * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce - * or increase the spikiness of rendered text. - * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from - * happening by adding padding to all sides of the text. - * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke - * e.g 'blue', '#FCFF00' - * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. - * Default is 0 (no stroke) - * @param {boolean} [style.trim=false] - Trim transparent borders - * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. - * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used - * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true - */ - function TextStyle(style) { - _classCallCheck(this, TextStyle); - - this.styleID = 0; - - Object.assign(this, defaultStyle, style); - } - - /** - * Creates a new TextStyle object with the same values as this one. - * Note that the only the properties of the object are cloned. - * - * @return {PIXI.TextStyle} New cloned TextStyle object - */ - - - TextStyle.prototype.clone = function clone() { - var clonedProperties = {}; - - for (var key in defaultStyle) { - clonedProperties[key] = this[key]; - } - - return new TextStyle(clonedProperties); - }; - - /** - * Resets all properties to the defaults specified in TextStyle.prototype._default - */ - - - TextStyle.prototype.reset = function reset() { - Object.assign(this, defaultStyle); - }; - - /** - * Generates a font style string to use for `TextMetrics.measureFont()`. - * - * @return {string} Font style string, for passing to `TextMetrics.measureFont()` - */ - TextStyle.prototype.toFontString = function toFontString() { - // build canvas api font setting from individual components. Convert a numeric this.fontSize to px - var fontSizeString = typeof this.fontSize === 'number' ? this.fontSize + 'px' : this.fontSize; - - // Clean-up fontFamily property by quoting each font name - // this will support font names with spaces - var fontFamilies = this.fontFamily; - - if (!Array.isArray(this.fontFamily)) { - fontFamilies = this.fontFamily.split(','); - } - - for (var i = fontFamilies.length - 1; i >= 0; i--) { - // Trim any extra white-space - var fontFamily = fontFamilies[i].trim(); - - // Check if font already contains strings - if (!/([\"\'])[^\'\"]+\1/.test(fontFamily)) { - fontFamily = '"' + fontFamily + '"'; - } - fontFamilies[i] = fontFamily; - } - - return this.fontStyle + ' ' + this.fontVariant + ' ' + this.fontWeight + ' ' + fontSizeString + ' ' + fontFamilies.join(','); - }; - - _createClass(TextStyle, [{ - key: 'align', - get: function get() { - return this._align; - }, - set: function set(align) { - if (this._align !== align) { - this._align = align; - this.styleID++; - } - } - }, { - key: 'breakWords', - get: function get() { - return this._breakWords; - }, - set: function set(breakWords) { - if (this._breakWords !== breakWords) { - this._breakWords = breakWords; - this.styleID++; - } - } - }, { - key: 'dropShadow', - get: function get() { - return this._dropShadow; - }, - set: function set(dropShadow) { - if (this._dropShadow !== dropShadow) { - this._dropShadow = dropShadow; - this.styleID++; - } - } - }, { - key: 'dropShadowAlpha', - get: function get() { - return this._dropShadowAlpha; - }, - set: function set(dropShadowAlpha) { - if (this._dropShadowAlpha !== dropShadowAlpha) { - this._dropShadowAlpha = dropShadowAlpha; - this.styleID++; - } - } - }, { - key: 'dropShadowAngle', - get: function get() { - return this._dropShadowAngle; - }, - set: function set(dropShadowAngle) { - if (this._dropShadowAngle !== dropShadowAngle) { - this._dropShadowAngle = dropShadowAngle; - this.styleID++; - } - } - }, { - key: 'dropShadowBlur', - get: function get() { - return this._dropShadowBlur; - }, - set: function set(dropShadowBlur) { - if (this._dropShadowBlur !== dropShadowBlur) { - this._dropShadowBlur = dropShadowBlur; - this.styleID++; - } - } - }, { - key: 'dropShadowColor', - get: function get() { - return this._dropShadowColor; - }, - set: function set(dropShadowColor) { - var outputColor = getColor(dropShadowColor); - if (this._dropShadowColor !== outputColor) { - this._dropShadowColor = outputColor; - this.styleID++; - } - } - }, { - key: 'dropShadowDistance', - get: function get() { - return this._dropShadowDistance; - }, - set: function set(dropShadowDistance) { - if (this._dropShadowDistance !== dropShadowDistance) { - this._dropShadowDistance = dropShadowDistance; - this.styleID++; - } - } - }, { - key: 'fill', - get: function get() { - return this._fill; - }, - set: function set(fill) { - var outputColor = getColor(fill); - if (this._fill !== outputColor) { - this._fill = outputColor; - this.styleID++; - } - } - }, { - key: 'fillGradientType', - get: function get() { - return this._fillGradientType; - }, - set: function set(fillGradientType) { - if (this._fillGradientType !== fillGradientType) { - this._fillGradientType = fillGradientType; - this.styleID++; - } - } - }, { - key: 'fillGradientStops', - get: function get() { - return this._fillGradientStops; - }, - set: function set(fillGradientStops) { - if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) { - this._fillGradientStops = fillGradientStops; - this.styleID++; - } - } - }, { - key: 'fontFamily', - get: function get() { - return this._fontFamily; - }, - set: function set(fontFamily) { - if (this.fontFamily !== fontFamily) { - this._fontFamily = fontFamily; - this.styleID++; - } - } - }, { - key: 'fontSize', - get: function get() { - return this._fontSize; - }, - set: function set(fontSize) { - if (this._fontSize !== fontSize) { - this._fontSize = fontSize; - this.styleID++; - } - } - }, { - key: 'fontStyle', - get: function get() { - return this._fontStyle; - }, - set: function set(fontStyle) { - if (this._fontStyle !== fontStyle) { - this._fontStyle = fontStyle; - this.styleID++; - } - } - }, { - key: 'fontVariant', - get: function get() { - return this._fontVariant; - }, - set: function set(fontVariant) { - if (this._fontVariant !== fontVariant) { - this._fontVariant = fontVariant; - this.styleID++; - } - } - }, { - key: 'fontWeight', - get: function get() { - return this._fontWeight; - }, - set: function set(fontWeight) { - if (this._fontWeight !== fontWeight) { - this._fontWeight = fontWeight; - this.styleID++; - } - } - }, { - key: 'letterSpacing', - get: function get() { - return this._letterSpacing; - }, - set: function set(letterSpacing) { - if (this._letterSpacing !== letterSpacing) { - this._letterSpacing = letterSpacing; - this.styleID++; - } - } - }, { - key: 'lineHeight', - get: function get() { - return this._lineHeight; - }, - set: function set(lineHeight) { - if (this._lineHeight !== lineHeight) { - this._lineHeight = lineHeight; - this.styleID++; - } - } - }, { - key: 'lineJoin', - get: function get() { - return this._lineJoin; - }, - set: function set(lineJoin) { - if (this._lineJoin !== lineJoin) { - this._lineJoin = lineJoin; - this.styleID++; - } - } - }, { - key: 'miterLimit', - get: function get() { - return this._miterLimit; - }, - set: function set(miterLimit) { - if (this._miterLimit !== miterLimit) { - this._miterLimit = miterLimit; - this.styleID++; - } - } - }, { - key: 'padding', - get: function get() { - return this._padding; - }, - set: function set(padding) { - if (this._padding !== padding) { - this._padding = padding; - this.styleID++; - } - } - }, { - key: 'stroke', - get: function get() { - return this._stroke; - }, - set: function set(stroke) { - var outputColor = getColor(stroke); - if (this._stroke !== outputColor) { - this._stroke = outputColor; - this.styleID++; - } - } - }, { - key: 'strokeThickness', - get: function get() { - return this._strokeThickness; - }, - set: function set(strokeThickness) { - if (this._strokeThickness !== strokeThickness) { - this._strokeThickness = strokeThickness; - this.styleID++; - } - } - }, { - key: 'textBaseline', - get: function get() { - return this._textBaseline; - }, - set: function set(textBaseline) { - if (this._textBaseline !== textBaseline) { - this._textBaseline = textBaseline; - this.styleID++; - } - } - }, { - key: 'trim', - get: function get() { - return this._trim; - }, - set: function set(trim) { - if (this._trim !== trim) { - this._trim = trim; - this.styleID++; - } - } - }, { - key: 'wordWrap', - get: function get() { - return this._wordWrap; - }, - set: function set(wordWrap) { - if (this._wordWrap !== wordWrap) { - this._wordWrap = wordWrap; - this.styleID++; - } - } - }, { - key: 'wordWrapWidth', - get: function get() { - return this._wordWrapWidth; - }, - set: function set(wordWrapWidth) { - if (this._wordWrapWidth !== wordWrapWidth) { - this._wordWrapWidth = wordWrapWidth; - this.styleID++; - } - } - }]); - - return TextStyle; -}(); - -/** - * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. - * - * @param {number|number[]} color - * @return {string} The color as a string. - */ - - -exports.default = TextStyle; -function getSingleColor(color) { - if (typeof color === 'number') { - return (0, _utils.hex2string)(color); - } else if (typeof color === 'string') { - if (color.indexOf('0x') === 0) { - color = color.replace('0x', '#'); - } - } - - return color; -} - -/** - * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. - * This version can also convert array of colors - * - * @param {number|number[]} color - * @return {string} The color as a string. - */ -function getColor(color) { - if (!Array.isArray(color)) { - return getSingleColor(color); - } else { - for (var i = 0; i < color.length; ++i) { - color[i] = getSingleColor(color[i]); - } - - return color; - } -} - -/** - * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. - * This version can also convert array of colors - * - * @param {Array} array1 First array to compare - * @param {Array} array2 Second array to compare - * @return {boolean} Do the arrays contain the same values in the same order - */ -function areArraysEqual(array1, array2) { - if (!Array.isArray(array1) || !Array.isArray(array2)) { - return false; - } - - if (array1.length !== array2.length) { - return false; - } - - for (var i = 0; i < array1.length; ++i) { - if (array1[i] !== array2[i]) { - return false; - } - } - - return true; -} - -},{"../const":46,"../utils":124}],111:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _BaseTexture2 = require('./BaseTexture'); - -var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); - -var _settings = require('../settings'); - -var _settings2 = _interopRequireDefault(_settings); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * A BaseRenderTexture is a special texture that allows any PixiJS display object to be rendered to it. - * - * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded - * otherwise black rectangles will be drawn instead. - * - * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position - * and rotation of the given Display Objects is ignored. For example: - * - * ```js - * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); - * let baseRenderTexture = new PIXI.BaseRenderTexture(renderer, 800, 600); - * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); - * - * sprite.position.x = 800/2; - * sprite.position.y = 600/2; - * sprite.anchor.x = 0.5; - * sprite.anchor.y = 0.5; - * - * baseRenderTexture.render(sprite); - * ``` - * - * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 - * you can clear the transform - * - * ```js - * - * sprite.setTransform() - * - * let baseRenderTexture = new PIXI.BaseRenderTexture(100, 100); - * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); - * - * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture - * ``` - * - * @class - * @extends PIXI.BaseTexture - * @memberof PIXI - */ -var BaseRenderTexture = function (_BaseTexture) { - _inherits(BaseRenderTexture, _BaseTexture); - - /** - * @param {number} [width=100] - The width of the base render texture - * @param {number} [height=100] - The height of the base render texture - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated - */ - function BaseRenderTexture() { - var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100; - var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; - var scaleMode = arguments[2]; - var resolution = arguments[3]; - - _classCallCheck(this, BaseRenderTexture); - - var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, null, scaleMode)); - - _this.resolution = resolution || _settings2.default.RESOLUTION; - - _this.width = width; - _this.height = height; - - _this.realWidth = _this.width * _this.resolution; - _this.realHeight = _this.height * _this.resolution; - - _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; - _this.hasLoaded = true; - - /** - * A map of renderer IDs to webgl renderTargets - * - * @private - * @member {object} - */ - _this._glRenderTargets = {}; - - /** - * A reference to the canvas render target (we only need one as this can be shared across renderers) - * - * @private - * @member {object} - */ - _this._canvasRenderTarget = null; - - /** - * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. - * - * @member {boolean} - */ - _this.valid = false; - return _this; - } - - /** - * Resizes the BaseRenderTexture. - * - * @param {number} width - The width to resize to. - * @param {number} height - The height to resize to. - */ - - - BaseRenderTexture.prototype.resize = function resize(width, height) { - if (width === this.width && height === this.height) { - return; - } - - this.valid = width > 0 && height > 0; - - this.width = width; - this.height = height; - - this.realWidth = this.width * this.resolution; - this.realHeight = this.height * this.resolution; - - if (!this.valid) { - return; - } - - this.emit('update', this); - }; - - /** - * Destroys this texture - * - */ - - - BaseRenderTexture.prototype.destroy = function destroy() { - _BaseTexture.prototype.destroy.call(this, true); - this.renderer = null; - }; - - return BaseRenderTexture; -}(_BaseTexture3.default); - -exports.default = BaseRenderTexture; - -},{"../settings":101,"./BaseTexture":112}],112:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _utils = require('../utils'); - -var _settings = require('../settings'); - -var _settings2 = _interopRequireDefault(_settings); - -var _eventemitter = require('eventemitter3'); - -var _eventemitter2 = _interopRequireDefault(_eventemitter); - -var _determineCrossOrigin = require('../utils/determineCrossOrigin'); - -var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); - -var _bitTwiddle = require('bit-twiddle'); - -var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * A texture stores the information that represents an image. All textures have a base texture. - * - * @class - * @extends EventEmitter - * @memberof PIXI - */ -var BaseTexture = function (_EventEmitter) { - _inherits(BaseTexture, _EventEmitter); - - /** - * @param {HTMLImageElement|HTMLCanvasElement} [source] - the source object of the texture. - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture - */ - function BaseTexture(source, scaleMode, resolution) { - _classCallCheck(this, BaseTexture); - - var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); - - _this.uid = (0, _utils.uid)(); - - _this.touched = 0; - - /** - * The resolution / device pixel ratio of the texture - * - * @member {number} - * @default 1 - */ - _this.resolution = resolution || _settings2.default.RESOLUTION; - - /** - * The width of the base texture set when the image has loaded - * - * @readonly - * @member {number} - */ - _this.width = 100; - - /** - * The height of the base texture set when the image has loaded - * - * @readonly - * @member {number} - */ - _this.height = 100; - - // TODO docs - // used to store the actual dimensions of the source - /** - * Used to store the actual width of the source of this texture - * - * @readonly - * @member {number} - */ - _this.realWidth = 100; - /** - * Used to store the actual height of the source of this texture - * - * @readonly - * @member {number} - */ - _this.realHeight = 100; - - /** - * The scale mode to apply when scaling this texture - * - * @member {number} - * @default PIXI.settings.SCALE_MODE - * @see PIXI.SCALE_MODES - */ - _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; - - /** - * Set to true once the base texture has successfully loaded. - * - * This is never true if the underlying source fails to load or has no texture data. - * - * @readonly - * @member {boolean} - */ - _this.hasLoaded = false; - - /** - * Set to true if the source is currently loading. - * - * If an Image source is loading the 'loaded' or 'error' event will be - * dispatched when the operation ends. An underyling source that is - * immediately-available bypasses loading entirely. - * - * @readonly - * @member {boolean} - */ - _this.isLoading = false; - - /** - * The image source that is used to create the texture. - * - * TODO: Make this a setter that calls loadSource(); - * - * @readonly - * @member {HTMLImageElement|HTMLCanvasElement} - */ - _this.source = null; // set in loadSource, if at all - - /** - * The image source that is used to create the texture. This is used to - * store the original Svg source when it is replaced with a canvas element. - * - * TODO: Currently not in use but could be used when re-scaling svg. - * - * @readonly - * @member {Image} - */ - _this.origSource = null; // set in loadSvg, if at all - - /** - * Type of image defined in source, eg. `png` or `svg` - * - * @readonly - * @member {string} - */ - _this.imageType = null; // set in updateImageType - - /** - * Scale for source image. Used with Svg images to scale them before rasterization. - * - * @readonly - * @member {number} - */ - _this.sourceScale = 1.0; - - /** - * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) - * All blend modes, and shaders written for default value. Change it on your own risk. - * - * @member {boolean} - * @default true - */ - _this.premultipliedAlpha = true; - - /** - * The image url of the texture - * - * @member {string} - */ - _this.imageUrl = null; - - /** - * Whether or not the texture is a power of two, try to use power of two textures as much - * as you can - * - * @private - * @member {boolean} - */ - _this.isPowerOfTwo = false; - - // used for webGL - - /** - * - * Set this to true if a mipmap of this texture needs to be generated. This value needs - * to be set before the texture is used - * Also the texture must be a power of two size to work - * - * @member {boolean} - * @see PIXI.MIPMAP_TEXTURES - */ - _this.mipmap = _settings2.default.MIPMAP_TEXTURES; - - /** - * - * WebGL Texture wrap mode - * - * @member {number} - * @see PIXI.WRAP_MODES - */ - _this.wrapMode = _settings2.default.WRAP_MODE; - - /** - * A map of renderer IDs to webgl textures - * - * @private - * @member {object} - */ - _this._glTextures = {}; - - _this._enabled = 0; - _this._virtalBoundId = -1; - - /** - * If the object has been destroyed via destroy(). If true, it should not be used. - * - * @member {boolean} - * @private - * @readonly - */ - _this._destroyed = false; - - /** - * The ids under which this BaseTexture has been added to the base texture cache. This is - * automatically set as long as BaseTexture.addToCache is used, but may not be set if a - * BaseTexture is added directly to the BaseTextureCache array. - * - * @member {string[]} - */ - _this.textureCacheIds = []; - - // if no source passed don't try to load - if (source) { - _this.loadSource(source); - } - - /** - * Fired when a not-immediately-available source finishes loading. - * - * @protected - * @event PIXI.BaseTexture#loaded - * @param {PIXI.BaseTexture} baseTexture - Resource loaded. - */ - - /** - * Fired when a not-immediately-available source fails to load. - * - * @protected - * @event PIXI.BaseTexture#error - * @param {PIXI.BaseTexture} baseTexture - Resource errored. - */ - - /** - * Fired when BaseTexture is updated. - * - * @protected - * @event PIXI.BaseTexture#update - * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated. - */ - - /** - * Fired when BaseTexture is destroyed. - * - * @protected - * @event PIXI.BaseTexture#dispose - * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed. - */ - return _this; - } - - /** - * Updates the texture on all the webgl renderers, this also assumes the src has changed. - * - * @fires PIXI.BaseTexture#update - */ - - - BaseTexture.prototype.update = function update() { - // Svg size is handled during load - if (this.imageType !== 'svg') { - this.realWidth = this.source.naturalWidth || this.source.videoWidth || this.source.width; - this.realHeight = this.source.naturalHeight || this.source.videoHeight || this.source.height; - - this._updateDimensions(); - } - - this.emit('update', this); - }; - - /** - * Update dimensions from real values - */ - - - BaseTexture.prototype._updateDimensions = function _updateDimensions() { - this.width = this.realWidth / this.resolution; - this.height = this.realHeight / this.resolution; - - this.isPowerOfTwo = _bitTwiddle2.default.isPow2(this.realWidth) && _bitTwiddle2.default.isPow2(this.realHeight); - }; - - /** - * Load a source. - * - * If the source is not-immediately-available, such as an image that needs to be - * downloaded, then the 'loaded' or 'error' event will be dispatched in the future - * and `hasLoaded` will remain false after this call. - * - * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: - * - * if (texture.hasLoaded) { - * // texture ready for use - * } else if (texture.isLoading) { - * // listen to 'loaded' and/or 'error' events on texture - * } else { - * // not loading, not going to load UNLESS the source is reloaded - * // (it may still make sense to listen to the events) - * } - * - * @protected - * @param {HTMLImageElement|HTMLCanvasElement} source - the source object of the texture. - */ - - - BaseTexture.prototype.loadSource = function loadSource(source) { - var wasLoading = this.isLoading; - - this.hasLoaded = false; - this.isLoading = false; - - if (wasLoading && this.source) { - this.source.onload = null; - this.source.onerror = null; - } - - var firstSourceLoaded = !this.source; - - this.source = source; - - // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((source.src && source.complete || source.getContext) && source.width && source.height) { - this._updateImageType(); - - if (this.imageType === 'svg') { - this._loadSvgSource(); - } else { - this._sourceLoaded(); - } - - if (firstSourceLoaded) { - // send loaded event if previous source was null and we have been passed a pre-loaded IMG element - this.emit('loaded', this); - } - } else if (!source.getContext) { - // Image fail / not ready - this.isLoading = true; - - var scope = this; - - source.onload = function () { - scope._updateImageType(); - source.onload = null; - source.onerror = null; - - if (!scope.isLoading) { - return; - } - - scope.isLoading = false; - scope._sourceLoaded(); - - if (scope.imageType === 'svg') { - scope._loadSvgSource(); - - return; - } - - scope.emit('loaded', scope); - }; - - source.onerror = function () { - source.onload = null; - source.onerror = null; - - if (!scope.isLoading) { - return; - } - - scope.isLoading = false; - scope.emit('error', scope); - }; - - // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element - // "The value of `complete` can thus change while a script is executing." - // So complete needs to be re-checked after the callbacks have been added.. - // NOTE: complete will be true if the image has no src so best to check if the src is set. - if (source.complete && source.src) { - // ..and if we're complete now, no need for callbacks - source.onload = null; - source.onerror = null; - - if (scope.imageType === 'svg') { - scope._loadSvgSource(); - - return; - } - - this.isLoading = false; - - if (source.width && source.height) { - this._sourceLoaded(); - - // If any previous subscribers possible - if (wasLoading) { - this.emit('loaded', this); - } - } - // If any previous subscribers possible - else if (wasLoading) { - this.emit('error', this); - } - } - } - }; - - /** - * Updates type of the source image. - */ - - - BaseTexture.prototype._updateImageType = function _updateImageType() { - if (!this.imageUrl) { - return; - } - - var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); - var imageType = void 0; - - if (dataUri && dataUri.mediaType === 'image') { - // Check for subType validity - var firstSubType = dataUri.subType.split('+')[0]; - - imageType = (0, _utils.getUrlFileExtension)('.' + firstSubType); - - if (!imageType) { - throw new Error('Invalid image type in data URI.'); - } - } else { - imageType = (0, _utils.getUrlFileExtension)(this.imageUrl); - - if (!imageType) { - imageType = 'png'; - } - } - - this.imageType = imageType; - }; - - /** - * Checks if `source` is an SVG image and whether it's loaded via a URL or a data URI. Then calls - * `_loadSvgSourceUsingDataUri` or `_loadSvgSourceUsingXhr`. - */ - - - BaseTexture.prototype._loadSvgSource = function _loadSvgSource() { - if (this.imageType !== 'svg') { - // Do nothing if source is not svg - return; - } - - var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); - - if (dataUri) { - this._loadSvgSourceUsingDataUri(dataUri); - } else { - // We got an URL, so we need to do an XHR to check the svg size - this._loadSvgSourceUsingXhr(); - } - }; - - /** - * Reads an SVG string from data URI and then calls `_loadSvgSourceUsingString`. - * - * @param {string} dataUri - The data uri to load from. - */ - - - BaseTexture.prototype._loadSvgSourceUsingDataUri = function _loadSvgSourceUsingDataUri(dataUri) { - var svgString = void 0; - - if (dataUri.encoding === 'base64') { - if (!atob) { - throw new Error('Your browser doesn\'t support base64 conversions.'); - } - svgString = atob(dataUri.data); - } else { - svgString = dataUri.data; - } - - this._loadSvgSourceUsingString(svgString); - }; - - /** - * Loads an SVG string from `imageUrl` using XHR and then calls `_loadSvgSourceUsingString`. - */ - - - BaseTexture.prototype._loadSvgSourceUsingXhr = function _loadSvgSourceUsingXhr() { - var _this2 = this; - - var svgXhr = new XMLHttpRequest(); - - // This throws error on IE, so SVG Document can't be used - // svgXhr.responseType = 'document'; - - // This is not needed since we load the svg as string (breaks IE too) - // but overrideMimeType() can be used to force the response to be parsed as XML - // svgXhr.overrideMimeType('image/svg+xml'); - - svgXhr.onload = function () { - if (svgXhr.readyState !== svgXhr.DONE || svgXhr.status !== 200) { - throw new Error('Failed to load SVG using XHR.'); - } - - _this2._loadSvgSourceUsingString(svgXhr.response); - }; - - svgXhr.onerror = function () { - return _this2.emit('error', _this2); - }; - - svgXhr.open('GET', this.imageUrl, true); - svgXhr.send(); - }; - - /** - * Loads texture using an SVG string. The original SVG Image is stored as `origSource` and the - * created canvas is the new `source`. The SVG is scaled using `sourceScale`. Called by - * `_loadSvgSourceUsingXhr` or `_loadSvgSourceUsingDataUri`. - * - * @param {string} svgString SVG source as string - * - * @fires PIXI.BaseTexture#loaded - */ - - - BaseTexture.prototype._loadSvgSourceUsingString = function _loadSvgSourceUsingString(svgString) { - var svgSize = (0, _utils.getSvgSize)(svgString); - - var svgWidth = svgSize.width; - var svgHeight = svgSize.height; - - if (!svgWidth || !svgHeight) { - throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.'); - } - - // Scale realWidth and realHeight - this.realWidth = Math.round(svgWidth * this.sourceScale); - this.realHeight = Math.round(svgHeight * this.sourceScale); - - this._updateDimensions(); - - // Create a canvas element - var canvas = document.createElement('canvas'); - - canvas.width = this.realWidth; - canvas.height = this.realHeight; - canvas._pixiId = 'canvas_' + (0, _utils.uid)(); - - // Draw the Svg to the canvas - canvas.getContext('2d').drawImage(this.source, 0, 0, svgWidth, svgHeight, 0, 0, this.realWidth, this.realHeight); - - // Replace the original source image with the canvas - this.origSource = this.source; - this.source = canvas; - - // Add also the canvas in cache (destroy clears by `imageUrl` and `source._pixiId`) - BaseTexture.addToCache(this, canvas._pixiId); - - this.isLoading = false; - this._sourceLoaded(); - this.emit('loaded', this); - }; - - /** - * Used internally to update the width, height, and some other tracking vars once - * a source has successfully loaded. - * - * @private - */ - - - BaseTexture.prototype._sourceLoaded = function _sourceLoaded() { - this.hasLoaded = true; - this.update(); - }; - - /** - * Destroys this base texture - * - */ - - - BaseTexture.prototype.destroy = function destroy() { - if (this.imageUrl) { - delete _utils.TextureCache[this.imageUrl]; - - this.imageUrl = null; - - if (!navigator.isCocoonJS) { - this.source.src = ''; - } - } - - this.source = null; - - this.dispose(); - - BaseTexture.removeFromCache(this); - this.textureCacheIds = null; - - this._destroyed = true; - }; - - /** - * Frees the texture from WebGL memory without destroying this texture object. - * This means you can still use the texture later which will upload it to GPU - * memory again. - * - * @fires PIXI.BaseTexture#dispose - */ - - - BaseTexture.prototype.dispose = function dispose() { - this.emit('dispose', this); - }; - - /** - * Changes the source image of the texture. - * The original source must be an Image element. - * - * @param {string} newSrc - the path of the image - */ - - - BaseTexture.prototype.updateSourceImage = function updateSourceImage(newSrc) { - this.source.src = newSrc; - - this.loadSource(this.source); - }; - - /** - * Helper function that creates a base texture from the given image url. - * If the image is not in the base texture cache it will be created and loaded. - * - * @static - * @param {string} imageUrl - The image url of the texture - * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. - * @return {PIXI.BaseTexture} The new base texture. - */ - - - BaseTexture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { - var baseTexture = _utils.BaseTextureCache[imageUrl]; - - if (!baseTexture) { - // new Image() breaks tex loading in some versions of Chrome. - // See https://code.google.com/p/chromium/issues/detail?id=238071 - var image = new Image(); // document.createElement('img'); - - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { - image.crossOrigin = (0, _determineCrossOrigin2.default)(imageUrl); - } else if (crossorigin) { - image.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; - } - - baseTexture = new BaseTexture(image, scaleMode); - baseTexture.imageUrl = imageUrl; - - if (sourceScale) { - baseTexture.sourceScale = sourceScale; - } - - // if there is an @2x at the end of the url we are going to assume its a highres image - baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); - - image.src = imageUrl; // Setting this triggers load - - BaseTexture.addToCache(baseTexture, imageUrl); - } - - return baseTexture; - }; - - /** - * Helper function that creates a base texture from the given canvas element. - * - * @static - * @param {HTMLCanvasElement} canvas - The canvas element source of the texture - * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values - * @param {string} [origin='canvas'] - A string origin of who created the base texture - * @return {PIXI.BaseTexture} The new base texture. - */ - - - BaseTexture.fromCanvas = function fromCanvas(canvas, scaleMode) { - var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'canvas'; - - if (!canvas._pixiId) { - canvas._pixiId = origin + '_' + (0, _utils.uid)(); - } - - var baseTexture = _utils.BaseTextureCache[canvas._pixiId]; - - if (!baseTexture) { - baseTexture = new BaseTexture(canvas, scaleMode); - BaseTexture.addToCache(baseTexture, canvas._pixiId); - } - - return baseTexture; - }; - - /** - * Helper function that creates a base texture based on the source you provide. - * The source can be - image url, image element, canvas element. - * - * @static - * @param {string|HTMLImageElement|HTMLCanvasElement} source - The source to create base texture from. - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. - * @return {PIXI.BaseTexture} The new base texture. - */ - - - BaseTexture.from = function from(source, scaleMode, sourceScale) { - if (typeof source === 'string') { - return BaseTexture.fromImage(source, undefined, scaleMode, sourceScale); - } else if (source instanceof HTMLImageElement) { - var imageUrl = source.src; - var baseTexture = _utils.BaseTextureCache[imageUrl]; - - if (!baseTexture) { - baseTexture = new BaseTexture(source, scaleMode); - baseTexture.imageUrl = imageUrl; - - if (sourceScale) { - baseTexture.sourceScale = sourceScale; - } - - // if there is an @2x at the end of the url we are going to assume its a highres image - baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); - - BaseTexture.addToCache(baseTexture, imageUrl); - } - - return baseTexture; - } else if (source instanceof HTMLCanvasElement) { - return BaseTexture.fromCanvas(source, scaleMode); - } - - // lets assume its a base texture! - return source; - }; - - /** - * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object. - * - * @static - * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache. - * @param {string} id - The id that the BaseTexture will be stored against. - */ - - - BaseTexture.addToCache = function addToCache(baseTexture, id) { - if (id) { - if (baseTexture.textureCacheIds.indexOf(id) === -1) { - baseTexture.textureCacheIds.push(id); - } - - /* eslint-disable no-console */ - if (_utils.BaseTextureCache[id]) { - console.warn('BaseTexture added to the cache with an id [' + id + '] that already had an entry'); - } - /* eslint-enable no-console */ - - _utils.BaseTextureCache[id] = baseTexture; - } - }; - - /** - * Remove a BaseTexture from the global BaseTextureCache. - * - * @static - * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself. - * @return {PIXI.BaseTexture|null} The BaseTexture that was removed. - */ - - - BaseTexture.removeFromCache = function removeFromCache(baseTexture) { - if (typeof baseTexture === 'string') { - var baseTextureFromCache = _utils.BaseTextureCache[baseTexture]; - - if (baseTextureFromCache) { - var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture); - - if (index > -1) { - baseTextureFromCache.textureCacheIds.splice(index, 1); - } - - delete _utils.BaseTextureCache[baseTexture]; - - return baseTextureFromCache; - } - } else if (baseTexture && baseTexture.textureCacheIds) { - for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) { - delete _utils.BaseTextureCache[baseTexture.textureCacheIds[i]]; - } - - baseTexture.textureCacheIds.length = 0; - - return baseTexture; - } - - return null; - }; - - return BaseTexture; -}(_eventemitter2.default); - -exports.default = BaseTexture; - -},{"../settings":101,"../utils":124,"../utils/determineCrossOrigin":123,"bit-twiddle":1,"eventemitter3":3}],113:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _BaseRenderTexture = require('./BaseRenderTexture'); - -var _BaseRenderTexture2 = _interopRequireDefault(_BaseRenderTexture); - -var _Texture2 = require('./Texture'); - -var _Texture3 = _interopRequireDefault(_Texture2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * A RenderTexture is a special texture that allows any PixiJS display object to be rendered to it. - * - * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded - * otherwise black rectangles will be drawn instead. - * - * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: - * - * ```js - * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); - * let renderTexture = PIXI.RenderTexture.create(800, 600); - * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); - * - * sprite.position.x = 800/2; - * sprite.position.y = 600/2; - * sprite.anchor.x = 0.5; - * sprite.anchor.y = 0.5; - * - * renderer.render(sprite, renderTexture); - * ``` - * - * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 - * you can clear the transform - * - * ```js - * - * sprite.setTransform() - * - * let renderTexture = new PIXI.RenderTexture.create(100, 100); - * - * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture - * ``` - * - * @class - * @extends PIXI.Texture - * @memberof PIXI - */ -var RenderTexture = function (_Texture) { - _inherits(RenderTexture, _Texture); - - /** - * @param {PIXI.BaseRenderTexture} baseRenderTexture - The renderer used for this RenderTexture - * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show - */ - function RenderTexture(baseRenderTexture, frame) { - _classCallCheck(this, RenderTexture); - - // support for legacy.. - var _legacyRenderer = null; - - if (!(baseRenderTexture instanceof _BaseRenderTexture2.default)) { - /* eslint-disable prefer-rest-params, no-console */ - var width = arguments[1]; - var height = arguments[2]; - var scaleMode = arguments[3]; - var resolution = arguments[4]; - - // we have an old render texture.. - console.warn('Please use RenderTexture.create(' + width + ', ' + height + ') instead of the ctor directly.'); - _legacyRenderer = arguments[0]; - /* eslint-enable prefer-rest-params, no-console */ - - frame = null; - baseRenderTexture = new _BaseRenderTexture2.default(width, height, scaleMode, resolution); - } - - /** - * The base texture object that this texture uses - * - * @member {BaseTexture} - */ - - var _this = _possibleConstructorReturn(this, _Texture.call(this, baseRenderTexture, frame)); - - _this.legacyRenderer = _legacyRenderer; - - /** - * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. - * - * @member {boolean} - */ - _this.valid = true; - - _this._updateUvs(); - return _this; - } - - /** - * Resizes the RenderTexture. - * - * @param {number} width - The width to resize to. - * @param {number} height - The height to resize to. - * @param {boolean} doNotResizeBaseTexture - Should the baseTexture.width and height values be resized as well? - */ - - - RenderTexture.prototype.resize = function resize(width, height, doNotResizeBaseTexture) { - // TODO - could be not required.. - this.valid = width > 0 && height > 0; - - this._frame.width = this.orig.width = width; - this._frame.height = this.orig.height = height; - - if (!doNotResizeBaseTexture) { - this.baseTexture.resize(width, height); - } - - this._updateUvs(); - }; - - /** - * A short hand way of creating a render texture. - * - * @param {number} [width=100] - The width of the render texture - * @param {number} [height=100] - The height of the render texture - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated - * @return {PIXI.RenderTexture} The new render texture - */ - - - RenderTexture.create = function create(width, height, scaleMode, resolution) { - return new RenderTexture(new _BaseRenderTexture2.default(width, height, scaleMode, resolution)); - }; - - return RenderTexture; -}(_Texture3.default); - -exports.default = RenderTexture; - -},{"./BaseRenderTexture":111,"./Texture":115}],114:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _ = require('../'); - -var _utils = require('../utils'); - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * Utility class for maintaining reference to a collection - * of Textures on a single Spritesheet. - * - * @class - * @memberof PIXI - */ -var Spritesheet = function () { - _createClass(Spritesheet, null, [{ - key: 'BATCH_SIZE', - - /** - * The maximum number of Textures to build per process. - * - * @type {number} - * @default 1000 - */ - get: function get() { - return 1000; - } - - /** - * @param {PIXI.BaseTexture} baseTexture Reference to the source BaseTexture object. - * @param {Object} data - Spritesheet image data. - * @param {string} [resolutionFilename] - The filename to consider when determining - * the resolution of the spritesheet. If not provided, the imageUrl will - * be used on the BaseTexture. - */ - - }]); - - function Spritesheet(baseTexture, data) { - var resolutionFilename = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; - - _classCallCheck(this, Spritesheet); - - /** - * Reference to ths source texture - * @type {PIXI.BaseTexture} - */ - this.baseTexture = baseTexture; - - /** - * Map of spritesheet textures. - * @type {Object} - */ - this.textures = {}; - - /** - * Reference to the original JSON data. - * @type {Object} - */ - this.data = data; - - /** - * The resolution of the spritesheet. - * @type {number} - */ - this.resolution = this._updateResolution(resolutionFilename || this.baseTexture.imageUrl); - - /** - * Map of spritesheet frames. - * @type {Object} - * @private - */ - this._frames = this.data.frames; - - /** - * Collection of frame names. - * @type {string[]} - * @private - */ - this._frameKeys = Object.keys(this._frames); - - /** - * Current batch index being processed. - * @type {number} - * @private - */ - this._batchIndex = 0; - - /** - * Callback when parse is completed. - * @type {Function} - * @private - */ - this._callback = null; - } - - /** - * Generate the resolution from the filename or fallback - * to the meta.scale field of the JSON data. - * - * @private - * @param {string} resolutionFilename - The filename to use for resolving - * the default resolution. - * @return {number} Resolution to use for spritesheet. - */ - - - Spritesheet.prototype._updateResolution = function _updateResolution(resolutionFilename) { - var scale = this.data.meta.scale; - - // Use a defaultValue of `null` to check if a url-based resolution is set - var resolution = (0, _utils.getResolutionOfUrl)(resolutionFilename, null); - - // No resolution found via URL - if (resolution === null) { - // Use the scale value or default to 1 - resolution = scale !== undefined ? parseFloat(scale) : 1; - } - - // For non-1 resolutions, update baseTexture - if (resolution !== 1) { - this.baseTexture.resolution = resolution; - this.baseTexture.update(); - } - - return resolution; - }; - - /** - * Parser spritesheet from loaded data. This is done asynchronously - * to prevent creating too many Texture within a single process. - * - * @param {Function} callback - Callback when complete returns - * a map of the Textures for this spritesheet. - */ - - - Spritesheet.prototype.parse = function parse(callback) { - this._batchIndex = 0; - this._callback = callback; - - if (this._frameKeys.length <= Spritesheet.BATCH_SIZE) { - this._processFrames(0); - this._parseComplete(); - } else { - this._nextBatch(); - } - }; - - /** - * Process a batch of frames - * - * @private - * @param {number} initialFrameIndex - The index of frame to start. - */ - - - Spritesheet.prototype._processFrames = function _processFrames(initialFrameIndex) { - var frameIndex = initialFrameIndex; - var maxFrames = Spritesheet.BATCH_SIZE; - - while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { - var i = this._frameKeys[frameIndex]; - var rect = this._frames[i].frame; - - if (rect) { - var frame = null; - var trim = null; - var orig = new _.Rectangle(0, 0, this._frames[i].sourceSize.w / this.resolution, this._frames[i].sourceSize.h / this.resolution); - - if (this._frames[i].rotated) { - frame = new _.Rectangle(rect.x / this.resolution, rect.y / this.resolution, rect.h / this.resolution, rect.w / this.resolution); - } else { - frame = new _.Rectangle(rect.x / this.resolution, rect.y / this.resolution, rect.w / this.resolution, rect.h / this.resolution); - } - - // Check to see if the sprite is trimmed - if (this._frames[i].trimmed) { - trim = new _.Rectangle(this._frames[i].spriteSourceSize.x / this.resolution, this._frames[i].spriteSourceSize.y / this.resolution, rect.w / this.resolution, rect.h / this.resolution); - } - - this.textures[i] = new _.Texture(this.baseTexture, frame, orig, trim, this._frames[i].rotated ? 2 : 0); - - // lets also add the frame to pixi's global cache for fromFrame and fromImage functions - _.Texture.addToCache(this.textures[i], i); - } - - frameIndex++; - } - }; - - /** - * The parse has completed. - * - * @private - */ - - - Spritesheet.prototype._parseComplete = function _parseComplete() { - var callback = this._callback; - - this._callback = null; - this._batchIndex = 0; - callback.call(this, this.textures); - }; - - /** - * Begin the next batch of textures. - * - * @private - */ - - - Spritesheet.prototype._nextBatch = function _nextBatch() { - var _this = this; - - this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); - this._batchIndex++; - setTimeout(function () { - if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) { - _this._nextBatch(); - } else { - _this._parseComplete(); - } - }, 0); - }; - - /** - * Destroy Spritesheet and don't use after this. - * - * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well - */ - - - Spritesheet.prototype.destroy = function destroy() { - var destroyBase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - - for (var i in this.textures) { - this.textures[i].destroy(); - } - this._frames = null; - this._frameKeys = null; - this.data = null; - this.textures = null; - if (destroyBase) { - this.baseTexture.destroy(); - } - this.baseTexture = null; - }; - - return Spritesheet; -}(); - -exports.default = Spritesheet; - -},{"../":65,"../utils":124}],115:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _BaseTexture = require('./BaseTexture'); - -var _BaseTexture2 = _interopRequireDefault(_BaseTexture); - -var _VideoBaseTexture = require('./VideoBaseTexture'); - -var _VideoBaseTexture2 = _interopRequireDefault(_VideoBaseTexture); - -var _TextureUvs = require('./TextureUvs'); - -var _TextureUvs2 = _interopRequireDefault(_TextureUvs); - -var _eventemitter = require('eventemitter3'); - -var _eventemitter2 = _interopRequireDefault(_eventemitter); - -var _math = require('../math'); - -var _utils = require('../utils'); - -var _settings = require('../settings'); - -var _settings2 = _interopRequireDefault(_settings); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * A texture stores the information that represents an image or part of an image. It cannot be added - * to the display list directly. Instead use it as the texture for a Sprite. If no frame is provided - * then the whole image is used. - * - * You can directly create a texture from an image and then reuse it multiple times like this : - * - * ```js - * let texture = PIXI.Texture.fromImage('assets/image.png'); - * let sprite1 = new PIXI.Sprite(texture); - * let sprite2 = new PIXI.Sprite(texture); - * ``` - * - * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. - * You can check for this by checking the sprite's _textureID property. - * ```js - * var texture = PIXI.Texture.fromImage('assets/image.svg'); - * var sprite1 = new PIXI.Sprite(texture); - * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file - * ``` - * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. - * - * @class - * @extends EventEmitter - * @memberof PIXI - */ -var Texture = function (_EventEmitter) { - _inherits(Texture, _EventEmitter); - - /** - * @param {PIXI.BaseTexture} baseTexture - The base texture source to create the texture from - * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show - * @param {PIXI.Rectangle} [orig] - The area of original texture - * @param {PIXI.Rectangle} [trim] - Trimmed rectangle of original texture - * @param {number} [rotate] - indicates how the texture was rotated by texture packer. See {@link PIXI.GroupD8} - */ - function Texture(baseTexture, frame, orig, trim, rotate) { - _classCallCheck(this, Texture); - - /** - * Does this Texture have any frame data assigned to it? - * - * @member {boolean} - */ - var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); - - _this.noFrame = false; - - if (!frame) { - _this.noFrame = true; - frame = new _math.Rectangle(0, 0, 1, 1); - } - - if (baseTexture instanceof Texture) { - baseTexture = baseTexture.baseTexture; - } - - /** - * The base texture that this texture uses. - * - * @member {PIXI.BaseTexture} - */ - _this.baseTexture = baseTexture; - - /** - * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, - * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) - * - * @member {PIXI.Rectangle} - */ - _this._frame = frame; - - /** - * This is the trimmed area of original texture, before it was put in atlas - * - * @member {PIXI.Rectangle} - */ - _this.trim = trim; - - /** - * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. - * - * @member {boolean} - */ - _this.valid = false; - - /** - * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) - * - * @member {boolean} - */ - _this.requiresUpdate = false; - - /** - * The WebGL UV data cache. - * - * @member {PIXI.TextureUvs} - * @private - */ - _this._uvs = null; - - /** - * This is the area of original texture, before it was put in atlas - * - * @member {PIXI.Rectangle} - */ - _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); - - _this._rotate = Number(rotate || 0); - - if (rotate === true) { - // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures - _this._rotate = 2; - } else if (_this._rotate % 2 !== 0) { - throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); - } - - if (baseTexture.hasLoaded) { - if (_this.noFrame) { - frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); - - // if there is no frame we should monitor for any base texture changes.. - baseTexture.on('update', _this.onBaseTextureUpdated, _this); - } - _this.frame = frame; - } else { - baseTexture.once('loaded', _this.onBaseTextureLoaded, _this); - } - - /** - * Fired when the texture is updated. This happens if the frame or the baseTexture is updated. - * - * @event PIXI.Texture#update - * @protected - * @param {PIXI.Texture} texture - Instance of texture being updated. - */ - - _this._updateID = 0; - - /** - * Extra field for extra plugins. May contain clamp settings and some matrices - * @type {Object} - */ - _this.transform = null; - - /** - * The ids under which this Texture has been added to the texture cache. This is - * automatically set as long as Texture.addToCache is used, but may not be set if a - * Texture is added directly to the TextureCache array. - * - * @member {string[]} - */ - _this.textureCacheIds = []; - return _this; - } - - /** - * Updates this texture on the gpu. - * - */ - - - Texture.prototype.update = function update() { - this.baseTexture.update(); - }; - - /** - * Called when the base texture is loaded - * - * @private - * @param {PIXI.BaseTexture} baseTexture - The base texture. - */ - - - Texture.prototype.onBaseTextureLoaded = function onBaseTextureLoaded(baseTexture) { - this._updateID++; - - // TODO this code looks confusing.. boo to abusing getters and setters! - if (this.noFrame) { - this.frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); - } else { - this.frame = this._frame; - } - - this.baseTexture.on('update', this.onBaseTextureUpdated, this); - this.emit('update', this); - }; - - /** - * Called when the base texture is updated - * - * @private - * @param {PIXI.BaseTexture} baseTexture - The base texture. - */ - - - Texture.prototype.onBaseTextureUpdated = function onBaseTextureUpdated(baseTexture) { - this._updateID++; - - this._frame.width = baseTexture.width; - this._frame.height = baseTexture.height; - - this.emit('update', this); - }; - - /** - * Destroys this texture - * - * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well - */ - - - Texture.prototype.destroy = function destroy(destroyBase) { - if (this.baseTexture) { - if (destroyBase) { - // delete the texture if it exists in the texture cache.. - // this only needs to be removed if the base texture is actually destroyed too.. - if (_utils.TextureCache[this.baseTexture.imageUrl]) { - Texture.removeFromCache(this.baseTexture.imageUrl); - } - - this.baseTexture.destroy(); - } - - this.baseTexture.off('update', this.onBaseTextureUpdated, this); - this.baseTexture.off('loaded', this.onBaseTextureLoaded, this); - - this.baseTexture = null; - } - - this._frame = null; - this._uvs = null; - this.trim = null; - this.orig = null; - - this.valid = false; - - Texture.removeFromCache(this); - this.textureCacheIds = null; - }; - - /** - * Creates a new texture object that acts the same as this one. - * - * @return {PIXI.Texture} The new texture - */ - - - Texture.prototype.clone = function clone() { - return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate); - }; - - /** - * Updates the internal WebGL UV cache. - * - * @protected - */ - - - Texture.prototype._updateUvs = function _updateUvs() { - if (!this._uvs) { - this._uvs = new _TextureUvs2.default(); - } - - this._uvs.set(this._frame, this.baseTexture, this.rotate); - - this._updateID++; - }; - - /** - * Helper function that creates a Texture object from the given image url. - * If the image is not in the texture cache it will be created and loaded. - * - * @static - * @param {string} imageUrl - The image url of the texture - * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. - * @return {PIXI.Texture} The newly created texture - */ - - - Texture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { - var texture = _utils.TextureCache[imageUrl]; - - if (!texture) { - texture = new Texture(_BaseTexture2.default.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); - Texture.addToCache(texture, imageUrl); - } - - return texture; - }; - - /** - * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId - * The frame ids are created when a Texture packer file has been loaded - * - * @static - * @param {string} frameId - The frame Id of the texture in the cache - * @return {PIXI.Texture} The newly created texture - */ - - - Texture.fromFrame = function fromFrame(frameId) { - var texture = _utils.TextureCache[frameId]; - - if (!texture) { - throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); - } - - return texture; - }; - - /** - * Helper function that creates a new Texture based on the given canvas element. - * - * @static - * @param {HTMLCanvasElement} canvas - The canvas element source of the texture - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {string} [origin='canvas'] - A string origin of who created the base texture - * @return {PIXI.Texture} The newly created texture - */ - - - Texture.fromCanvas = function fromCanvas(canvas, scaleMode) { - var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'canvas'; - - return new Texture(_BaseTexture2.default.fromCanvas(canvas, scaleMode, origin)); - }; - - /** - * Helper function that creates a new Texture based on the given video element. - * - * @static - * @param {HTMLVideoElement|string} video - The URL or actual element of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - - - Texture.fromVideo = function fromVideo(video, scaleMode) { - if (typeof video === 'string') { - return Texture.fromVideoUrl(video, scaleMode); - } - - return new Texture(_VideoBaseTexture2.default.fromVideo(video, scaleMode)); - }; - - /** - * Helper function that creates a new Texture based on the video url. - * - * @static - * @param {string} videoUrl - URL of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - - - Texture.fromVideoUrl = function fromVideoUrl(videoUrl, scaleMode) { - return new Texture(_VideoBaseTexture2.default.fromUrl(videoUrl, scaleMode)); - }; - - /** - * Helper function that creates a new Texture based on the source you provide. - * The source can be - frame id, image url, video url, canvas element, video element, base texture - * - * @static - * @param {number|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} - * source - Source to create texture from - * @return {PIXI.Texture} The newly created texture - */ - - - Texture.from = function from(source) { - // TODO auto detect cross origin.. - // TODO pass in scale mode? - if (typeof source === 'string') { - var texture = _utils.TextureCache[source]; - - if (!texture) { - // check if its a video.. - var isVideo = source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/) !== null; - - if (isVideo) { - return Texture.fromVideoUrl(source); - } - - return Texture.fromImage(source); - } - - return texture; - } else if (source instanceof HTMLImageElement) { - return new Texture(_BaseTexture2.default.from(source)); - } else if (source instanceof HTMLCanvasElement) { - return Texture.fromCanvas(source, _settings2.default.SCALE_MODE, 'HTMLCanvasElement'); - } else if (source instanceof HTMLVideoElement) { - return Texture.fromVideo(source); - } else if (source instanceof _BaseTexture2.default) { - return new Texture(source); - } - - // lets assume its a texture! - return source; - }; - - /** - * Create a texture from a source and add to the cache. - * - * @static - * @param {HTMLImageElement|HTMLCanvasElement} source - The input source. - * @param {String} imageUrl - File name of texture, for cache and resolving resolution. - * @param {String} [name] - Human readible name for the texture cache. If no name is - * specified, only `imageUrl` will be used as the cache ID. - * @return {PIXI.Texture} Output texture - */ - - - Texture.fromLoader = function fromLoader(source, imageUrl, name) { - var baseTexture = new _BaseTexture2.default(source, undefined, (0, _utils.getResolutionOfUrl)(imageUrl)); - var texture = new Texture(baseTexture); - - baseTexture.imageUrl = imageUrl; - - // No name, use imageUrl instead - if (!name) { - name = imageUrl; - } - - // lets also add the frame to pixi's global cache for fromFrame and fromImage fucntions - _BaseTexture2.default.addToCache(texture.baseTexture, name); - Texture.addToCache(texture, name); - - // also add references by url if they are different. - if (name !== imageUrl) { - _BaseTexture2.default.addToCache(texture.baseTexture, imageUrl); - Texture.addToCache(texture, imageUrl); - } - - return texture; - }; - - /** - * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object. - * - * @static - * @param {PIXI.Texture} texture - The Texture to add to the cache. - * @param {string} id - The id that the Texture will be stored against. - */ - - - Texture.addToCache = function addToCache(texture, id) { - if (id) { - if (texture.textureCacheIds.indexOf(id) === -1) { - texture.textureCacheIds.push(id); - } - - /* eslint-disable no-console */ - if (_utils.TextureCache[id]) { - console.warn('Texture added to the cache with an id [' + id + '] that already had an entry'); - } - /* eslint-enable no-console */ - - _utils.TextureCache[id] = texture; - } - }; - - /** - * Remove a Texture from the global TextureCache. - * - * @static - * @param {string|PIXI.Texture} texture - id of a Texture to be removed, or a Texture instance itself - * @return {PIXI.Texture|null} The Texture that was removed - */ - - - Texture.removeFromCache = function removeFromCache(texture) { - if (typeof texture === 'string') { - var textureFromCache = _utils.TextureCache[texture]; - - if (textureFromCache) { - var index = textureFromCache.textureCacheIds.indexOf(texture); - - if (index > -1) { - textureFromCache.textureCacheIds.splice(index, 1); - } - - delete _utils.TextureCache[texture]; - - return textureFromCache; - } - } else if (texture && texture.textureCacheIds) { - for (var i = 0; i < texture.textureCacheIds.length; ++i) { - delete _utils.TextureCache[texture.textureCacheIds[i]]; - } - - texture.textureCacheIds.length = 0; - - return texture; - } - - return null; - }; - - /** - * The frame specifies the region of the base texture that this texture uses. - * - * @member {PIXI.Rectangle} - */ - - - _createClass(Texture, [{ - key: 'frame', - get: function get() { - return this._frame; - }, - set: function set(frame) // eslint-disable-line require-jsdoc - { - this._frame = frame; - - this.noFrame = false; - - if (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height) { - throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' + ('X: ' + frame.x + ' + ' + frame.width + ' = ' + (frame.x + frame.width) + ' > ' + this.baseTexture.width + ' ') + ('Y: ' + frame.y + ' + ' + frame.height + ' = ' + (frame.y + frame.height) + ' > ' + this.baseTexture.height)); - } - - // this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - this.valid = frame && frame.width && frame.height && this.baseTexture.hasLoaded; - - if (!this.trim && !this.rotate) { - this.orig = frame; - } - - if (this.valid) { - this._updateUvs(); - } - } - - /** - * Indicates whether the texture is rotated inside the atlas - * set to 2 to compensate for texture packer rotation - * set to 6 to compensate for spine packer rotation - * can be used to rotate or mirror sprites - * See {@link PIXI.GroupD8} for explanation - * - * @member {number} - */ - - }, { - key: 'rotate', - get: function get() { - return this._rotate; - }, - set: function set(rotate) // eslint-disable-line require-jsdoc - { - this._rotate = rotate; - if (this.valid) { - this._updateUvs(); - } - } - - /** - * The width of the Texture in pixels. - * - * @member {number} - */ - - }, { - key: 'width', - get: function get() { - return this.orig.width; - } - - /** - * The height of the Texture in pixels. - * - * @member {number} - */ - - }, { - key: 'height', - get: function get() { - return this.orig.height; - } - }]); - - return Texture; -}(_eventemitter2.default); - -exports.default = Texture; - - -function createWhiteTexture() { - var canvas = document.createElement('canvas'); - - canvas.width = 10; - canvas.height = 10; - - var context = canvas.getContext('2d'); - - context.fillStyle = 'white'; - context.fillRect(0, 0, 10, 10); - - return new Texture(new _BaseTexture2.default(canvas)); -} - -function removeAllHandlers(tex) { - tex.destroy = function _emptyDestroy() {/* empty */}; - tex.on = function _emptyOn() {/* empty */}; - tex.once = function _emptyOnce() {/* empty */}; - tex.emit = function _emptyEmit() {/* empty */}; -} - -/** - * An empty texture, used often to not have to create multiple empty textures. - * Can not be destroyed. - * - * @static - * @constant - */ -Texture.EMPTY = new Texture(new _BaseTexture2.default()); -removeAllHandlers(Texture.EMPTY); -removeAllHandlers(Texture.EMPTY.baseTexture); - -/** - * A white texture of 10x10 size, used for graphics and other things - * Can not be destroyed. - * - * @static - * @constant - */ -Texture.WHITE = createWhiteTexture(); -removeAllHandlers(Texture.WHITE); -removeAllHandlers(Texture.WHITE.baseTexture); - -},{"../math":70,"../settings":101,"../utils":124,"./BaseTexture":112,"./TextureUvs":116,"./VideoBaseTexture":117,"eventemitter3":3}],116:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _GroupD = require('../math/GroupD8'); - -var _GroupD2 = _interopRequireDefault(_GroupD); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * A standard object to store the Uvs of a texture - * - * @class - * @private - * @memberof PIXI - */ -var TextureUvs = function () { - /** - * - */ - function TextureUvs() { - _classCallCheck(this, TextureUvs); - - this.x0 = 0; - this.y0 = 0; - - this.x1 = 1; - this.y1 = 0; - - this.x2 = 1; - this.y2 = 1; - - this.x3 = 0; - this.y3 = 1; - - this.uvsUint32 = new Uint32Array(4); - } - - /** - * Sets the texture Uvs based on the given frame information. - * - * @private - * @param {PIXI.Rectangle} frame - The frame of the texture - * @param {PIXI.Rectangle} baseFrame - The base frame of the texture - * @param {number} rotate - Rotation of frame, see {@link PIXI.GroupD8} - */ - - - TextureUvs.prototype.set = function set(frame, baseFrame, rotate) { - var tw = baseFrame.width; - var th = baseFrame.height; - - if (rotate) { - // width and height div 2 div baseFrame size - var w2 = frame.width / 2 / tw; - var h2 = frame.height / 2 / th; - - // coordinates of center - var cX = frame.x / tw + w2; - var cY = frame.y / th + h2; - - rotate = _GroupD2.default.add(rotate, _GroupD2.default.NW); // NW is top-left corner - this.x0 = cX + w2 * _GroupD2.default.uX(rotate); - this.y0 = cY + h2 * _GroupD2.default.uY(rotate); - - rotate = _GroupD2.default.add(rotate, 2); // rotate 90 degrees clockwise - this.x1 = cX + w2 * _GroupD2.default.uX(rotate); - this.y1 = cY + h2 * _GroupD2.default.uY(rotate); - - rotate = _GroupD2.default.add(rotate, 2); - this.x2 = cX + w2 * _GroupD2.default.uX(rotate); - this.y2 = cY + h2 * _GroupD2.default.uY(rotate); - - rotate = _GroupD2.default.add(rotate, 2); - this.x3 = cX + w2 * _GroupD2.default.uX(rotate); - this.y3 = cY + h2 * _GroupD2.default.uY(rotate); - } else { - this.x0 = frame.x / tw; - this.y0 = frame.y / th; - - this.x1 = (frame.x + frame.width) / tw; - this.y1 = frame.y / th; - - this.x2 = (frame.x + frame.width) / tw; - this.y2 = (frame.y + frame.height) / th; - - this.x3 = frame.x / tw; - this.y3 = (frame.y + frame.height) / th; - } - - this.uvsUint32[0] = (this.y0 * 65535 & 0xFFFF) << 16 | this.x0 * 65535 & 0xFFFF; - this.uvsUint32[1] = (this.y1 * 65535 & 0xFFFF) << 16 | this.x1 * 65535 & 0xFFFF; - this.uvsUint32[2] = (this.y2 * 65535 & 0xFFFF) << 16 | this.x2 * 65535 & 0xFFFF; - this.uvsUint32[3] = (this.y3 * 65535 & 0xFFFF) << 16 | this.x3 * 65535 & 0xFFFF; - }; - - return TextureUvs; -}(); - -exports.default = TextureUvs; - -},{"../math/GroupD8":66}],117:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _BaseTexture2 = require('./BaseTexture'); - -var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); - -var _utils = require('../utils'); - -var _ticker = require('../ticker'); - -var _const = require('../const'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * A texture of a [playing] Video. - * - * Video base textures mimic PixiJS BaseTexture.from.... method in their creation process. - * - * This can be used in several ways, such as: - * - * ```js - * let texture = PIXI.VideoBaseTexture.fromUrl('http://mydomain.com/video.mp4'); - * - * let texture = PIXI.VideoBaseTexture.fromUrl({ src: 'http://mydomain.com/video.mp4', mime: 'video/mp4' }); - * - * let texture = PIXI.VideoBaseTexture.fromUrls(['/video.webm', '/video.mp4']); - * - * let texture = PIXI.VideoBaseTexture.fromUrls([ - * { src: '/video.webm', mime: 'video/webm' }, - * { src: '/video.mp4', mime: 'video/mp4' } - * ]); - * ``` - * - * See the ["deus" demo](http://www.goodboydigital.com/pixijs/examples/deus/). - * - * @class - * @extends PIXI.BaseTexture - * @memberof PIXI - */ -var VideoBaseTexture = function (_BaseTexture) { - _inherits(VideoBaseTexture, _BaseTexture); - - /** - * @param {HTMLVideoElement} source - Video source - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - */ - function VideoBaseTexture(source, scaleMode) { - _classCallCheck(this, VideoBaseTexture); - - if (!source) { - throw new Error('No video source element specified.'); - } - - // hook in here to check if video is already available. - // BaseTexture looks for a source.complete boolean, plus width & height. - - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { - source.complete = true; - } - - var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, source, scaleMode)); - - _this.width = source.videoWidth; - _this.height = source.videoHeight; - - _this._autoUpdate = true; - _this._isAutoUpdating = false; - - /** - * When set to true will automatically play videos used by this texture once - * they are loaded. If false, it will not modify the playing state. - * - * @member {boolean} - * @default true - */ - _this.autoPlay = true; - - _this.update = _this.update.bind(_this); - _this._onCanPlay = _this._onCanPlay.bind(_this); - - source.addEventListener('play', _this._onPlayStart.bind(_this)); - source.addEventListener('pause', _this._onPlayStop.bind(_this)); - _this.hasLoaded = false; - _this.__loaded = false; - - if (!_this._isSourceReady()) { - source.addEventListener('canplay', _this._onCanPlay); - source.addEventListener('canplaythrough', _this._onCanPlay); - } else { - _this._onCanPlay(); - } - return _this; - } - - /** - * Returns true if the underlying source is playing. - * - * @private - * @return {boolean} True if playing. - */ - - - VideoBaseTexture.prototype._isSourcePlaying = function _isSourcePlaying() { - var source = this.source; - - return source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2; - }; - - /** - * Returns true if the underlying source is ready for playing. - * - * @private - * @return {boolean} True if ready. - */ - - - VideoBaseTexture.prototype._isSourceReady = function _isSourceReady() { - return this.source.readyState === 3 || this.source.readyState === 4; - }; - - /** - * Runs the update loop when the video is ready to play - * - * @private - */ - - - VideoBaseTexture.prototype._onPlayStart = function _onPlayStart() { - // Just in case the video has not received its can play even yet.. - if (!this.hasLoaded) { - this._onCanPlay(); - } - - if (!this._isAutoUpdating && this.autoUpdate) { - _ticker.shared.add(this.update, this, _const.UPDATE_PRIORITY.HIGH); - this._isAutoUpdating = true; - } - }; - - /** - * Fired when a pause event is triggered, stops the update loop - * - * @private - */ - - - VideoBaseTexture.prototype._onPlayStop = function _onPlayStop() { - if (this._isAutoUpdating) { - _ticker.shared.remove(this.update, this); - this._isAutoUpdating = false; - } - }; - - /** - * Fired when the video is loaded and ready to play - * - * @private - */ - - - VideoBaseTexture.prototype._onCanPlay = function _onCanPlay() { - this.hasLoaded = true; - - if (this.source) { - this.source.removeEventListener('canplay', this._onCanPlay); - this.source.removeEventListener('canplaythrough', this._onCanPlay); - - this.width = this.source.videoWidth; - this.height = this.source.videoHeight; - - // prevent multiple loaded dispatches.. - if (!this.__loaded) { - this.__loaded = true; - this.emit('loaded', this); - } - - if (this._isSourcePlaying()) { - this._onPlayStart(); - } else if (this.autoPlay) { - this.source.play(); - } - } - }; - - /** - * Destroys this texture - * - */ - - - VideoBaseTexture.prototype.destroy = function destroy() { - if (this._isAutoUpdating) { - _ticker.shared.remove(this.update, this); - } - - if (this.source && this.source._pixiId) { - _BaseTexture3.default.removeFromCache(this.source._pixiId); - delete this.source._pixiId; - } - - _BaseTexture.prototype.destroy.call(this); - }; - - /** - * Mimic PixiJS BaseTexture.from.... method. - * - * @static - * @param {HTMLVideoElement} video - Video to create texture from - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture - */ - - - VideoBaseTexture.fromVideo = function fromVideo(video, scaleMode) { - if (!video._pixiId) { - video._pixiId = 'video_' + (0, _utils.uid)(); - } - - var baseTexture = _utils.BaseTextureCache[video._pixiId]; - - if (!baseTexture) { - baseTexture = new VideoBaseTexture(video, scaleMode); - _BaseTexture3.default.addToCache(baseTexture, video._pixiId); - } - - return baseTexture; - }; - - /** - * Helper function that creates a new BaseTexture based on the given video element. - * This BaseTexture can then be used to create a texture - * - * @static - * @param {string|object|string[]|object[]} videoSrc - The URL(s) for the video. - * @param {string} [videoSrc.src] - One of the source urls for the video - * @param {string} [videoSrc.mime] - The mimetype of the video (e.g. 'video/mp4'). If not specified - * the url's extension will be used as the second part of the mime type. - * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture - */ - - - VideoBaseTexture.fromUrl = function fromUrl(videoSrc, scaleMode) { - var video = document.createElement('video'); - - video.setAttribute('webkit-playsinline', ''); - video.setAttribute('playsinline', ''); - - // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { - video.appendChild(createSource(videoSrc[i].src || videoSrc[i], videoSrc[i].mime)); - } - } - // single object or string - else { - video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); - } - - video.load(); - - return VideoBaseTexture.fromVideo(video, scaleMode); - }; - - /** - * Should the base texture automatically update itself, set to true by default - * - * @member {boolean} - */ - - - _createClass(VideoBaseTexture, [{ - key: 'autoUpdate', - get: function get() { - return this._autoUpdate; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - if (value !== this._autoUpdate) { - this._autoUpdate = value; - - if (!this._autoUpdate && this._isAutoUpdating) { - _ticker.shared.remove(this.update, this); - this._isAutoUpdating = false; - } else if (this._autoUpdate && !this._isAutoUpdating) { - _ticker.shared.add(this.update, this, _const.UPDATE_PRIORITY.HIGH); - this._isAutoUpdating = true; - } - } - } - }]); - - return VideoBaseTexture; -}(_BaseTexture3.default); - -exports.default = VideoBaseTexture; - - -VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; - -function createSource(path, type) { - if (!type) { - type = 'video/' + path.substr(path.lastIndexOf('.') + 1); - } - - var source = document.createElement('source'); - - source.src = path; - source.type = type; - - return source; -} - -},{"../const":46,"../ticker":120,"../utils":124,"./BaseTexture":112}],118:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _settings = require('../settings'); - -var _settings2 = _interopRequireDefault(_settings); - -var _const = require('../const'); - -var _TickerListener = require('./TickerListener'); - -var _TickerListener2 = _interopRequireDefault(_TickerListener); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * A Ticker class that runs an update loop that other objects listen to. - * This class is composed around listeners - * meant for execution on the next requested animation frame. - * Animation frames are requested only when necessary, - * e.g. When the ticker is started and the emitter has listeners. - * - * @class - * @memberof PIXI.ticker - */ -var Ticker = function () { - /** - * - */ - function Ticker() { - var _this = this; - - _classCallCheck(this, Ticker); - - /** - * The first listener. All new listeners added are chained on this. - * @private - * @type {TickerListener} - */ - this._head = new _TickerListener2.default(null, null, Infinity); - - /** - * Internal current frame request ID - * @private - */ - this._requestId = null; - - /** - * Internal value managed by minFPS property setter and getter. - * This is the maximum allowed milliseconds between updates. - * @private - */ - this._maxElapsedMS = 100; - - /** - * Whether or not this ticker should invoke the method - * {@link PIXI.ticker.Ticker#start} automatically - * when a listener is added. - * - * @member {boolean} - * @default false - */ - this.autoStart = false; - - /** - * Scalar time value from last frame to this frame. - * This value is capped by setting {@link PIXI.ticker.Ticker#minFPS} - * and is scaled with {@link PIXI.ticker.Ticker#speed}. - * **Note:** The cap may be exceeded by scaling. - * - * @member {number} - * @default 1 - */ - this.deltaTime = 1; - - /** - * Time elapsed in milliseconds from last frame to this frame. - * Opposed to what the scalar {@link PIXI.ticker.Ticker#deltaTime} - * is based, this value is neither capped nor scaled. - * If the platform supports DOMHighResTimeStamp, - * this value will have a precision of 1 µs. - * Defaults to target frame time - * - * @member {number} - * @default 16.66 - */ - this.elapsedMS = 1 / _settings2.default.TARGET_FPMS; - - /** - * The last time {@link PIXI.ticker.Ticker#update} was invoked. - * This value is also reset internally outside of invoking - * update, but only when a new animation frame is requested. - * If the platform supports DOMHighResTimeStamp, - * this value will have a precision of 1 µs. - * - * @member {number} - * @default 0 - */ - this.lastTime = 0; - - /** - * Factor of current {@link PIXI.ticker.Ticker#deltaTime}. - * @example - * // Scales ticker.deltaTime to what would be - * // the equivalent of approximately 120 FPS - * ticker.speed = 2; - * - * @member {number} - * @default 1 - */ - this.speed = 1; - - /** - * Whether or not this ticker has been started. - * `true` if {@link PIXI.ticker.Ticker#start} has been called. - * `false` if {@link PIXI.ticker.Ticker#stop} has been called. - * While `false`, this value may change to `true` in the - * event of {@link PIXI.ticker.Ticker#autoStart} being `true` - * and a listener is added. - * - * @member {boolean} - * @default false - */ - this.started = false; - - /** - * Internal tick method bound to ticker instance. - * This is because in early 2015, Function.bind - * is still 60% slower in high performance scenarios. - * Also separating frame requests from update method - * so listeners may be called at any time and with - * any animation API, just invoke ticker.update(time). - * - * @private - * @param {number} time - Time since last tick. - */ - this._tick = function (time) { - _this._requestId = null; - - if (_this.started) { - // Invoke listeners now - _this.update(time); - // Listener side effects may have modified ticker state. - if (_this.started && _this._requestId === null && _this._head.next) { - _this._requestId = requestAnimationFrame(_this._tick); - } - } - }; - } - - /** - * Conditionally requests a new animation frame. - * If a frame has not already been requested, and if the internal - * emitter has listeners, a new frame is requested. - * - * @private - */ - - - Ticker.prototype._requestIfNeeded = function _requestIfNeeded() { - if (this._requestId === null && this._head.next) { - // ensure callbacks get correct delta - this.lastTime = performance.now(); - this._requestId = requestAnimationFrame(this._tick); - } - }; - - /** - * Conditionally cancels a pending animation frame. - * - * @private - */ - - - Ticker.prototype._cancelIfNeeded = function _cancelIfNeeded() { - if (this._requestId !== null) { - cancelAnimationFrame(this._requestId); - this._requestId = null; - } - }; - - /** - * Conditionally requests a new animation frame. - * If the ticker has been started it checks if a frame has not already - * been requested, and if the internal emitter has listeners. If these - * conditions are met, a new frame is requested. If the ticker has not - * been started, but autoStart is `true`, then the ticker starts now, - * and continues with the previous conditions to request a new frame. - * - * @private - */ - - - Ticker.prototype._startIfPossible = function _startIfPossible() { - if (this.started) { - this._requestIfNeeded(); - } else if (this.autoStart) { - this.start(); - } - }; - - /** - * Register a handler for tick events. Calls continuously unless - * it is removed or the ticker is stopped. - * - * @param {Function} fn - The listener function to be added for updates - * @param {Function} [context] - The listener context - * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting - * @returns {PIXI.ticker.Ticker} This instance of a ticker - */ - - - Ticker.prototype.add = function add(fn, context) { - var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _const.UPDATE_PRIORITY.NORMAL; - - return this._addListener(new _TickerListener2.default(fn, context, priority)); - }; - - /** - * Add a handler for the tick event which is only execute once. - * - * @param {Function} fn - The listener function to be added for one update - * @param {Function} [context] - The listener context - * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting - * @returns {PIXI.ticker.Ticker} This instance of a ticker - */ - - - Ticker.prototype.addOnce = function addOnce(fn, context) { - var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _const.UPDATE_PRIORITY.NORMAL; - - return this._addListener(new _TickerListener2.default(fn, context, priority, true)); - }; - - /** - * Internally adds the event handler so that it can be sorted by priority. - * Priority allows certain handler (user, AnimatedSprite, Interaction) to be run - * before the rendering. - * - * @private - * @param {TickerListener} listener - Current listener being added. - * @returns {PIXI.ticker.Ticker} This instance of a ticker - */ - - - Ticker.prototype._addListener = function _addListener(listener) { - // For attaching to head - var current = this._head.next; - var previous = this._head; - - // Add the first item - if (!current) { - listener.connect(previous); - } else { - // Go from highest to lowest priority - while (current) { - if (listener.priority > current.priority) { - listener.connect(previous); - break; - } - previous = current; - current = current.next; - } - - // Not yet connected - if (!listener.previous) { - listener.connect(previous); - } - } - - this._startIfPossible(); - - return this; - }; - - /** - * Removes any handlers matching the function and context parameters. - * If no handlers are left after removing, then it cancels the animation frame. - * - * @param {Function} fn - The listener function to be removed - * @param {Function} [context] - The listener context to be removed - * @returns {PIXI.ticker.Ticker} This instance of a ticker - */ - - - Ticker.prototype.remove = function remove(fn, context) { - var listener = this._head.next; - - while (listener) { - // We found a match, lets remove it - // no break to delete all possible matches - // incase a listener was added 2+ times - if (listener.match(fn, context)) { - listener = listener.destroy(); - } else { - listener = listener.next; - } - } - - if (!this._head.next) { - this._cancelIfNeeded(); - } - - return this; - }; - - /** - * Starts the ticker. If the ticker has listeners - * a new animation frame is requested at this point. - */ - - - Ticker.prototype.start = function start() { - if (!this.started) { - this.started = true; - this._requestIfNeeded(); - } - }; - - /** - * Stops the ticker. If the ticker has requested - * an animation frame it is canceled at this point. - */ - - - Ticker.prototype.stop = function stop() { - if (this.started) { - this.started = false; - this._cancelIfNeeded(); - } - }; - - /** - * Destroy the ticker and don't use after this. Calling - * this method removes all references to internal events. - */ - - - Ticker.prototype.destroy = function destroy() { - this.stop(); - - var listener = this._head.next; - - while (listener) { - listener = listener.destroy(true); - } - - this._head.destroy(); - this._head = null; - }; - - /** - * Triggers an update. An update entails setting the - * current {@link PIXI.ticker.Ticker#elapsedMS}, - * the current {@link PIXI.ticker.Ticker#deltaTime}, - * invoking all listeners with current deltaTime, - * and then finally setting {@link PIXI.ticker.Ticker#lastTime} - * with the value of currentTime that was provided. - * This method will be called automatically by animation - * frame callbacks if the ticker instance has been started - * and listeners are added. - * - * @param {number} [currentTime=performance.now()] - the current time of execution - */ - - - Ticker.prototype.update = function update() { - var currentTime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : performance.now(); - - var elapsedMS = void 0; - - // If the difference in time is zero or negative, we ignore most of the work done here. - // If there is no valid difference, then should be no reason to let anyone know about it. - // A zero delta, is exactly that, nothing should update. - // - // The difference in time can be negative, and no this does not mean time traveling. - // This can be the result of a race condition between when an animation frame is requested - // on the current JavaScript engine event loop, and when the ticker's start method is invoked - // (which invokes the internal _requestIfNeeded method). If a frame is requested before - // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, - // can receive a time argument that can be less than the lastTime value that was set within - // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. - // - // This check covers this browser engine timing issue, as well as if consumers pass an invalid - // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. - - if (currentTime > this.lastTime) { - // Save uncapped elapsedMS for measurement - elapsedMS = this.elapsedMS = currentTime - this.lastTime; - - // cap the milliseconds elapsed used for deltaTime - if (elapsedMS > this._maxElapsedMS) { - elapsedMS = this._maxElapsedMS; - } - - this.deltaTime = elapsedMS * _settings2.default.TARGET_FPMS * this.speed; - - // Cache a local reference, in-case ticker is destroyed - // during the emit, we can still check for head.next - var head = this._head; - - // Invoke listeners added to internal emitter - var listener = head.next; - - while (listener) { - listener = listener.emit(this.deltaTime); - } - - if (!head.next) { - this._cancelIfNeeded(); - } - } else { - this.deltaTime = this.elapsedMS = 0; - } - - this.lastTime = currentTime; - }; - - /** - * The frames per second at which this ticker is running. - * The default is approximately 60 in most modern browsers. - * **Note:** This does not factor in the value of - * {@link PIXI.ticker.Ticker#speed}, which is specific - * to scaling {@link PIXI.ticker.Ticker#deltaTime}. - * - * @member {number} - * @readonly - */ - - - _createClass(Ticker, [{ - key: 'FPS', - get: function get() { - return 1000 / this.elapsedMS; - } - - /** - * Manages the maximum amount of milliseconds allowed to - * elapse between invoking {@link PIXI.ticker.Ticker#update}. - * This value is used to cap {@link PIXI.ticker.Ticker#deltaTime}, - * but does not effect the measured value of {@link PIXI.ticker.Ticker#FPS}. - * When setting this property it is clamped to a value between - * `0` and `PIXI.settings.TARGET_FPMS * 1000`. - * - * @member {number} - * @default 10 - */ - - }, { - key: 'minFPS', - get: function get() { - return 1000 / this._maxElapsedMS; - }, - set: function set(fps) // eslint-disable-line require-jsdoc - { - // Clamp: 0 to TARGET_FPMS - var minFPMS = Math.min(Math.max(0, fps) / 1000, _settings2.default.TARGET_FPMS); - - this._maxElapsedMS = 1 / minFPMS; - } - }]); - - return Ticker; -}(); - -exports.default = Ticker; - -},{"../const":46,"../settings":101,"./TickerListener":119}],119:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * Internal class for handling the priority sorting of ticker handlers. - * - * @private - * @class - * @memberof PIXI.ticker - */ -var TickerListener = function () { - /** - * Constructor - * - * @param {Function} fn - The listener function to be added for one update - * @param {Function} [context=null] - The listener context - * @param {number} [priority=0] - The priority for emitting - * @param {boolean} [once=false] - If the handler should fire once - */ - function TickerListener(fn) { - var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; - var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; - var once = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - - _classCallCheck(this, TickerListener); - - /** - * The handler function to execute. - * @member {Function} - */ - this.fn = fn; - - /** - * The calling to execute. - * @member {Function} - */ - this.context = context; - - /** - * The current priority. - * @member {number} - */ - this.priority = priority; - - /** - * If this should only execute once. - * @member {boolean} - */ - this.once = once; - - /** - * The next item in chain. - * @member {TickerListener} - */ - this.next = null; - - /** - * The previous item in chain. - * @member {TickerListener} - */ - this.previous = null; - - /** - * `true` if this listener has been destroyed already. - * @member {boolean} - * @private - */ - this._destroyed = false; - } - - /** - * Simple compare function to figure out if a function and context match. - * - * @param {Function} fn - The listener function to be added for one update - * @param {Function} context - The listener context - * @return {boolean} `true` if the listener match the arguments - */ - - - TickerListener.prototype.match = function match(fn, context) { - context = context || null; - - return this.fn === fn && this.context === context; - }; - - /** - * Emit by calling the current function. - * @param {number} deltaTime - time since the last emit. - * @return {TickerListener} Next ticker - */ - - - TickerListener.prototype.emit = function emit(deltaTime) { - if (this.fn) { - if (this.context) { - this.fn.call(this.context, deltaTime); - } else { - this.fn(deltaTime); - } - } - - var redirect = this.next; - - if (this.once) { - this.destroy(true); - } - - // Soft-destroying should remove - // the next reference - if (this._destroyed) { - this.next = null; - } - - return redirect; - }; - - /** - * Connect to the list. - * @param {TickerListener} previous - Input node, previous listener - */ - - - TickerListener.prototype.connect = function connect(previous) { - this.previous = previous; - if (previous.next) { - previous.next.previous = this; - } - this.next = previous.next; - previous.next = this; - }; - - /** - * Destroy and don't use after this. - * @param {boolean} [hard = false] `true` to remove the `next` reference, this - * is considered a hard destroy. Soft destroy maintains the next reference. - * @return {TickerListener} The listener to redirect while emitting or removing. - */ - - - TickerListener.prototype.destroy = function destroy() { - var hard = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - - this._destroyed = true; - this.fn = null; - this.context = null; - - // Disconnect, hook up next and previous - if (this.previous) { - this.previous.next = this.next; - } - - if (this.next) { - this.next.previous = this.previous; - } - - // Redirect to the next item - var redirect = this.previous; - - // Remove references - this.next = hard ? null : redirect; - this.previous = null; - - return redirect; - }; - - return TickerListener; -}(); - -exports.default = TickerListener; - -},{}],120:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.Ticker = exports.shared = undefined; - -var _Ticker = require('./Ticker'); - -var _Ticker2 = _interopRequireDefault(_Ticker); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The shared ticker instance used by {@link PIXI.extras.AnimatedSprite}. - * and by {@link PIXI.interaction.InteractionManager}. - * The property {@link PIXI.ticker.Ticker#autoStart} is set to `true` - * for this instance. Please follow the examples for usage, including - * how to opt-out of auto-starting the shared ticker. - * - * @example - * let ticker = PIXI.ticker.shared; - * // Set this to prevent starting this ticker when listeners are added. - * // By default this is true only for the PIXI.ticker.shared instance. - * ticker.autoStart = false; - * // FYI, call this to ensure the ticker is stopped. It should be stopped - * // if you have not attempted to render anything yet. - * ticker.stop(); - * // Call this when you are ready for a running shared ticker. - * ticker.start(); - * - * @example - * // You may use the shared ticker to render... - * let renderer = PIXI.autoDetectRenderer(800, 600); - * let stage = new PIXI.Container(); - * let interactionManager = PIXI.interaction.InteractionManager(renderer); - * document.body.appendChild(renderer.view); - * ticker.add(function (time) { - * renderer.render(stage); - * }); - * - * @example - * // Or you can just update it manually. - * ticker.autoStart = false; - * ticker.stop(); - * function animate(time) { - * ticker.update(time); - * renderer.render(stage); - * requestAnimationFrame(animate); - * } - * animate(performance.now()); - * - * @type {PIXI.ticker.Ticker} - * @memberof PIXI.ticker - */ -var shared = new _Ticker2.default(); - -shared.autoStart = true; -shared.destroy = function () { - // protect destroying shared ticker - // this is used by other internal systems - // like AnimatedSprite and InteractionManager -}; - -/** - * This namespace contains an API for interacting with PIXI's internal global update loop. - * - * This ticker is used for rendering, {@link PIXI.extras.AnimatedSprite AnimatedSprite}, - * {@link PIXI.interaction.InteractionManager InteractionManager} and many other time-based PIXI systems. - * @example - * const ticker = new PIXI.ticker.Ticker(); - * ticker.stop(); - * ticker.add((deltaTime) => { - * // do something every frame - * }); - * ticker.start(); - * @namespace PIXI.ticker - */ -exports.shared = shared; -exports.Ticker = _Ticker2.default; - -},{"./Ticker":118}],121:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.default = canUploadSameBuffer; -function canUploadSameBuffer() { - // Uploading the same buffer multiple times in a single frame can cause perf issues. - // Apparent on IOS so only check for that at the moment - // this check may become more complex if this issue pops up elsewhere. - var ios = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform); - - return !ios; -} - -},{}],122:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.default = createIndicesForQuads; -/** - * Generic Mask Stack data structure - * - * @memberof PIXI - * @function createIndicesForQuads - * @private - * @param {number} size - Number of quads - * @return {Uint16Array} indices - */ -function createIndicesForQuads(size) { - // the total number of indices in our array, there are 6 points per quad. - - var totalIndices = size * 6; - - var indices = new Uint16Array(totalIndices); - - // fill the indices with the quads to draw - for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { - indices[i + 0] = j + 0; - indices[i + 1] = j + 1; - indices[i + 2] = j + 2; - indices[i + 3] = j + 0; - indices[i + 4] = j + 2; - indices[i + 5] = j + 3; - } - - return indices; -} - -},{}],123:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.default = determineCrossOrigin; - -var _url2 = require('url'); - -var _url3 = _interopRequireDefault(_url2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var tempAnchor = void 0; - -/** - * Sets the `crossOrigin` property for this resource based on if the url - * for this resource is cross-origin. If crossOrigin was manually set, this - * function does nothing. - * Nipped from the resource loader! - * - * @ignore - * @param {string} url - The url to test. - * @param {object} [loc=window.location] - The location object to test against. - * @return {string} The crossOrigin value to use (or empty string for none). - */ -function determineCrossOrigin(url) { - var loc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.location; - - // data: and javascript: urls are considered same-origin - if (url.indexOf('data:') === 0) { - return ''; - } - - // default is window.location - loc = loc || window.location; - - if (!tempAnchor) { - tempAnchor = document.createElement('a'); - } - - // let the browser determine the full href for the url of this resource and then - // parse with the node url lib, we can't use the properties of the anchor element - // because they don't work in IE9 :( - tempAnchor.href = url; - url = _url3.default.parse(tempAnchor.href); - - var samePort = !url.port && loc.port === '' || url.port === loc.port; - - // if cross origin - if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { - return 'anonymous'; - } - - return ''; -} - -},{"url":29}],124:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.premultiplyBlendMode = exports.BaseTextureCache = exports.TextureCache = exports.mixins = exports.pluginTarget = exports.EventEmitter = exports.removeItems = exports.isMobile = undefined; -exports.uid = uid; -exports.hex2rgb = hex2rgb; -exports.hex2string = hex2string; -exports.rgb2hex = rgb2hex; -exports.getResolutionOfUrl = getResolutionOfUrl; -exports.decomposeDataUri = decomposeDataUri; -exports.getUrlFileExtension = getUrlFileExtension; -exports.getSvgSize = getSvgSize; -exports.skipHello = skipHello; -exports.sayHello = sayHello; -exports.isWebGLSupported = isWebGLSupported; -exports.sign = sign; -exports.destroyTextureCache = destroyTextureCache; -exports.clearTextureCache = clearTextureCache; -exports.correctBlendMode = correctBlendMode; -exports.premultiplyTint = premultiplyTint; -exports.premultiplyRgba = premultiplyRgba; -exports.premultiplyTintToRgba = premultiplyTintToRgba; - -var _const = require('../const'); - -var _settings = require('../settings'); - -var _settings2 = _interopRequireDefault(_settings); - -var _eventemitter = require('eventemitter3'); - -var _eventemitter2 = _interopRequireDefault(_eventemitter); - -var _pluginTarget = require('./pluginTarget'); - -var _pluginTarget2 = _interopRequireDefault(_pluginTarget); - -var _mixin = require('./mixin'); - -var mixins = _interopRequireWildcard(_mixin); - -var _ismobilejs = require('ismobilejs'); - -var isMobile = _interopRequireWildcard(_ismobilejs); - -var _removeArrayItems = require('remove-array-items'); - -var _removeArrayItems2 = _interopRequireDefault(_removeArrayItems); - -var _mapPremultipliedBlendModes = require('./mapPremultipliedBlendModes'); - -var _mapPremultipliedBlendModes2 = _interopRequireDefault(_mapPremultipliedBlendModes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var nextUid = 0; -var saidHello = false; - -/** - * Generalized convenience utilities for PIXI. - * @example - * // Extend PIXI's internal Event Emitter. - * class MyEmitter extends PIXI.utils.EventEmitter { - * constructor() { - * super(); - * console.log("Emitter created!"); - * } - * } - * - * // Get info on current device - * console.log(PIXI.utils.isMobile); - * - * // Convert hex color to string - * console.log(PIXI.utils.hex2string(0xff00ff)); // returns: "#ff00ff" - * @namespace PIXI.utils - */ -exports.isMobile = isMobile; -exports.removeItems = _removeArrayItems2.default; -exports.EventEmitter = _eventemitter2.default; -exports.pluginTarget = _pluginTarget2.default; -exports.mixins = mixins; - -/** - * Gets the next unique identifier - * - * @memberof PIXI.utils - * @function uid - * @return {number} The next unique identifier to use. - */ - -function uid() { - return ++nextUid; -} - -/** - * Converts a hex color number to an [R, G, B] array - * - * @memberof PIXI.utils - * @function hex2rgb - * @param {number} hex - The number to convert - * @param {number[]} [out=[]] If supplied, this array will be used rather than returning a new one - * @return {number[]} An array representing the [R, G, B] of the color. - */ -function hex2rgb(hex, out) { - out = out || []; - - out[0] = (hex >> 16 & 0xFF) / 255; - out[1] = (hex >> 8 & 0xFF) / 255; - out[2] = (hex & 0xFF) / 255; - - return out; -} - -/** - * Converts a hex color number to a string. - * - * @memberof PIXI.utils - * @function hex2string - * @param {number} hex - Number in hex - * @return {string} The string color. - */ -function hex2string(hex) { - hex = hex.toString(16); - hex = '000000'.substr(0, 6 - hex.length) + hex; - - return '#' + hex; -} - -/** - * Converts a color as an [R, G, B] array to a hex number - * - * @memberof PIXI.utils - * @function rgb2hex - * @param {number[]} rgb - rgb array - * @return {number} The color number - */ -function rgb2hex(rgb) { - return (rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + (rgb[2] * 255 | 0); -} - -/** - * get the resolution / device pixel ratio of an asset by looking for the prefix - * used by spritesheets and image urls - * - * @memberof PIXI.utils - * @function getResolutionOfUrl - * @param {string} url - the image path - * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. - * @return {number} resolution / device pixel ratio of an asset - */ -function getResolutionOfUrl(url, defaultValue) { - var resolution = _settings2.default.RETINA_PREFIX.exec(url); - - if (resolution) { - return parseFloat(resolution[1]); - } - - return defaultValue !== undefined ? defaultValue : 1; -} - -/** - * Typedef for decomposeDataUri return object. - * - * @typedef {object} DecomposedDataUri - * @property {mediaType} Media type, eg. `image` - * @property {subType} Sub type, eg. `png` - * @property {encoding} Data encoding, eg. `base64` - * @property {data} The actual data - */ - -/** - * Split a data URI into components. Returns undefined if - * parameter `dataUri` is not a valid data URI. - * - * @memberof PIXI.utils - * @function decomposeDataUri - * @param {string} dataUri - the data URI to check - * @return {DecomposedDataUri|undefined} The decomposed data uri or undefined - */ -function decomposeDataUri(dataUri) { - var dataUriMatch = _const.DATA_URI.exec(dataUri); - - if (dataUriMatch) { - return { - mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, - subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, - encoding: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, - data: dataUriMatch[4] - }; - } - - return undefined; -} - -/** - * Get type of the image by regexp for extension. Returns undefined for unknown extensions. - * - * @memberof PIXI.utils - * @function getUrlFileExtension - * @param {string} url - the image path - * @return {string|undefined} image extension - */ -function getUrlFileExtension(url) { - var extension = _const.URL_FILE_EXTENSION.exec(url); - - if (extension) { - return extension[1].toLowerCase(); - } - - return undefined; -} - -/** - * Typedef for Size object. - * - * @typedef {object} Size - * @property {width} Width component - * @property {height} Height component - */ - -/** - * Get size from an svg string using regexp. - * - * @memberof PIXI.utils - * @function getSvgSize - * @param {string} svgString - a serialized svg element - * @return {Size|undefined} image extension - */ -function getSvgSize(svgString) { - var sizeMatch = _const.SVG_SIZE.exec(svgString); - var size = {}; - - if (sizeMatch) { - size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3])); - size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7])); - } - - return size; -} - -/** - * Skips the hello message of renderers that are created after this is run. - * - * @function skipHello - * @memberof PIXI.utils - */ -function skipHello() { - saidHello = true; -} - -/** - * Logs out the version and renderer information for this running instance of PIXI. - * If you don't want to see this message you can run `PIXI.utils.skipHello()` before - * creating your renderer. Keep in mind that doing that will forever makes you a jerk face. - * - * @static - * @function sayHello - * @memberof PIXI.utils - * @param {string} type - The string renderer type to log. - */ -function sayHello(type) { - if (saidHello) { - return; - } - - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { - var args = ['\n %c %c %c PixiJS ' + _const.VERSION + ' - \u2730 ' + type + ' \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n', 'background: #ff66a5; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff66a5; background: #030307; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'background: #ffc3dc; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;']; - - window.console.log.apply(console, args); - } else if (window.console) { - window.console.log('PixiJS ' + _const.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); - } - - saidHello = true; -} - -/** - * Helper for checking for webgl support - * - * @memberof PIXI.utils - * @function isWebGLSupported - * @return {boolean} is webgl supported - */ -function isWebGLSupported() { - var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true }; - - try { - if (!window.WebGLRenderingContext) { - return false; - } - - var canvas = document.createElement('canvas'); - var gl = canvas.getContext('webgl', contextOptions) || canvas.getContext('experimental-webgl', contextOptions); - - var success = !!(gl && gl.getContextAttributes().stencil); - - if (gl) { - var loseContext = gl.getExtension('WEBGL_lose_context'); - - if (loseContext) { - loseContext.loseContext(); - } - } - - gl = null; - - return success; - } catch (e) { - return false; - } -} - -/** - * Returns sign of number - * - * @memberof PIXI.utils - * @function sign - * @param {number} n - the number to check the sign of - * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive - */ -function sign(n) { - if (n === 0) return 0; - - return n < 0 ? -1 : 1; -} - -/** - * @todo Describe property usage - * - * @memberof PIXI.utils - * @private - */ -var TextureCache = exports.TextureCache = Object.create(null); - -/** - * @todo Describe property usage - * - * @memberof PIXI.utils - * @private - */ -var BaseTextureCache = exports.BaseTextureCache = Object.create(null); - -/** - * Destroys all texture in the cache - * - * @memberof PIXI.utils - * @function destroyTextureCache - */ -function destroyTextureCache() { - var key = void 0; - - for (key in TextureCache) { - TextureCache[key].destroy(); - } - for (key in BaseTextureCache) { - BaseTextureCache[key].destroy(); - } -} - -/** - * Removes all textures from cache, but does not destroy them - * - * @memberof PIXI.utils - * @function clearTextureCache - */ -function clearTextureCache() { - var key = void 0; - - for (key in TextureCache) { - delete TextureCache[key]; - } - for (key in BaseTextureCache) { - delete BaseTextureCache[key]; - } -} - -/** - * maps premultiply flag and blendMode to adjusted blendMode - * @memberof PIXI.utils - * @const premultiplyBlendMode - * @type {Array} - */ -var premultiplyBlendMode = exports.premultiplyBlendMode = (0, _mapPremultipliedBlendModes2.default)(); - -/** - * changes blendMode according to texture format - * - * @memberof PIXI.utils - * @function correctBlendMode - * @param {number} blendMode supposed blend mode - * @param {boolean} premultiplied whether source is premultiplied - * @returns {number} true blend mode for this texture - */ -function correctBlendMode(blendMode, premultiplied) { - return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode]; -} - -/** - * premultiplies tint - * - * @param {number} tint integet RGB - * @param {number} alpha floating point alpha (0.0-1.0) - * @returns {number} tint multiplied by alpha - */ -function premultiplyTint(tint, alpha) { - if (alpha === 1.0) { - return (alpha * 255 << 24) + tint; - } - if (alpha === 0.0) { - return 0; - } - var R = tint >> 16 & 0xFF; - var G = tint >> 8 & 0xFF; - var B = tint & 0xFF; - - R = R * alpha + 0.5 | 0; - G = G * alpha + 0.5 | 0; - B = B * alpha + 0.5 | 0; - - return (alpha * 255 << 24) + (R << 16) + (G << 8) + B; -} - -/** - * combines rgb and alpha to out array - * - * @param {Float32Array|number[]} rgb input rgb - * @param {number} alpha alpha param - * @param {Float32Array} [out] output - * @param {boolean} [premultiply=true] do premultiply it - * @returns {Float32Array} vec4 rgba - */ -function premultiplyRgba(rgb, alpha, out, premultiply) { - out = out || new Float32Array(4); - if (premultiply || premultiply === undefined) { - out[0] = rgb[0] * alpha; - out[1] = rgb[1] * alpha; - out[2] = rgb[2] * alpha; - } else { - out[0] = rgb[0]; - out[1] = rgb[1]; - out[2] = rgb[2]; - } - out[3] = alpha; - - return out; -} - -/** - * converts integer tint and float alpha to vec4 form, premultiplies by default - * - * @param {number} tint input tint - * @param {number} alpha alpha param - * @param {Float32Array} [out] output - * @param {boolean} [premultiply=true] do premultiply it - * @returns {Float32Array} vec4 rgba - */ -function premultiplyTintToRgba(tint, alpha, out, premultiply) { - out = out || new Float32Array(4); - out[0] = (tint >> 16 & 0xFF) / 255.0; - out[1] = (tint >> 8 & 0xFF) / 255.0; - out[2] = (tint & 0xFF) / 255.0; - if (premultiply || premultiply === undefined) { - out[0] *= alpha; - out[1] *= alpha; - out[2] *= alpha; - } - out[3] = alpha; - - return out; -} - -},{"../const":46,"../settings":101,"./mapPremultipliedBlendModes":125,"./mixin":127,"./pluginTarget":128,"eventemitter3":3,"ismobilejs":4,"remove-array-items":31}],125:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.default = mapPremultipliedBlendModes; - -var _const = require('../const'); - -/** - * Corrects PixiJS blend, takes premultiplied alpha into account - * - * @memberof PIXI - * @function mapPremultipliedBlendModes - * @private - * @param {Array} [array] - The array to output into. - * @return {Array} Mapped modes. - */ - -function mapPremultipliedBlendModes() { - var pm = []; - var npm = []; - - for (var i = 0; i < 32; i++) { - pm[i] = i; - npm[i] = i; - } - - pm[_const.BLEND_MODES.NORMAL_NPM] = _const.BLEND_MODES.NORMAL; - pm[_const.BLEND_MODES.ADD_NPM] = _const.BLEND_MODES.ADD; - pm[_const.BLEND_MODES.SCREEN_NPM] = _const.BLEND_MODES.SCREEN; - - npm[_const.BLEND_MODES.NORMAL] = _const.BLEND_MODES.NORMAL_NPM; - npm[_const.BLEND_MODES.ADD] = _const.BLEND_MODES.ADD_NPM; - npm[_const.BLEND_MODES.SCREEN] = _const.BLEND_MODES.SCREEN_NPM; - - var array = []; - - array.push(npm); - array.push(pm); - - return array; -} - -},{"../const":46}],126:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.default = maxRecommendedTextures; - -var _ismobilejs = require('ismobilejs'); - -var _ismobilejs2 = _interopRequireDefault(_ismobilejs); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function maxRecommendedTextures(max) { - if (_ismobilejs2.default.tablet || _ismobilejs2.default.phone) { - // check if the res is iphone 6 or higher.. - return 4; - } - - // desktop should be ok - return max; -} - -},{"ismobilejs":4}],127:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.mixin = mixin; -exports.delayMixin = delayMixin; -exports.performMixins = performMixins; -/** - * Mixes all enumerable properties and methods from a source object to a target object. - * - * @memberof PIXI.utils.mixins - * @function mixin - * @param {object} target The prototype or instance that properties and methods should be added to. - * @param {object} source The source of properties and methods to mix in. - */ -function mixin(target, source) { - if (!target || !source) return; - // in ES8/ES2017, this would be really easy: - // Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - - // get all the enumerable property keys - var keys = Object.keys(source); - - // loop through properties - for (var i = 0; i < keys.length; ++i) { - var propertyName = keys[i]; - - // Set the property using the property descriptor - this works for accessors and normal value properties - Object.defineProperty(target, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); - } -} - -var mixins = []; - -/** - * Queues a mixin to be handled towards the end of the initialization of PIXI, so that deprecation - * can take effect. - * - * @memberof PIXI.utils.mixins - * @function delayMixin - * @private - * @param {object} target The prototype or instance that properties and methods should be added to. - * @param {object} source The source of properties and methods to mix in. - */ -function delayMixin(target, source) { - mixins.push(target, source); -} - -/** - * Handles all mixins queued via delayMixin(). - * - * @memberof PIXI.utils.mixins - * @function performMixins - * @private - */ -function performMixins() { - for (var i = 0; i < mixins.length; i += 2) { - mixin(mixins[i], mixins[i + 1]); - } - mixins.length = 0; -} - -},{}],128:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -/** - * Mixins functionality to make an object have "plugins". - * - * @example - * function MyObject() {} - * - * pluginTarget.mixin(MyObject); - * - * @mixin - * @memberof PIXI.utils - * @param {object} obj - The object to mix into. - */ -function pluginTarget(obj) { - obj.__plugins = {}; - - /** - * Adds a plugin to an object - * - * @param {string} pluginName - The events that should be listed. - * @param {Function} ctor - The constructor function for the plugin. - */ - obj.registerPlugin = function registerPlugin(pluginName, ctor) { - obj.__plugins[pluginName] = ctor; - }; - - /** - * Instantiates all the plugins of this object - * - */ - obj.prototype.initPlugins = function initPlugins() { - this.plugins = this.plugins || {}; - - for (var o in obj.__plugins) { - this.plugins[o] = new obj.__plugins[o](this); - } - }; - - /** - * Removes all the plugins of this object - * - */ - obj.prototype.destroyPlugins = function destroyPlugins() { - for (var o in this.plugins) { - this.plugins[o].destroy(); - this.plugins[o] = null; - } - - this.plugins = null; - }; -} - -exports.default = { - /** - * Mixes in the properties of the pluginTarget into another object - * - * @param {object} obj - The obj to mix into - */ - mixin: function mixin(obj) { - pluginTarget(obj); - } -}; - -},{}],129:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.default = trimCanvas; -/** - * Trim transparent borders from a canvas - * - * @memberof PIXI - * @function trimCanvas - * @private - * @param {HTMLCanvasElement} canvas - the canvas to trim - * @returns {object} Trim data - */ -function trimCanvas(canvas) { - // https://gist.github.com/remy/784508 - - var width = canvas.width; - var height = canvas.height; - - var context = canvas.getContext('2d'); - var imageData = context.getImageData(0, 0, width, height); - var pixels = imageData.data; - var len = pixels.length; - - var bound = { - top: null, - left: null, - right: null, - bottom: null - }; - var i = void 0; - var x = void 0; - var y = void 0; - - for (i = 0; i < len; i += 4) { - if (pixels[i + 3] !== 0) { - x = i / 4 % width; - y = ~~(i / 4 / width); - - if (bound.top === null) { - bound.top = y; - } - - if (bound.left === null) { - bound.left = x; - } else if (x < bound.left) { - bound.left = x; - } - - if (bound.right === null) { - bound.right = x + 1; - } else if (bound.right < x) { - bound.right = x + 1; - } - - if (bound.bottom === null) { - bound.bottom = y; - } else if (bound.bottom < y) { - bound.bottom = y; - } - } - } - - width = bound.right - bound.left; - height = bound.bottom - bound.top + 1; - - var data = context.getImageData(bound.left, bound.top, width, height); - - return { - height: height, - width: width, - data: data - }; -} - -},{}],130:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.default = deprecation; -// provide method to give a stack track for warnings -// useful for tracking-down where deprecated methods/properties/classes -// are being used within the code -function warn(msg) { - /* eslint-disable no-console */ - var stack = new Error().stack; - - // Handle IE < 10 and Safari < 6 - if (typeof stack === 'undefined') { - console.warn('Deprecation Warning: ', msg); - } else { - // chop off the stack trace which includes pixi.js internal calls - stack = stack.split('\n').splice(3).join('\n'); - - if (console.groupCollapsed) { - console.groupCollapsed('%cDeprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', msg); - console.warn(stack); - console.groupEnd(); - } else { - console.warn('Deprecation Warning: ', msg); - console.warn(stack); - } - } - /* eslint-enable no-console */ -} - -function deprecation(core) { - var mesh = core.mesh, - particles = core.particles, - extras = core.extras, - filters = core.filters, - prepare = core.prepare, - loaders = core.loaders, - interaction = core.interaction; - - - Object.defineProperties(core, { - - /** - * @class - * @private - * @name SpriteBatch - * @memberof PIXI - * @see PIXI.ParticleContainer - * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. - * @deprecated since version 3.0.0 - */ - SpriteBatch: { - get: function get() { - throw new ReferenceError('SpriteBatch does not exist any more, ' + 'please use the new ParticleContainer instead.'); - } - }, - - /** - * @class - * @private - * @name AssetLoader - * @memberof PIXI - * @see PIXI.loaders.Loader - * @throws {ReferenceError} The loader system was overhauled in PixiJS v3, - * please see the new PIXI.loaders.Loader class. - * @deprecated since version 3.0.0 - */ - AssetLoader: { - get: function get() { - throw new ReferenceError('The loader system was overhauled in PixiJS v3, ' + 'please see the new PIXI.loaders.Loader class.'); - } - }, - - /** - * @class - * @private - * @name Stage - * @memberof PIXI - * @see PIXI.Container - * @deprecated since version 3.0.0 - */ - Stage: { - get: function get() { - warn('You do not need to use a PIXI Stage any more, you can simply render any container.'); - - return core.Container; - } - }, - - /** - * @class - * @private - * @name DisplayObjectContainer - * @memberof PIXI - * @see PIXI.Container - * @deprecated since version 3.0.0 - */ - DisplayObjectContainer: { - get: function get() { - warn('DisplayObjectContainer has been shortened to Container, please use Container from now on.'); - - return core.Container; - } - }, - - /** - * @class - * @private - * @name Strip - * @memberof PIXI - * @see PIXI.mesh.Mesh - * @deprecated since version 3.0.0 - */ - Strip: { - get: function get() { - warn('The Strip class has been renamed to Mesh and moved to mesh.Mesh, please use mesh.Mesh from now on.'); - - return mesh.Mesh; - } - }, - - /** - * @class - * @private - * @name Rope - * @memberof PIXI - * @see PIXI.mesh.Rope - * @deprecated since version 3.0.0 - */ - Rope: { - get: function get() { - warn('The Rope class has been moved to mesh.Rope, please use mesh.Rope from now on.'); - - return mesh.Rope; - } - }, - - /** - * @class - * @private - * @name ParticleContainer - * @memberof PIXI - * @see PIXI.particles.ParticleContainer - * @deprecated since version 4.0.0 - */ - ParticleContainer: { - get: function get() { - warn('The ParticleContainer class has been moved to particles.ParticleContainer, ' + 'please use particles.ParticleContainer from now on.'); - - return particles.ParticleContainer; - } - }, - - /** - * @class - * @private - * @name MovieClip - * @memberof PIXI - * @see PIXI.extras.MovieClip - * @deprecated since version 3.0.0 - */ - MovieClip: { - get: function get() { - warn('The MovieClip class has been moved to extras.AnimatedSprite, please use extras.AnimatedSprite.'); - - return extras.AnimatedSprite; - } - }, - - /** - * @class - * @private - * @name TilingSprite - * @memberof PIXI - * @see PIXI.extras.TilingSprite - * @deprecated since version 3.0.0 - */ - TilingSprite: { - get: function get() { - warn('The TilingSprite class has been moved to extras.TilingSprite, ' + 'please use extras.TilingSprite from now on.'); - - return extras.TilingSprite; - } - }, - - /** - * @class - * @private - * @name BitmapText - * @memberof PIXI - * @see PIXI.extras.BitmapText - * @deprecated since version 3.0.0 - */ - BitmapText: { - get: function get() { - warn('The BitmapText class has been moved to extras.BitmapText, ' + 'please use extras.BitmapText from now on.'); - - return extras.BitmapText; - } - }, - - /** - * @class - * @private - * @name blendModes - * @memberof PIXI - * @see PIXI.BLEND_MODES - * @deprecated since version 3.0.0 - */ - blendModes: { - get: function get() { - warn('The blendModes has been moved to BLEND_MODES, please use BLEND_MODES from now on.'); - - return core.BLEND_MODES; - } - }, - - /** - * @class - * @private - * @name scaleModes - * @memberof PIXI - * @see PIXI.SCALE_MODES - * @deprecated since version 3.0.0 - */ - scaleModes: { - get: function get() { - warn('The scaleModes has been moved to SCALE_MODES, please use SCALE_MODES from now on.'); - - return core.SCALE_MODES; - } - }, - - /** - * @class - * @private - * @name BaseTextureCache - * @memberof PIXI - * @see PIXI.utils.BaseTextureCache - * @deprecated since version 3.0.0 - */ - BaseTextureCache: { - get: function get() { - warn('The BaseTextureCache class has been moved to utils.BaseTextureCache, ' + 'please use utils.BaseTextureCache from now on.'); - - return core.utils.BaseTextureCache; - } - }, - - /** - * @class - * @private - * @name TextureCache - * @memberof PIXI - * @see PIXI.utils.TextureCache - * @deprecated since version 3.0.0 - */ - TextureCache: { - get: function get() { - warn('The TextureCache class has been moved to utils.TextureCache, ' + 'please use utils.TextureCache from now on.'); - - return core.utils.TextureCache; - } - }, - - /** - * @namespace - * @private - * @name math - * @memberof PIXI - * @see PIXI - * @deprecated since version 3.0.6 - */ - math: { - get: function get() { - warn('The math namespace is deprecated, please access members already accessible on PIXI.'); - - return core; - } - }, - - /** - * @class - * @private - * @name PIXI.AbstractFilter - * @see PIXI.Filter - * @deprecated since version 3.0.6 - */ - AbstractFilter: { - get: function get() { - warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); - - return core.Filter; - } - }, - - /** - * @class - * @private - * @name PIXI.TransformManual - * @see PIXI.TransformBase - * @deprecated since version 4.0.0 - */ - TransformManual: { - get: function get() { - warn('TransformManual has been renamed to TransformBase, please update your pixi-spine'); - - return core.TransformBase; - } - }, - - /** - * @static - * @constant - * @name PIXI.TARGET_FPMS - * @see PIXI.settings.TARGET_FPMS - * @deprecated since version 4.2.0 - */ - TARGET_FPMS: { - get: function get() { - warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); - - return core.settings.TARGET_FPMS; - }, - set: function set(value) { - warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); - - core.settings.TARGET_FPMS = value; - } - }, - - /** - * @static - * @constant - * @name PIXI.FILTER_RESOLUTION - * @see PIXI.settings.FILTER_RESOLUTION - * @deprecated since version 4.2.0 - */ - FILTER_RESOLUTION: { - get: function get() { - warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); - - return core.settings.FILTER_RESOLUTION; - }, - set: function set(value) { - warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); - - core.settings.FILTER_RESOLUTION = value; - } - }, - - /** - * @static - * @constant - * @name PIXI.RESOLUTION - * @see PIXI.settings.RESOLUTION - * @deprecated since version 4.2.0 - */ - RESOLUTION: { - get: function get() { - warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); - - return core.settings.RESOLUTION; - }, - set: function set(value) { - warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); - - core.settings.RESOLUTION = value; - } - }, - - /** - * @static - * @constant - * @name PIXI.MIPMAP_TEXTURES - * @see PIXI.settings.MIPMAP_TEXTURES - * @deprecated since version 4.2.0 - */ - MIPMAP_TEXTURES: { - get: function get() { - warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); - - return core.settings.MIPMAP_TEXTURES; - }, - set: function set(value) { - warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); - - core.settings.MIPMAP_TEXTURES = value; - } - }, - - /** - * @static - * @constant - * @name PIXI.SPRITE_BATCH_SIZE - * @see PIXI.settings.SPRITE_BATCH_SIZE - * @deprecated since version 4.2.0 - */ - SPRITE_BATCH_SIZE: { - get: function get() { - warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); - - return core.settings.SPRITE_BATCH_SIZE; - }, - set: function set(value) { - warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); - - core.settings.SPRITE_BATCH_SIZE = value; - } - }, - - /** - * @static - * @constant - * @name PIXI.SPRITE_MAX_TEXTURES - * @see PIXI.settings.SPRITE_MAX_TEXTURES - * @deprecated since version 4.2.0 - */ - SPRITE_MAX_TEXTURES: { - get: function get() { - warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); - - return core.settings.SPRITE_MAX_TEXTURES; - }, - set: function set(value) { - warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); - - core.settings.SPRITE_MAX_TEXTURES = value; - } - }, - - /** - * @static - * @constant - * @name PIXI.RETINA_PREFIX - * @see PIXI.settings.RETINA_PREFIX - * @deprecated since version 4.2.0 - */ - RETINA_PREFIX: { - get: function get() { - warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); - - return core.settings.RETINA_PREFIX; - }, - set: function set(value) { - warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); - - core.settings.RETINA_PREFIX = value; - } - }, - - /** - * @static - * @constant - * @name PIXI.DEFAULT_RENDER_OPTIONS - * @see PIXI.settings.RENDER_OPTIONS - * @deprecated since version 4.2.0 - */ - DEFAULT_RENDER_OPTIONS: { - get: function get() { - warn('PIXI.DEFAULT_RENDER_OPTIONS has been deprecated, please use PIXI.settings.DEFAULT_RENDER_OPTIONS'); - - return core.settings.RENDER_OPTIONS; - } - } - }); - - // Move the default properties to settings - var defaults = [{ parent: 'TRANSFORM_MODE', target: 'TRANSFORM_MODE' }, { parent: 'GC_MODES', target: 'GC_MODE' }, { parent: 'WRAP_MODES', target: 'WRAP_MODE' }, { parent: 'SCALE_MODES', target: 'SCALE_MODE' }, { parent: 'PRECISION', target: 'PRECISION_FRAGMENT' }]; - - var _loop = function _loop(i) { - var deprecation = defaults[i]; - - Object.defineProperty(core[deprecation.parent], 'DEFAULT', { - get: function get() { - warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, ' + ('please use PIXI.settings.' + deprecation.target)); - - return core.settings[deprecation.target]; - }, - set: function set(value) { - warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, ' + ('please use PIXI.settings.' + deprecation.target)); - - core.settings[deprecation.target] = value; - } - }); - }; - - for (var i = 0; i < defaults.length; i++) { - _loop(i); - } - - Object.defineProperties(core.settings, { - - /** - * @static - * @name PRECISION - * @memberof PIXI.settings - * @see PIXI.PRECISION - * @deprecated since version 4.4.0 - */ - PRECISION: { - get: function get() { - warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); - - return core.settings.PRECISION_FRAGMENT; - }, - set: function set(value) { - warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); - - core.settings.PRECISION_FRAGMENT = value; - } - } - }); - - if (extras.AnimatedSprite) { - Object.defineProperties(extras, { - - /** - * @class - * @name MovieClip - * @memberof PIXI.extras - * @see PIXI.extras.AnimatedSprite - * @deprecated since version 4.2.0 - */ - MovieClip: { - get: function get() { - warn('The MovieClip class has been renamed to AnimatedSprite, please use AnimatedSprite from now on.'); - - return extras.AnimatedSprite; - } - } - }); - } - - core.DisplayObject.prototype.generateTexture = function generateTexture(renderer, scaleMode, resolution) { - warn('generateTexture has moved to the renderer, please use renderer.generateTexture(displayObject)'); - - return renderer.generateTexture(this, scaleMode, resolution); - }; - - core.Graphics.prototype.generateTexture = function generateTexture(scaleMode, resolution) { - warn('graphics generate texture has moved to the renderer. ' + 'Or to render a graphics to a texture using canvas please use generateCanvasTexture'); - - return this.generateCanvasTexture(scaleMode, resolution); - }; - - core.RenderTexture.prototype.render = function render(displayObject, matrix, clear, updateTransform) { - this.legacyRenderer.render(displayObject, this, clear, matrix, !updateTransform); - warn('RenderTexture.render is now deprecated, please use renderer.render(displayObject, renderTexture)'); - }; - - core.RenderTexture.prototype.getImage = function getImage(target) { - warn('RenderTexture.getImage is now deprecated, please use renderer.extract.image(target)'); - - return this.legacyRenderer.extract.image(target); - }; - - core.RenderTexture.prototype.getBase64 = function getBase64(target) { - warn('RenderTexture.getBase64 is now deprecated, please use renderer.extract.base64(target)'); - - return this.legacyRenderer.extract.base64(target); - }; - - core.RenderTexture.prototype.getCanvas = function getCanvas(target) { - warn('RenderTexture.getCanvas is now deprecated, please use renderer.extract.canvas(target)'); - - return this.legacyRenderer.extract.canvas(target); - }; - - core.RenderTexture.prototype.getPixels = function getPixels(target) { - warn('RenderTexture.getPixels is now deprecated, please use renderer.extract.pixels(target)'); - - return this.legacyRenderer.pixels(target); - }; - - /** - * @method - * @private - * @name PIXI.Sprite#setTexture - * @see PIXI.Sprite#texture - * @deprecated since version 3.0.0 - * @param {PIXI.Texture} texture - The texture to set to. - */ - core.Sprite.prototype.setTexture = function setTexture(texture) { - this.texture = texture; - warn('setTexture is now deprecated, please use the texture property, e.g : sprite.texture = texture;'); - }; - - if (extras.BitmapText) { - /** - * @method - * @name PIXI.extras.BitmapText#setText - * @see PIXI.extras.BitmapText#text - * @deprecated since version 3.0.0 - * @param {string} text - The text to set to. - */ - extras.BitmapText.prototype.setText = function setText(text) { - this.text = text; - warn('setText is now deprecated, please use the text property, e.g : myBitmapText.text = \'my text\';'); - }; - } - - /** - * @method - * @name PIXI.Text#setText - * @see PIXI.Text#text - * @deprecated since version 3.0.0 - * @param {string} text - The text to set to. - */ - core.Text.prototype.setText = function setText(text) { - this.text = text; - warn('setText is now deprecated, please use the text property, e.g : myText.text = \'my text\';'); - }; - - /** - * Calculates the ascent, descent and fontSize of a given fontStyle - * - * @name PIXI.Text.calculateFontProperties - * @see PIXI.TextMetrics.measureFont - * @deprecated since version 4.5.0 - * @param {string} font - String representing the style of the font - * @return {Object} Font properties object - */ - core.Text.calculateFontProperties = function calculateFontProperties(font) { - warn('Text.calculateFontProperties is now deprecated, please use the TextMetrics.measureFont'); - - return core.TextMetrics.measureFont(font); - }; - - Object.defineProperties(core.Text, { - fontPropertiesCache: { - get: function get() { - warn('Text.fontPropertiesCache is deprecated'); - - return core.TextMetrics._fonts; - } - }, - fontPropertiesCanvas: { - get: function get() { - warn('Text.fontPropertiesCanvas is deprecated'); - - return core.TextMetrics._canvas; - } - }, - fontPropertiesContext: { - get: function get() { - warn('Text.fontPropertiesContext is deprecated'); - - return core.TextMetrics._context; - } - } - }); - - /** - * @method - * @name PIXI.Text#setStyle - * @see PIXI.Text#style - * @deprecated since version 3.0.0 - * @param {*} style - The style to set to. - */ - core.Text.prototype.setStyle = function setStyle(style) { - this.style = style; - warn('setStyle is now deprecated, please use the style property, e.g : myText.style = style;'); - }; - - /** - * @method - * @name PIXI.Text#determineFontProperties - * @see PIXI.Text#measureFontProperties - * @deprecated since version 4.2.0 - * @private - * @param {string} fontStyle - String representing the style of the font - * @return {Object} Font properties object - */ - core.Text.prototype.determineFontProperties = function determineFontProperties(fontStyle) { - warn('determineFontProperties is now deprecated, please use TextMetrics.measureFont method'); - - return core.TextMetrics.measureFont(fontStyle); - }; - - /** - * @method - * @name PIXI.Text.getFontStyle - * @see PIXI.TextMetrics.getFontStyle - * @deprecated since version 4.5.0 - * @param {PIXI.TextStyle} style - The style to use. - * @return {string} Font string - */ - core.Text.getFontStyle = function getFontStyle(style) { - warn('getFontStyle is now deprecated, please use TextStyle.toFontString() instead'); - - style = style || {}; - - if (!(style instanceof core.TextStyle)) { - style = new core.TextStyle(style); - } - - return style.toFontString(); - }; - - Object.defineProperties(core.TextStyle.prototype, { - /** - * Set all properties of a font as a single string - * - * @name PIXI.TextStyle#font - * @deprecated since version 4.0.0 - */ - font: { - get: function get() { - warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\', \'fontSize\', \'fontStyle\', \'fontVariant\' and \'fontWeight\' properties from now on'); - - var fontSizeString = typeof this._fontSize === 'number' ? this._fontSize + 'px' : this._fontSize; - - return this._fontStyle + ' ' + this._fontVariant + ' ' + this._fontWeight + ' ' + fontSizeString + ' ' + this._fontFamily; - }, - set: function set(font) { - warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\',\'fontSize\',fontStyle\',\'fontVariant\' and \'fontWeight\' properties from now on'); - - // can work out fontStyle from search of whole string - if (font.indexOf('italic') > 1) { - this._fontStyle = 'italic'; - } else if (font.indexOf('oblique') > -1) { - this._fontStyle = 'oblique'; - } else { - this._fontStyle = 'normal'; - } - - // can work out fontVariant from search of whole string - if (font.indexOf('small-caps') > -1) { - this._fontVariant = 'small-caps'; - } else { - this._fontVariant = 'normal'; - } - - // fontWeight and fontFamily are tricker to find, but it's easier to find the fontSize due to it's units - var splits = font.split(' '); - var fontSizeIndex = -1; - - this._fontSize = 26; - for (var i = 0; i < splits.length; ++i) { - if (splits[i].match(/(px|pt|em|%)/)) { - fontSizeIndex = i; - this._fontSize = splits[i]; - break; - } - } - - // we can now search for fontWeight as we know it must occur before the fontSize - this._fontWeight = 'normal'; - for (var _i = 0; _i < fontSizeIndex; ++_i) { - if (splits[_i].match(/(bold|bolder|lighter|100|200|300|400|500|600|700|800|900)/)) { - this._fontWeight = splits[_i]; - break; - } - } - - // and finally join everything together after the fontSize in case the font family has multiple words - if (fontSizeIndex > -1 && fontSizeIndex < splits.length - 1) { - this._fontFamily = ''; - for (var _i2 = fontSizeIndex + 1; _i2 < splits.length; ++_i2) { - this._fontFamily += splits[_i2] + ' '; - } - - this._fontFamily = this._fontFamily.slice(0, -1); - } else { - this._fontFamily = 'Arial'; - } - - this.styleID++; - } - } - }); - - /** - * @method - * @name PIXI.Texture#setFrame - * @see PIXI.Texture#setFrame - * @deprecated since version 3.0.0 - * @param {PIXI.Rectangle} frame - The frame to set. - */ - core.Texture.prototype.setFrame = function setFrame(frame) { - this.frame = frame; - warn('setFrame is now deprecated, please use the frame property, e.g: myTexture.frame = frame;'); - }; - - /** - * @static - * @function - * @name PIXI.Texture.addTextureToCache - * @see PIXI.Texture.addToCache - * @deprecated since 4.5.0 - * @param {PIXI.Texture} texture - The Texture to add to the cache. - * @param {string} id - The id that the texture will be stored against. - */ - core.Texture.addTextureToCache = function addTextureToCache(texture, id) { - core.Texture.addToCache(texture, id); - warn('Texture.addTextureToCache is deprecated, please use Texture.addToCache from now on.'); - }; - - /** - * @static - * @function - * @name PIXI.Texture.removeTextureFromCache - * @see PIXI.Texture.removeFromCache - * @deprecated since 4.5.0 - * @param {string} id - The id of the texture to be removed - * @return {PIXI.Texture|null} The texture that was removed - */ - core.Texture.removeTextureFromCache = function removeTextureFromCache(id) { - warn('Texture.removeTextureFromCache is deprecated, please use Texture.removeFromCache from now on. ' + 'Be aware that Texture.removeFromCache does not automatically its BaseTexture from the BaseTextureCache. ' + 'For that, use BaseTexture.removeFromCache'); - - core.BaseTexture.removeFromCache(id); - - return core.Texture.removeFromCache(id); - }; - - Object.defineProperties(filters, { - - /** - * @class - * @private - * @name PIXI.filters.AbstractFilter - * @see PIXI.AbstractFilter - * @deprecated since version 3.0.6 - */ - AbstractFilter: { - get: function get() { - warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); - - return core.AbstractFilter; - } - }, - - /** - * @class - * @private - * @name PIXI.filters.SpriteMaskFilter - * @see PIXI.SpriteMaskFilter - * @deprecated since version 3.0.6 - */ - SpriteMaskFilter: { - get: function get() { - warn('filters.SpriteMaskFilter is an undocumented alias, please use SpriteMaskFilter from now on.'); - - return core.SpriteMaskFilter; - } - } - }); - - /** - * @method - * @name PIXI.utils.uuid - * @see PIXI.utils.uid - * @deprecated since version 3.0.6 - * @return {number} The uid - */ - core.utils.uuid = function () { - warn('utils.uuid() is deprecated, please use utils.uid() from now on.'); - - return core.utils.uid(); - }; - - /** - * @method - * @name PIXI.utils.canUseNewCanvasBlendModes - * @see PIXI.CanvasTinter - * @deprecated - * @return {boolean} Can use blend modes. - */ - core.utils.canUseNewCanvasBlendModes = function () { - warn('utils.canUseNewCanvasBlendModes() is deprecated, please use CanvasTinter.canUseMultiply from now on'); - - return core.CanvasTinter.canUseMultiply; - }; - - var saidHello = true; - - /** - * @name PIXI.utils._saidHello - * @type {boolean} - * @see PIXI.utils.skipHello - * @deprecated since 4.1.0 - */ - Object.defineProperty(core.utils, '_saidHello', { - set: function set(bool) { - if (bool) { - warn('PIXI.utils._saidHello is deprecated, please use PIXI.utils.skipHello()'); - this.skipHello(); - } - saidHello = bool; - }, - get: function get() { - return saidHello; - } - }); - - if (prepare.BasePrepare) { - /** - * @method - * @name PIXI.prepare.BasePrepare#register - * @see PIXI.prepare.BasePrepare#registerFindHook - * @deprecated since version 4.4.2 - * @param {Function} [addHook] - Function call that takes two parameters: `item:*, queue:Array` - * function must return `true` if it was able to add item to the queue. - * @param {Function} [uploadHook] - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and - * function must return `true` if it was able to handle upload of item. - * @return {PIXI.BasePrepare} Instance of plugin for chaining. - */ - prepare.BasePrepare.prototype.register = function register(addHook, uploadHook) { - warn('renderer.plugins.prepare.register is now deprecated, ' + 'please use renderer.plugins.prepare.registerFindHook & renderer.plugins.prepare.registerUploadHook'); - - if (addHook) { - this.registerFindHook(addHook); - } - - if (uploadHook) { - this.registerUploadHook(uploadHook); - } - - return this; - }; - } - - if (prepare.canvas) { - /** - * The number of graphics or textures to upload to the GPU. - * - * @name PIXI.prepare.canvas.UPLOADS_PER_FRAME - * @static - * @type {number} - * @see PIXI.prepare.BasePrepare.limiter - * @deprecated since 4.2.0 - */ - Object.defineProperty(prepare.canvas, 'UPLOADS_PER_FRAME', { - set: function set() { - warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); - // because we don't have a reference to the renderer, we can't actually set - // the uploads per frame, so we'll have to stick with the warning. - }, - get: function get() { - warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); - - return NaN; - } - }); - } - - if (prepare.webgl) { - /** - * The number of graphics or textures to upload to the GPU. - * - * @name PIXI.prepare.webgl.UPLOADS_PER_FRAME - * @static - * @type {number} - * @see PIXI.prepare.BasePrepare.limiter - * @deprecated since 4.2.0 - */ - Object.defineProperty(prepare.webgl, 'UPLOADS_PER_FRAME', { - set: function set() { - warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); - // because we don't have a reference to the renderer, we can't actually set - // the uploads per frame, so we'll have to stick with the warning. - }, - get: function get() { - warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); - - return NaN; - } - }); - } - - if (loaders.Loader) { - var Resource = loaders.Resource; - var Loader = loaders.Loader; - - Object.defineProperties(Resource.prototype, { - isJson: { - get: function get() { - warn('The isJson property is deprecated, please use `resource.type === Resource.TYPE.JSON`.'); - - return this.type === Resource.TYPE.JSON; - } - }, - isXml: { - get: function get() { - warn('The isXml property is deprecated, please use `resource.type === Resource.TYPE.XML`.'); - - return this.type === Resource.TYPE.XML; - } - }, - isImage: { - get: function get() { - warn('The isImage property is deprecated, please use `resource.type === Resource.TYPE.IMAGE`.'); - - return this.type === Resource.TYPE.IMAGE; - } - }, - isAudio: { - get: function get() { - warn('The isAudio property is deprecated, please use `resource.type === Resource.TYPE.AUDIO`.'); - - return this.type === Resource.TYPE.AUDIO; - } - }, - isVideo: { - get: function get() { - warn('The isVideo property is deprecated, please use `resource.type === Resource.TYPE.VIDEO`.'); - - return this.type === Resource.TYPE.VIDEO; - } - } - }); - - Object.defineProperties(Loader.prototype, { - before: { - get: function get() { - warn('The before() method is deprecated, please use pre().'); - - return this.pre; - } - }, - after: { - get: function get() { - warn('The after() method is deprecated, please use use().'); - - return this.use; - } - } - }); - } - - if (interaction.interactiveTarget) { - /** - * @name PIXI.interaction.interactiveTarget#defaultCursor - * @static - * @type {number} - * @see PIXI.interaction.interactiveTarget#cursor - * @deprecated since 4.3.0 - */ - Object.defineProperty(interaction.interactiveTarget, 'defaultCursor', { - set: function set(value) { - warn('Property defaultCursor has been replaced with \'cursor\'. '); - this.cursor = value; - }, - get: function get() { - warn('Property defaultCursor has been replaced with \'cursor\'. '); - - return this.cursor; - } - }); - } - - if (interaction.InteractionManager) { - /** - * @name PIXI.interaction.InteractionManager#defaultCursorStyle - * @static - * @type {string} - * @see PIXI.interaction.InteractionManager#cursorStyles - * @deprecated since 4.3.0 - */ - Object.defineProperty(interaction.InteractionManager, 'defaultCursorStyle', { - set: function set(value) { - warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); - this.cursorStyles.default = value; - }, - get: function get() { - warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); - - return this.cursorStyles.default; - } - }); - - /** - * @name PIXI.interaction.InteractionManager#currentCursorStyle - * @static - * @type {string} - * @see PIXI.interaction.InteractionManager#cursorStyles - * @deprecated since 4.3.0 - */ - Object.defineProperty(interaction.InteractionManager, 'currentCursorStyle', { - set: function set(value) { - warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); - this.currentCursorMode = value; - }, - get: function get() { - warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); - - return this.currentCursorMode; - } - }); - } -} - -},{}],131:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _core = require('../../core'); - -var core = _interopRequireWildcard(_core); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var TEMP_RECT = new core.Rectangle(); - -/** - * The extract manager provides functionality to export content from the renderers. - * - * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract - * - * @class - * @memberof PIXI.extract - */ - -var CanvasExtract = function () { - /** - * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer - */ - function CanvasExtract(renderer) { - _classCallCheck(this, CanvasExtract); - - this.renderer = renderer; - /** - * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture - * - * @member {PIXI.extract.CanvasExtract} extract - * @memberof PIXI.CanvasRenderer# - * @see PIXI.extract.CanvasExtract - */ - renderer.extract = this; - } - - /** - * Will return a HTML Image of the target - * - * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture - * to convert. If left empty will use use the main renderer - * @return {HTMLImageElement} HTML Image of the target - */ - - - CanvasExtract.prototype.image = function image(target) { - var image = new Image(); - - image.src = this.base64(target); - - return image; - }; - - /** - * Will return a a base64 encoded string of this target. It works by calling - * `CanvasExtract.getCanvas` and then running toDataURL on that. - * - * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture - * to convert. If left empty will use use the main renderer - * @return {string} A base64 encoded string of the texture. - */ - - - CanvasExtract.prototype.base64 = function base64(target) { - return this.canvas(target).toDataURL(); - }; - - /** - * Creates a Canvas element, renders this target to it and then returns it. - * - * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture - * to convert. If left empty will use use the main renderer - * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. - */ - - - CanvasExtract.prototype.canvas = function canvas(target) { - var renderer = this.renderer; - var context = void 0; - var resolution = void 0; - var frame = void 0; - var renderTexture = void 0; - - if (target) { - if (target instanceof core.RenderTexture) { - renderTexture = target; - } else { - renderTexture = renderer.generateTexture(target); - } - } - - if (renderTexture) { - context = renderTexture.baseTexture._canvasRenderTarget.context; - resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; - frame = renderTexture.frame; - } else { - context = renderer.rootContext; - - frame = TEMP_RECT; - frame.width = this.renderer.width; - frame.height = this.renderer.height; - } - - var width = frame.width * resolution; - var height = frame.height * resolution; - - var canvasBuffer = new core.CanvasRenderTarget(width, height); - var canvasData = context.getImageData(frame.x * resolution, frame.y * resolution, width, height); - - canvasBuffer.context.putImageData(canvasData, 0, 0); - - // send the canvas back.. - return canvasBuffer.canvas; - }; - - /** - * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA - * order, with integer values between 0 and 255 (included). - * - * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture - * to convert. If left empty will use use the main renderer - * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture - */ - - - CanvasExtract.prototype.pixels = function pixels(target) { - var renderer = this.renderer; - var context = void 0; - var resolution = void 0; - var frame = void 0; - var renderTexture = void 0; - - if (target) { - if (target instanceof core.RenderTexture) { - renderTexture = target; - } else { - renderTexture = renderer.generateTexture(target); - } - } - - if (renderTexture) { - context = renderTexture.baseTexture._canvasRenderTarget.context; - resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; - frame = renderTexture.frame; - } else { - context = renderer.rootContext; - - frame = TEMP_RECT; - frame.width = renderer.width; - frame.height = renderer.height; - } - - return context.getImageData(0, 0, frame.width * resolution, frame.height * resolution).data; - }; - - /** - * Destroys the extract - * - */ - - - CanvasExtract.prototype.destroy = function destroy() { - this.renderer.extract = null; - this.renderer = null; - }; - - return CanvasExtract; -}(); - -exports.default = CanvasExtract; - - -core.CanvasRenderer.registerPlugin('extract', CanvasExtract); - -},{"../../core":65}],132:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _WebGLExtract = require('./webgl/WebGLExtract'); - -Object.defineProperty(exports, 'webgl', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_WebGLExtract).default; - } -}); - -var _CanvasExtract = require('./canvas/CanvasExtract'); - -Object.defineProperty(exports, 'canvas', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_CanvasExtract).default; - } -}); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -},{"./canvas/CanvasExtract":131,"./webgl/WebGLExtract":133}],133:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _core = require('../../core'); - -var core = _interopRequireWildcard(_core); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var TEMP_RECT = new core.Rectangle(); -var BYTES_PER_PIXEL = 4; - -/** - * The extract manager provides functionality to export content from the renderers. - * - * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract - * - * @class - * @memberof PIXI.extract - */ - -var WebGLExtract = function () { - /** - * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer - */ - function WebGLExtract(renderer) { - _classCallCheck(this, WebGLExtract); - - this.renderer = renderer; - /** - * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture - * - * @member {PIXI.extract.WebGLExtract} extract - * @memberof PIXI.WebGLRenderer# - * @see PIXI.extract.WebGLExtract - */ - renderer.extract = this; - } - - /** - * Will return a HTML Image of the target - * - * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture - * to convert. If left empty will use use the main renderer - * @return {HTMLImageElement} HTML Image of the target - */ - - - WebGLExtract.prototype.image = function image(target) { - var image = new Image(); - - image.src = this.base64(target); - - return image; - }; - - /** - * Will return a a base64 encoded string of this target. It works by calling - * `WebGLExtract.getCanvas` and then running toDataURL on that. - * - * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture - * to convert. If left empty will use use the main renderer - * @return {string} A base64 encoded string of the texture. - */ - - - WebGLExtract.prototype.base64 = function base64(target) { - return this.canvas(target).toDataURL(); - }; - - /** - * Creates a Canvas element, renders this target to it and then returns it. - * - * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture - * to convert. If left empty will use use the main renderer - * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. - */ - - - WebGLExtract.prototype.canvas = function canvas(target) { - var renderer = this.renderer; - var textureBuffer = void 0; - var resolution = void 0; - var frame = void 0; - var flipY = false; - var renderTexture = void 0; - - if (target) { - if (target instanceof core.RenderTexture) { - renderTexture = target; - } else { - renderTexture = this.renderer.generateTexture(target); - } - } - - if (renderTexture) { - textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; - resolution = textureBuffer.resolution; - frame = renderTexture.frame; - flipY = false; - } else { - textureBuffer = this.renderer.rootRenderTarget; - resolution = textureBuffer.resolution; - flipY = true; - - frame = TEMP_RECT; - frame.width = textureBuffer.size.width; - frame.height = textureBuffer.size.height; - } - - var width = frame.width * resolution; - var height = frame.height * resolution; - - var canvasBuffer = new core.CanvasRenderTarget(width, height); - - if (textureBuffer) { - // bind the buffer - renderer.bindRenderTarget(textureBuffer); - - // set up an array of pixels - var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); - - // read pixels to the array - var gl = renderer.gl; - - gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); - - // add the pixels to the canvas - var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); - - canvasData.data.set(webglPixels); - - canvasBuffer.context.putImageData(canvasData, 0, 0); - - // pulling pixels - if (flipY) { - canvasBuffer.context.scale(1, -1); - canvasBuffer.context.drawImage(canvasBuffer.canvas, 0, -height); - } - } - - // send the canvas back.. - return canvasBuffer.canvas; - }; - - /** - * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA - * order, with integer values between 0 and 255 (included). - * - * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture - * to convert. If left empty will use use the main renderer - * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture - */ - - - WebGLExtract.prototype.pixels = function pixels(target) { - var renderer = this.renderer; - var textureBuffer = void 0; - var resolution = void 0; - var frame = void 0; - var renderTexture = void 0; - - if (target) { - if (target instanceof core.RenderTexture) { - renderTexture = target; - } else { - renderTexture = this.renderer.generateTexture(target); - } - } - - if (renderTexture) { - textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; - resolution = textureBuffer.resolution; - frame = renderTexture.frame; - } else { - textureBuffer = this.renderer.rootRenderTarget; - resolution = textureBuffer.resolution; - - frame = TEMP_RECT; - frame.width = textureBuffer.size.width; - frame.height = textureBuffer.size.height; - } - - var width = frame.width * resolution; - var height = frame.height * resolution; - - var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); - - if (textureBuffer) { - // bind the buffer - renderer.bindRenderTarget(textureBuffer); - // read pixels to the array - var gl = renderer.gl; - - gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); - } - - return webglPixels; - }; - - /** - * Destroys the extract - * - */ - - - WebGLExtract.prototype.destroy = function destroy() { - this.renderer.extract = null; - this.renderer = null; - }; - - return WebGLExtract; -}(); - -exports.default = WebGLExtract; - - -core.WebGLRenderer.registerPlugin('extract', WebGLExtract); - -},{"../../core":65}],134:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _core = require('../core'); - -var core = _interopRequireWildcard(_core); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * @typedef FrameObject - * @type {object} - * @property {PIXI.Texture} texture - The {@link PIXI.Texture} of the frame - * @property {number} time - the duration of the frame in ms - */ - -/** - * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. - * - * ```js - * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; - * let textureArray = []; - * - * for (let i=0; i < 4; i++) - * { - * let texture = PIXI.Texture.fromImage(alienImages[i]); - * textureArray.push(texture); - * }; - * - * let mc = new PIXI.AnimatedSprite(textureArray); - * ``` - * - * @class - * @extends PIXI.Sprite - * @memberof PIXI.extras - */ -var AnimatedSprite = function (_core$Sprite) { - _inherits(AnimatedSprite, _core$Sprite); - - /** - * @param {PIXI.Texture[]|FrameObject[]} textures - an array of {@link PIXI.Texture} or frame - * objects that make up the animation - * @param {boolean} [autoUpdate=true] - Whether to use PIXI.ticker.shared to auto update animation time. - */ - function AnimatedSprite(textures, autoUpdate) { - _classCallCheck(this, AnimatedSprite); - - /** - * @private - */ - var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, textures[0] instanceof core.Texture ? textures[0] : textures[0].texture)); - - _this._textures = null; - - /** - * @private - */ - _this._durations = null; - - _this.textures = textures; - - /** - * `true` uses PIXI.ticker.shared to auto update animation time. - * @type {boolean} - * @default true - * @private - */ - _this._autoUpdate = autoUpdate !== false; - - /** - * The speed that the AnimatedSprite will play at. Higher is faster, lower is slower - * - * @member {number} - * @default 1 - */ - _this.animationSpeed = 1; - - /** - * Whether or not the animate sprite repeats after playing. - * - * @member {boolean} - * @default true - */ - _this.loop = true; - - /** - * Function to call when a AnimatedSprite finishes playing - * - * @member {Function} - */ - _this.onComplete = null; - - /** - * Function to call when a AnimatedSprite changes which texture is being rendered - * - * @member {Function} - */ - _this.onFrameChange = null; - - /** - * Function to call when 'loop' is true, and an AnimatedSprite is played and loops around to start again - * - * @member {Function} - */ - _this.onLoop = null; - - /** - * Elapsed time since animation has been started, used internally to display current texture - * - * @member {number} - * @private - */ - _this._currentTime = 0; - - /** - * Indicates if the AnimatedSprite is currently playing - * - * @member {boolean} - * @readonly - */ - _this.playing = false; - return _this; - } - - /** - * Stops the AnimatedSprite - * - */ - - - AnimatedSprite.prototype.stop = function stop() { - if (!this.playing) { - return; - } - - this.playing = false; - if (this._autoUpdate) { - core.ticker.shared.remove(this.update, this); - } - }; - - /** - * Plays the AnimatedSprite - * - */ - - - AnimatedSprite.prototype.play = function play() { - if (this.playing) { - return; - } - - this.playing = true; - if (this._autoUpdate) { - core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.HIGH); - } - }; - - /** - * Stops the AnimatedSprite and goes to a specific frame - * - * @param {number} frameNumber - frame index to stop at - */ - - - AnimatedSprite.prototype.gotoAndStop = function gotoAndStop(frameNumber) { - this.stop(); - - var previousFrame = this.currentFrame; - - this._currentTime = frameNumber; - - if (previousFrame !== this.currentFrame) { - this.updateTexture(); - } - }; - - /** - * Goes to a specific frame and begins playing the AnimatedSprite - * - * @param {number} frameNumber - frame index to start at - */ - - - AnimatedSprite.prototype.gotoAndPlay = function gotoAndPlay(frameNumber) { - var previousFrame = this.currentFrame; - - this._currentTime = frameNumber; - - if (previousFrame !== this.currentFrame) { - this.updateTexture(); - } - - this.play(); - }; - - /** - * Updates the object transform for rendering. - * - * @private - * @param {number} deltaTime - Time since last tick. - */ - - - AnimatedSprite.prototype.update = function update(deltaTime) { - var elapsed = this.animationSpeed * deltaTime; - var previousFrame = this.currentFrame; - - if (this._durations !== null) { - var lag = this._currentTime % 1 * this._durations[this.currentFrame]; - - lag += elapsed / 60 * 1000; - - while (lag < 0) { - this._currentTime--; - lag += this._durations[this.currentFrame]; - } - - var sign = Math.sign(this.animationSpeed * deltaTime); - - this._currentTime = Math.floor(this._currentTime); - - while (lag >= this._durations[this.currentFrame]) { - lag -= this._durations[this.currentFrame] * sign; - this._currentTime += sign; - } - - this._currentTime += lag / this._durations[this.currentFrame]; - } else { - this._currentTime += elapsed; - } - - if (this._currentTime < 0 && !this.loop) { - this.gotoAndStop(0); - - if (this.onComplete) { - this.onComplete(); - } - } else if (this._currentTime >= this._textures.length && !this.loop) { - this.gotoAndStop(this._textures.length - 1); - - if (this.onComplete) { - this.onComplete(); - } - } else if (previousFrame !== this.currentFrame) { - if (this.loop && this.onLoop) { - if (this.animationSpeed > 0 && this.currentFrame < previousFrame) { - this.onLoop(); - } else if (this.animationSpeed < 0 && this.currentFrame > previousFrame) { - this.onLoop(); - } - } - - this.updateTexture(); - } - }; - - /** - * Updates the displayed texture to match the current frame index - * - * @private - */ - - - AnimatedSprite.prototype.updateTexture = function updateTexture() { - this._texture = this._textures[this.currentFrame]; - this._textureID = -1; - - if (this.onFrameChange) { - this.onFrameChange(this.currentFrame); - } - }; - - /** - * Stops the AnimatedSprite and destroys it - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy - * method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well - * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well - */ - - - AnimatedSprite.prototype.destroy = function destroy(options) { - this.stop(); - _core$Sprite.prototype.destroy.call(this, options); - }; - - /** - * A short hand way of creating a movieclip from an array of frame ids - * - * @static - * @param {string[]} frames - The array of frames ids the movieclip will use as its texture frames - * @return {AnimatedSprite} The new animated sprite with the specified frames. - */ - - - AnimatedSprite.fromFrames = function fromFrames(frames) { - var textures = []; - - for (var i = 0; i < frames.length; ++i) { - textures.push(core.Texture.fromFrame(frames[i])); - } - - return new AnimatedSprite(textures); - }; - - /** - * A short hand way of creating a movieclip from an array of image ids - * - * @static - * @param {string[]} images - the array of image urls the movieclip will use as its texture frames - * @return {AnimatedSprite} The new animate sprite with the specified images as frames. - */ - - - AnimatedSprite.fromImages = function fromImages(images) { - var textures = []; - - for (var i = 0; i < images.length; ++i) { - textures.push(core.Texture.fromImage(images[i])); - } - - return new AnimatedSprite(textures); - }; - - /** - * totalFrames is the total number of frames in the AnimatedSprite. This is the same as number of textures - * assigned to the AnimatedSprite. - * - * @readonly - * @member {number} - * @default 0 - */ - - - _createClass(AnimatedSprite, [{ - key: 'totalFrames', - get: function get() { - return this._textures.length; - } - - /** - * The array of textures used for this AnimatedSprite - * - * @member {PIXI.Texture[]} - */ - - }, { - key: 'textures', - get: function get() { - return this._textures; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - if (value[0] instanceof core.Texture) { - this._textures = value; - this._durations = null; - } else { - this._textures = []; - this._durations = []; - - for (var i = 0; i < value.length; i++) { - this._textures.push(value[i].texture); - this._durations.push(value[i].time); - } - } - this.gotoAndStop(0); - this.updateTexture(); - } - - /** - * The AnimatedSprites current frame index - * - * @member {number} - * @readonly - */ - - }, { - key: 'currentFrame', - get: function get() { - var currentFrame = Math.floor(this._currentTime) % this._textures.length; - - if (currentFrame < 0) { - currentFrame += this._textures.length; - } - - return currentFrame; - } - }]); - - return AnimatedSprite; -}(core.Sprite); - -exports.default = AnimatedSprite; - -},{"../core":65}],135:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _core = require('../core'); - -var core = _interopRequireWildcard(_core); - -var _ObservablePoint = require('../core/math/ObservablePoint'); - -var _ObservablePoint2 = _interopRequireDefault(_ObservablePoint); - -var _settings = require('../core/settings'); - -var _settings2 = _interopRequireDefault(_settings); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * A BitmapText object will create a line or multiple lines of text using bitmap font. To - * split a line you can use '\n', '\r' or '\r\n' in your string. You can generate the fnt files using: - * - * A BitmapText can only be created when the font is loaded - * - * ```js - * // in this case the font is in a file called 'desyrel.fnt' - * let bitmapText = new PIXI.extras.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); - * ``` - * - * http://www.angelcode.com/products/bmfont/ for windows or - * http://www.bmglyph.com/ for mac. - * - * @class - * @extends PIXI.Container - * @memberof PIXI.extras - */ -var BitmapText = function (_core$Container) { - _inherits(BitmapText, _core$Container); - - /** - * @param {string} text - The copy that you would like the text to display - * @param {object} style - The style parameters - * @param {string|object} style.font - The font descriptor for the object, can be passed as a string of form - * "24px FontName" or "FontName" or as an object with explicit name/size properties. - * @param {string} [style.font.name] - The bitmap font id - * @param {number} [style.font.size] - The size of the font in pixels, e.g. 24 - * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), does not affect - * single line text - * @param {number} [style.tint=0xFFFFFF] - The tint color - */ - function BitmapText(text) { - var style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - _classCallCheck(this, BitmapText); - - /** - * Private tracker for the width of the overall text - * - * @member {number} - * @private - */ - var _this = _possibleConstructorReturn(this, _core$Container.call(this)); - - _this._textWidth = 0; - - /** - * Private tracker for the height of the overall text - * - * @member {number} - * @private - */ - _this._textHeight = 0; - - /** - * Private tracker for the letter sprite pool. - * - * @member {PIXI.Sprite[]} - * @private - */ - _this._glyphs = []; - - /** - * Private tracker for the current style. - * - * @member {object} - * @private - */ - _this._font = { - tint: style.tint !== undefined ? style.tint : 0xFFFFFF, - align: style.align || 'left', - name: null, - size: 0 - }; - - /** - * Private tracker for the current font. - * - * @member {object} - * @private - */ - _this.font = style.font; // run font setter - - /** - * Private tracker for the current text. - * - * @member {string} - * @private - */ - _this._text = text; - - /** - * The max width of this bitmap text in pixels. If the text provided is longer than the - * value provided, line breaks will be automatically inserted in the last whitespace. - * Disable by setting value to 0 - * - * @member {number} - * @private - */ - _this._maxWidth = 0; - - /** - * The max line height. This is useful when trying to use the total height of the Text, - * ie: when trying to vertically align. - * - * @member {number} - * @private - */ - _this._maxLineHeight = 0; - - /** - * Text anchor. read-only - * - * @member {PIXI.ObservablePoint} - * @private - */ - _this._anchor = new _ObservablePoint2.default(function () { - _this.dirty = true; - }, _this, 0, 0); - - /** - * The dirty state of this object. - * - * @member {boolean} - */ - _this.dirty = false; - - _this.updateText(); - return _this; - } - - /** - * Renders text and updates it when needed - * - * @private - */ - - - BitmapText.prototype.updateText = function updateText() { - var data = BitmapText.fonts[this._font.name]; - var scale = this._font.size / data.size; - var pos = new core.Point(); - var chars = []; - var lineWidths = []; - - var prevCharCode = null; - var lastLineWidth = 0; - var maxLineWidth = 0; - var line = 0; - var lastSpace = -1; - var lastSpaceWidth = 0; - var spacesRemoved = 0; - var maxLineHeight = 0; - - for (var i = 0; i < this.text.length; i++) { - var charCode = this.text.charCodeAt(i); - - if (/(\s)/.test(this.text.charAt(i))) { - lastSpace = i; - lastSpaceWidth = lastLineWidth; - } - - if (/(?:\r\n|\r|\n)/.test(this.text.charAt(i))) { - lineWidths.push(lastLineWidth); - maxLineWidth = Math.max(maxLineWidth, lastLineWidth); - line++; - - pos.x = 0; - pos.y += data.lineHeight; - prevCharCode = null; - continue; - } - - if (lastSpace !== -1 && this._maxWidth > 0 && pos.x * scale > this._maxWidth) { - core.utils.removeItems(chars, lastSpace - spacesRemoved, i - lastSpace); - i = lastSpace; - lastSpace = -1; - ++spacesRemoved; - - lineWidths.push(lastSpaceWidth); - maxLineWidth = Math.max(maxLineWidth, lastSpaceWidth); - line++; - - pos.x = 0; - pos.y += data.lineHeight; - prevCharCode = null; - continue; - } - - var charData = data.chars[charCode]; - - if (!charData) { - continue; - } - - if (prevCharCode && charData.kerning[prevCharCode]) { - pos.x += charData.kerning[prevCharCode]; - } - - chars.push({ - texture: charData.texture, - line: line, - charCode: charCode, - position: new core.Point(pos.x + charData.xOffset, pos.y + charData.yOffset) - }); - lastLineWidth = pos.x + (charData.texture.width + charData.xOffset); - pos.x += charData.xAdvance; - maxLineHeight = Math.max(maxLineHeight, charData.yOffset + charData.texture.height); - prevCharCode = charCode; - } - - lineWidths.push(lastLineWidth); - maxLineWidth = Math.max(maxLineWidth, lastLineWidth); - - var lineAlignOffsets = []; - - for (var _i = 0; _i <= line; _i++) { - var alignOffset = 0; - - if (this._font.align === 'right') { - alignOffset = maxLineWidth - lineWidths[_i]; - } else if (this._font.align === 'center') { - alignOffset = (maxLineWidth - lineWidths[_i]) / 2; - } - - lineAlignOffsets.push(alignOffset); - } - - var lenChars = chars.length; - var tint = this.tint; - - for (var _i2 = 0; _i2 < lenChars; _i2++) { - var c = this._glyphs[_i2]; // get the next glyph sprite - - if (c) { - c.texture = chars[_i2].texture; - } else { - c = new core.Sprite(chars[_i2].texture); - this._glyphs.push(c); - } - - c.position.x = (chars[_i2].position.x + lineAlignOffsets[chars[_i2].line]) * scale; - c.position.y = chars[_i2].position.y * scale; - c.scale.x = c.scale.y = scale; - c.tint = tint; - - if (!c.parent) { - this.addChild(c); - } - } - - // remove unnecessary children. - for (var _i3 = lenChars; _i3 < this._glyphs.length; ++_i3) { - this.removeChild(this._glyphs[_i3]); - } - - this._textWidth = maxLineWidth * scale; - this._textHeight = (pos.y + data.lineHeight) * scale; - - // apply anchor - if (this.anchor.x !== 0 || this.anchor.y !== 0) { - for (var _i4 = 0; _i4 < lenChars; _i4++) { - this._glyphs[_i4].x -= this._textWidth * this.anchor.x; - this._glyphs[_i4].y -= this._textHeight * this.anchor.y; - } - } - this._maxLineHeight = maxLineHeight * scale; - }; - - /** - * Updates the transform of this object - * - * @private - */ - - - BitmapText.prototype.updateTransform = function updateTransform() { - this.validate(); - this.containerUpdateTransform(); - }; - - /** - * Validates text before calling parent's getLocalBounds - * - * @return {PIXI.Rectangle} The rectangular bounding area - */ - - - BitmapText.prototype.getLocalBounds = function getLocalBounds() { - this.validate(); - - return _core$Container.prototype.getLocalBounds.call(this); - }; - - /** - * Updates text when needed - * - * @private - */ - - - BitmapText.prototype.validate = function validate() { - if (this.dirty) { - this.updateText(); - this.dirty = false; - } - }; - - /** - * The tint of the BitmapText object - * - * @member {number} - */ - - - /** - * Register a bitmap font with data and a texture. - * - * @static - * @param {XMLDocument} xml - The XML document data. - * @param {PIXI.Texture} texture - Texture with all symbols. - * @return {Object} Result font object with font, size, lineHeight and char fields. - */ - BitmapText.registerFont = function registerFont(xml, texture) { - var data = {}; - var info = xml.getElementsByTagName('info')[0]; - var common = xml.getElementsByTagName('common')[0]; - var res = texture.baseTexture.resolution || _settings2.default.RESOLUTION; - - data.font = info.getAttribute('face'); - data.size = parseInt(info.getAttribute('size'), 10); - data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) / res; - data.chars = {}; - - // parse letters - var letters = xml.getElementsByTagName('char'); - - for (var i = 0; i < letters.length; i++) { - var letter = letters[i]; - var charCode = parseInt(letter.getAttribute('id'), 10); - - var textureRect = new core.Rectangle(parseInt(letter.getAttribute('x'), 10) / res + texture.frame.x / res, parseInt(letter.getAttribute('y'), 10) / res + texture.frame.y / res, parseInt(letter.getAttribute('width'), 10) / res, parseInt(letter.getAttribute('height'), 10) / res); - - data.chars[charCode] = { - xOffset: parseInt(letter.getAttribute('xoffset'), 10) / res, - yOffset: parseInt(letter.getAttribute('yoffset'), 10) / res, - xAdvance: parseInt(letter.getAttribute('xadvance'), 10) / res, - kerning: {}, - texture: new core.Texture(texture.baseTexture, textureRect) - - }; - } - - // parse kernings - var kernings = xml.getElementsByTagName('kerning'); - - for (var _i5 = 0; _i5 < kernings.length; _i5++) { - var kerning = kernings[_i5]; - var first = parseInt(kerning.getAttribute('first'), 10) / res; - var second = parseInt(kerning.getAttribute('second'), 10) / res; - var amount = parseInt(kerning.getAttribute('amount'), 10) / res; - - if (data.chars[second]) { - data.chars[second].kerning[first] = amount; - } - } - - // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3 - // but it's very likely to change - BitmapText.fonts[data.font] = data; - - return data; - }; - - _createClass(BitmapText, [{ - key: 'tint', - get: function get() { - return this._font.tint; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._font.tint = typeof value === 'number' && value >= 0 ? value : 0xFFFFFF; - - this.dirty = true; - } - - /** - * The alignment of the BitmapText object - * - * @member {string} - * @default 'left' - */ - - }, { - key: 'align', - get: function get() { - return this._font.align; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._font.align = value || 'left'; - - this.dirty = true; - } - - /** - * The anchor sets the origin point of the text. - * The default is 0,0 this means the text's origin is the top left - * Setting the anchor to 0.5,0.5 means the text's origin is centered - * Setting the anchor to 1,1 would mean the text's origin point will be the bottom right corner - * - * @member {PIXI.Point | number} - */ - - }, { - key: 'anchor', - get: function get() { - return this._anchor; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - if (typeof value === 'number') { - this._anchor.set(value); - } else { - this._anchor.copy(value); - } - } - - /** - * The font descriptor of the BitmapText object - * - * @member {string|object} - */ - - }, { - key: 'font', - get: function get() { - return this._font; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - if (!value) { - return; - } - - if (typeof value === 'string') { - value = value.split(' '); - - this._font.name = value.length === 1 ? value[0] : value.slice(1).join(' '); - this._font.size = value.length >= 2 ? parseInt(value[0], 10) : BitmapText.fonts[this._font.name].size; - } else { - this._font.name = value.name; - this._font.size = typeof value.size === 'number' ? value.size : parseInt(value.size, 10); - } - - this.dirty = true; - } - - /** - * The text of the BitmapText object - * - * @member {string} - */ - - }, { - key: 'text', - get: function get() { - return this._text; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - value = value.toString() || ' '; - if (this._text === value) { - return; - } - this._text = value; - this.dirty = true; - } - - /** - * The max width of this bitmap text in pixels. If the text provided is longer than the - * value provided, line breaks will be automatically inserted in the last whitespace. - * Disable by setting value to 0 - * - * @member {number} - */ - - }, { - key: 'maxWidth', - get: function get() { - return this._maxWidth; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - if (this._maxWidth === value) { - return; - } - this._maxWidth = value; - this.dirty = true; - } - - /** - * The max line height. This is useful when trying to use the total height of the Text, - * ie: when trying to vertically align. - * - * @member {number} - * @readonly - */ - - }, { - key: 'maxLineHeight', - get: function get() { - this.validate(); - - return this._maxLineHeight; - } - - /** - * The width of the overall text, different from fontSize, - * which is defined in the style object - * - * @member {number} - * @readonly - */ - - }, { - key: 'textWidth', - get: function get() { - this.validate(); - - return this._textWidth; - } - - /** - * The height of the overall text, different from fontSize, - * which is defined in the style object - * - * @member {number} - * @readonly - */ - - }, { - key: 'textHeight', - get: function get() { - this.validate(); - - return this._textHeight; - } - }]); - - return BitmapText; -}(core.Container); - -exports.default = BitmapText; - - -BitmapText.fonts = {}; - -},{"../core":65,"../core/math/ObservablePoint":68,"../core/settings":101}],136:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _Matrix = require('../core/math/Matrix'); - -var _Matrix2 = _interopRequireDefault(_Matrix); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var tempMat = new _Matrix2.default(); - -/** - * class controls uv transform and frame clamp for texture - * - * @class - * @memberof PIXI.extras - */ - -var TextureTransform = function () { - /** - * - * @param {PIXI.Texture} texture observed texture - * @param {number} [clampMargin] Changes frame clamping, 0.5 by default. Use -0.5 for extra border. - * @constructor - */ - function TextureTransform(texture, clampMargin) { - _classCallCheck(this, TextureTransform); - - this._texture = texture; - - this.mapCoord = new _Matrix2.default(); - - this.uClampFrame = new Float32Array(4); - - this.uClampOffset = new Float32Array(2); - - this._lastTextureID = -1; - - /** - * Changes frame clamping - * Works with TilingSprite and Mesh - * Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders - * - * @default 0 - * @member {number} - */ - this.clampOffset = 0; - - /** - * Changes frame clamping - * Works with TilingSprite and Mesh - * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas - * - * @default 0.5 - * @member {number} - */ - this.clampMargin = typeof clampMargin === 'undefined' ? 0.5 : clampMargin; - } - - /** - * texture property - * @member {PIXI.Texture} - */ - - - /** - * Multiplies uvs array to transform - * @param {Float32Array} uvs mesh uvs - * @param {Float32Array} [out=uvs] output - * @returns {Float32Array} output - */ - TextureTransform.prototype.multiplyUvs = function multiplyUvs(uvs, out) { - if (out === undefined) { - out = uvs; - } - - var mat = this.mapCoord; - - for (var i = 0; i < uvs.length; i += 2) { - var x = uvs[i]; - var y = uvs[i + 1]; - - out[i] = x * mat.a + y * mat.c + mat.tx; - out[i + 1] = x * mat.b + y * mat.d + mat.ty; - } - - return out; - }; - - /** - * updates matrices if texture was changed - * @param {boolean} forceUpdate if true, matrices will be updated any case - * @returns {boolean} whether or not it was updated - */ - - - TextureTransform.prototype.update = function update(forceUpdate) { - var tex = this._texture; - - if (!tex || !tex.valid) { - return false; - } - - if (!forceUpdate && this._lastTextureID === tex._updateID) { - return false; - } - - this._lastTextureID = tex._updateID; - - var uvs = tex._uvs; - - this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); - - var orig = tex.orig; - var trim = tex.trim; - - if (trim) { - tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); - this.mapCoord.append(tempMat); - } - - var texBase = tex.baseTexture; - var frame = this.uClampFrame; - var margin = this.clampMargin / texBase.resolution; - var offset = this.clampOffset; - - frame[0] = (tex._frame.x + margin + offset) / texBase.width; - frame[1] = (tex._frame.y + margin + offset) / texBase.height; - frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; - frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; - this.uClampOffset[0] = offset / texBase.realWidth; - this.uClampOffset[1] = offset / texBase.realHeight; - - return true; - }; - - _createClass(TextureTransform, [{ - key: 'texture', - get: function get() { - return this._texture; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._texture = value; - this._lastTextureID = -1; - } - }]); - - return TextureTransform; -}(); - -exports.default = TextureTransform; - -},{"../core/math/Matrix":67}],137:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _core = require('../core'); - -var core = _interopRequireWildcard(_core); - -var _CanvasTinter = require('../core/sprites/canvas/CanvasTinter'); - -var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); - -var _TextureTransform = require('./TextureTransform'); - -var _TextureTransform2 = _interopRequireDefault(_TextureTransform); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -var tempPoint = new core.Point(); - -/** - * A tiling sprite is a fast way of rendering a tiling image - * - * @class - * @extends PIXI.Sprite - * @memberof PIXI.extras - */ - -var TilingSprite = function (_core$Sprite) { - _inherits(TilingSprite, _core$Sprite); - - /** - * @param {PIXI.Texture} texture - the texture of the tiling sprite - * @param {number} [width=100] - the width of the tiling sprite - * @param {number} [height=100] - the height of the tiling sprite - */ - function TilingSprite(texture) { - var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; - var height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 100; - - _classCallCheck(this, TilingSprite); - - /** - * Tile transform - * - * @member {PIXI.TransformStatic} - */ - var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, texture)); - - _this.tileTransform = new core.TransformStatic(); - - // /// private - - /** - * The with of the tiling sprite - * - * @member {number} - * @private - */ - _this._width = width; - - /** - * The height of the tiling sprite - * - * @member {number} - * @private - */ - _this._height = height; - - /** - * Canvas pattern - * - * @type {CanvasPattern} - * @private - */ - _this._canvasPattern = null; - - /** - * transform that is applied to UV to get the texture coords - * - * @member {PIXI.extras.TextureTransform} - */ - _this.uvTransform = texture.transform || new _TextureTransform2.default(texture); - - /** - * Plugin that is responsible for rendering this element. - * Allows to customize the rendering process without overriding '_renderWebGL' method. - * - * @member {string} - * @default 'tilingSprite' - */ - _this.pluginName = 'tilingSprite'; - - /** - * Whether or not anchor affects uvs - * - * @member {boolean} - * @default false - */ - _this.uvRespectAnchor = false; - return _this; - } - /** - * Changes frame clamping in corresponding textureTransform, shortcut - * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas - * - * @default 0.5 - * @member {number} - */ - - - /** - * @private - */ - TilingSprite.prototype._onTextureUpdate = function _onTextureUpdate() { - if (this.uvTransform) { - this.uvTransform.texture = this._texture; - } - }; - - /** - * Renders the object using the WebGL renderer - * - * @private - * @param {PIXI.WebGLRenderer} renderer - The renderer - */ - - - TilingSprite.prototype._renderWebGL = function _renderWebGL(renderer) { - // tweak our texture temporarily.. - var texture = this._texture; - - if (!texture || !texture.valid) { - return; - } - - this.tileTransform.updateLocalTransform(); - this.uvTransform.update(); - - renderer.setObjectRenderer(renderer.plugins[this.pluginName]); - renderer.plugins[this.pluginName].render(this); - }; - - /** - * Renders the object using the Canvas renderer - * - * @private - * @param {PIXI.CanvasRenderer} renderer - a reference to the canvas renderer - */ - - - TilingSprite.prototype._renderCanvas = function _renderCanvas(renderer) { - var texture = this._texture; - - if (!texture.baseTexture.hasLoaded) { - return; - } - - var context = renderer.context; - var transform = this.worldTransform; - var resolution = renderer.resolution; - var baseTexture = texture.baseTexture; - var baseTextureResolution = baseTexture.resolution; - var modX = this.tilePosition.x / this.tileScale.x % texture._frame.width * baseTextureResolution; - var modY = this.tilePosition.y / this.tileScale.y % texture._frame.height * baseTextureResolution; - - // create a nice shiny pattern! - // TODO this needs to be refreshed if texture changes.. - if (!this._canvasPattern) { - // cut an object from a spritesheet.. - var tempCanvas = new core.CanvasRenderTarget(texture._frame.width, texture._frame.height, baseTextureResolution); - - // Tint the tiling sprite - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { - this.cachedTint = this.tint; - - this.tintedTexture = _CanvasTinter2.default.getTintedTexture(this, this.tint); - } - tempCanvas.context.drawImage(this.tintedTexture, 0, 0); - } else { - tempCanvas.context.drawImage(baseTexture.source, -texture._frame.x * baseTextureResolution, -texture._frame.y * baseTextureResolution); - } - this._canvasPattern = tempCanvas.context.createPattern(tempCanvas.canvas, 'repeat'); - } - - // set context state.. - context.globalAlpha = this.worldAlpha; - context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); - - renderer.setBlendMode(this.blendMode); - - // fill the pattern! - context.fillStyle = this._canvasPattern; - - // TODO - this should be rolled into the setTransform above.. - context.scale(this.tileScale.x / baseTextureResolution, this.tileScale.y / baseTextureResolution); - - var anchorX = this.anchor.x * -this._width; - var anchorY = this.anchor.y * -this._height; - - if (this.uvRespectAnchor) { - context.translate(modX, modY); - - context.fillRect(-modX + anchorX, -modY + anchorY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); - } else { - context.translate(modX + anchorX, modY + anchorY); - - context.fillRect(-modX, -modY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); - } - }; - - /** - * Updates the bounds of the tiling sprite. - * - * @private - */ - - - TilingSprite.prototype._calculateBounds = function _calculateBounds() { - var minX = this._width * -this._anchor._x; - var minY = this._height * -this._anchor._y; - var maxX = this._width * (1 - this._anchor._x); - var maxY = this._height * (1 - this._anchor._y); - - this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); - }; - - /** - * Gets the local bounds of the sprite object. - * - * @param {PIXI.Rectangle} rect - The output rectangle. - * @return {PIXI.Rectangle} The bounds. - */ - - - TilingSprite.prototype.getLocalBounds = function getLocalBounds(rect) { - // we can do a fast local bounds if the sprite has no children! - if (this.children.length === 0) { - this._bounds.minX = this._width * -this._anchor._x; - this._bounds.minY = this._height * -this._anchor._y; - this._bounds.maxX = this._width * (1 - this._anchor._x); - this._bounds.maxY = this._height * (1 - this._anchor._x); - - if (!rect) { - if (!this._localBoundsRect) { - this._localBoundsRect = new core.Rectangle(); - } - - rect = this._localBoundsRect; - } - - return this._bounds.getRectangle(rect); - } - - return _core$Sprite.prototype.getLocalBounds.call(this, rect); - }; - - /** - * Checks if a point is inside this tiling sprite. - * - * @param {PIXI.Point} point - the point to check - * @return {boolean} Whether or not the sprite contains the point. - */ - - - TilingSprite.prototype.containsPoint = function containsPoint(point) { - this.worldTransform.applyInverse(point, tempPoint); - - var width = this._width; - var height = this._height; - var x1 = -width * this.anchor._x; - - if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { - var y1 = -height * this.anchor._y; - - if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { - return true; - } - } - - return false; - }; - - /** - * Destroys this sprite and optionally its texture and children - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy - * method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well - * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well - */ - - - TilingSprite.prototype.destroy = function destroy(options) { - _core$Sprite.prototype.destroy.call(this, options); - - this.tileTransform = null; - this.uvTransform = null; - }; - - /** - * Helper function that creates a new tiling sprite based on the source you provide. - * The source can be - frame id, image url, video url, canvas element, video element, base texture - * - * @static - * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from - * @param {number} width - the width of the tiling sprite - * @param {number} height - the height of the tiling sprite - * @return {PIXI.Texture} The newly created texture - */ - - - TilingSprite.from = function from(source, width, height) { - return new TilingSprite(core.Texture.from(source), width, height); - }; - - /** - * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId - * The frame ids are created when a Texture packer file has been loaded - * - * @static - * @param {string} frameId - The frame Id of the texture in the cache - * @param {number} width - the width of the tiling sprite - * @param {number} height - the height of the tiling sprite - * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId - */ - - - TilingSprite.fromFrame = function fromFrame(frameId, width, height) { - var texture = core.utils.TextureCache[frameId]; - - if (!texture) { - throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ' + this); - } - - return new TilingSprite(texture, width, height); - }; - - /** - * Helper function that creates a sprite that will contain a texture based on an image url - * If the image is not in the texture cache it will be loaded - * - * @static - * @param {string} imageId - The image url of the texture - * @param {number} width - the width of the tiling sprite - * @param {number} height - the height of the tiling sprite - * @param {boolean} [crossorigin] - if you want to specify the cross-origin parameter - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, - * see {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id - */ - - - TilingSprite.fromImage = function fromImage(imageId, width, height, crossorigin, scaleMode) { - return new TilingSprite(core.Texture.fromImage(imageId, crossorigin, scaleMode), width, height); - }; - - /** - * The width of the sprite, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - - - _createClass(TilingSprite, [{ - key: 'clampMargin', - get: function get() { - return this.uvTransform.clampMargin; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.uvTransform.clampMargin = value; - this.uvTransform.update(true); - } - - /** - * The scaling of the image that is being tiled - * - * @member {PIXI.ObservablePoint} - */ - - }, { - key: 'tileScale', - get: function get() { - return this.tileTransform.scale; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.tileTransform.scale.copy(value); - } - - /** - * The offset of the image that is being tiled - * - * @member {PIXI.ObservablePoint} - */ - - }, { - key: 'tilePosition', - get: function get() { - return this.tileTransform.position; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.tileTransform.position.copy(value); - } - }, { - key: 'width', - get: function get() { - return this._width; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._width = value; - } - - /** - * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - - }, { - key: 'height', - get: function get() { - return this._height; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._height = value; - } - }]); - - return TilingSprite; -}(core.Sprite); - -exports.default = TilingSprite; - -},{"../core":65,"../core/sprites/canvas/CanvasTinter":104,"./TextureTransform":136}],138:[function(require,module,exports){ -'use strict'; - -var _core = require('../core'); - -var core = _interopRequireWildcard(_core); - -var _Texture = require('../core/textures/Texture'); - -var _Texture2 = _interopRequireDefault(_Texture); - -var _BaseTexture = require('../core/textures/BaseTexture'); - -var _BaseTexture2 = _interopRequireDefault(_BaseTexture); - -var _utils = require('../core/utils'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var DisplayObject = core.DisplayObject; -var _tempMatrix = new core.Matrix(); - -DisplayObject.prototype._cacheAsBitmap = false; -DisplayObject.prototype._cacheData = false; - -// figured theres no point adding ALL the extra variables to prototype. -// this model can hold the information needed. This can also be generated on demand as -// most objects are not cached as bitmaps. -/** - * @class - * @ignore - */ - -var CacheData = -/** - * - */ -function CacheData() { - _classCallCheck(this, CacheData); - - this.textureCacheId = null; - - this.originalRenderWebGL = null; - this.originalRenderCanvas = null; - this.originalCalculateBounds = null; - this.originalGetLocalBounds = null; - - this.originalUpdateTransform = null; - this.originalHitTest = null; - this.originalDestroy = null; - this.originalMask = null; - this.originalFilterArea = null; - this.sprite = null; -}; - -Object.defineProperties(DisplayObject.prototype, { - /** - * Set this to true if you want this display object to be cached as a bitmap. - * This basically takes a snap shot of the display object as it is at that moment. It can - * provide a performance benefit for complex static displayObjects. - * To remove simply set this property to 'false' - * - * IMPORTANT GOTCHA - make sure that all your textures are preloaded BEFORE setting this property to true - * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. - * - * @member {boolean} - * @memberof PIXI.DisplayObject# - */ - cacheAsBitmap: { - get: function get() { - return this._cacheAsBitmap; - }, - set: function set(value) { - if (this._cacheAsBitmap === value) { - return; - } - - this._cacheAsBitmap = value; - - var data = void 0; - - if (value) { - if (!this._cacheData) { - this._cacheData = new CacheData(); - } - - data = this._cacheData; - - data.originalRenderWebGL = this.renderWebGL; - data.originalRenderCanvas = this.renderCanvas; - - data.originalUpdateTransform = this.updateTransform; - data.originalCalculateBounds = this._calculateBounds; - data.originalGetLocalBounds = this.getLocalBounds; - - data.originalDestroy = this.destroy; - - data.originalContainsPoint = this.containsPoint; - - data.originalMask = this._mask; - data.originalFilterArea = this.filterArea; - - this.renderWebGL = this._renderCachedWebGL; - this.renderCanvas = this._renderCachedCanvas; - - this.destroy = this._cacheAsBitmapDestroy; - } else { - data = this._cacheData; - - if (data.sprite) { - this._destroyCachedDisplayObject(); - } - - this.renderWebGL = data.originalRenderWebGL; - this.renderCanvas = data.originalRenderCanvas; - this._calculateBounds = data.originalCalculateBounds; - this.getLocalBounds = data.originalGetLocalBounds; - - this.destroy = data.originalDestroy; - - this.updateTransform = data.originalUpdateTransform; - this.containsPoint = data.originalContainsPoint; - - this._mask = data.originalMask; - this.filterArea = data.originalFilterArea; - } - } - } -}); - -/** - * Renders a cached version of the sprite with WebGL - * - * @private - * @memberof PIXI.DisplayObject# - * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer - */ -DisplayObject.prototype._renderCachedWebGL = function _renderCachedWebGL(renderer) { - if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { - return; - } - - this._initCachedDisplayObject(renderer); - - this._cacheData.sprite._transformID = -1; - this._cacheData.sprite.worldAlpha = this.worldAlpha; - this._cacheData.sprite._renderWebGL(renderer); -}; - -/** - * Prepares the WebGL renderer to cache the sprite - * - * @private - * @memberof PIXI.DisplayObject# - * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer - */ -DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { - if (this._cacheData && this._cacheData.sprite) { - return; - } - - // make sure alpha is set to 1 otherwise it will get rendered as invisible! - var cacheAlpha = this.alpha; - - this.alpha = 1; - - // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) - renderer.currentRenderer.flush(); - // this.filters= []; - - // next we find the dimensions of the untransformed object - // this function also calls updatetransform on all its children as part of the measuring. - // This means we don't need to update the transform again in this function - // TODO pass an object to clone too? saves having to create a new one each time! - var bounds = this.getLocalBounds().clone(); - - // add some padding! - if (this._filters) { - var padding = this._filters[0].padding; - - bounds.pad(padding); - } - - // for now we cache the current renderTarget that the webGL renderer is currently using. - // this could be more elegent.. - var cachedRenderTarget = renderer._activeRenderTarget; - // We also store the filter stack - I will definitely look to change how this works a little later down the line. - var stack = renderer.filterManager.filterStack; - - // this renderTexture will be used to store the cached DisplayObject - - var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); - - var textureCacheId = 'cacheAsBitmap_' + (0, _utils.uid)(); - - this._cacheData.textureCacheId = textureCacheId; - - _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); - _Texture2.default.addToCache(renderTexture, textureCacheId); - - // need to set // - var m = _tempMatrix; - - m.tx = -bounds.x; - m.ty = -bounds.y; - - // reset - this.transform.worldTransform.identity(); - - // set all properties to there original so we can render to a texture - this.renderWebGL = this._cacheData.originalRenderWebGL; - - renderer.render(this, renderTexture, true, m, true); - // now restore the state be setting the new properties - - renderer.bindRenderTarget(cachedRenderTarget); - - renderer.filterManager.filterStack = stack; - - this.renderWebGL = this._renderCachedWebGL; - this.updateTransform = this.displayObjectUpdateTransform; - - this._mask = null; - this.filterArea = null; - - // create our cached sprite - var cachedSprite = new core.Sprite(renderTexture); - - cachedSprite.transform.worldTransform = this.transform.worldTransform; - cachedSprite.anchor.x = -(bounds.x / bounds.width); - cachedSprite.anchor.y = -(bounds.y / bounds.height); - cachedSprite.alpha = cacheAlpha; - cachedSprite._bounds = this._bounds; - - // easy bounds.. - this._calculateBounds = this._calculateCachedBounds; - this.getLocalBounds = this._getCachedLocalBounds; - - this._cacheData.sprite = cachedSprite; - - this.transform._parentID = -1; - // restore the transform of the cached sprite to avoid the nasty flicker.. - if (!this.parent) { - this.parent = renderer._tempDisplayObjectParent; - this.updateTransform(); - this.parent = null; - } else { - this.updateTransform(); - } - - // map the hit test.. - this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); -}; - -/** - * Renders a cached version of the sprite with canvas - * - * @private - * @memberof PIXI.DisplayObject# - * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer - */ -DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { - if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { - return; - } - - this._initCachedDisplayObjectCanvas(renderer); - - this._cacheData.sprite.worldAlpha = this.worldAlpha; - - this._cacheData.sprite.renderCanvas(renderer); -}; - -// TODO this can be the same as the webGL verison.. will need to do a little tweaking first though.. -/** - * Prepares the Canvas renderer to cache the sprite - * - * @private - * @memberof PIXI.DisplayObject# - * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer - */ -DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { - if (this._cacheData && this._cacheData.sprite) { - return; - } - - // get bounds actually transforms the object for us already! - var bounds = this.getLocalBounds(); - - var cacheAlpha = this.alpha; - - this.alpha = 1; - - var cachedRenderTarget = renderer.context; - - var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); - - var textureCacheId = 'cacheAsBitmap_' + (0, _utils.uid)(); - - this._cacheData.textureCacheId = textureCacheId; - - _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); - _Texture2.default.addToCache(renderTexture, textureCacheId); - - // need to set // - var m = _tempMatrix; - - this.transform.localTransform.copy(m); - m.invert(); - - m.tx -= bounds.x; - m.ty -= bounds.y; - - // m.append(this.transform.worldTransform.) - // set all properties to there original so we can render to a texture - this.renderCanvas = this._cacheData.originalRenderCanvas; - - // renderTexture.render(this, m, true); - renderer.render(this, renderTexture, true, m, false); - - // now restore the state be setting the new properties - renderer.context = cachedRenderTarget; - - this.renderCanvas = this._renderCachedCanvas; - this._calculateBounds = this._calculateCachedBounds; - - this._mask = null; - this.filterArea = null; - - // create our cached sprite - var cachedSprite = new core.Sprite(renderTexture); - - cachedSprite.transform.worldTransform = this.transform.worldTransform; - cachedSprite.anchor.x = -(bounds.x / bounds.width); - cachedSprite.anchor.y = -(bounds.y / bounds.height); - cachedSprite._bounds = this._bounds; - cachedSprite.alpha = cacheAlpha; - - if (!this.parent) { - this.parent = renderer._tempDisplayObjectParent; - this.updateTransform(); - this.parent = null; - } else { - this.updateTransform(); - } - - this.updateTransform = this.displayObjectUpdateTransform; - - this._cacheData.sprite = cachedSprite; - - this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); -}; - -/** - * Calculates the bounds of the cached sprite - * - * @private - */ -DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { - this._cacheData.sprite._calculateBounds(); -}; - -/** - * Gets the bounds of the cached sprite. - * - * @private - * @return {Rectangle} The local bounds. - */ -DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { - return this._cacheData.sprite.getLocalBounds(); -}; - -/** - * Destroys the cached sprite. - * - * @private - */ -DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { - this._cacheData.sprite._texture.destroy(true); - this._cacheData.sprite = null; - - _BaseTexture2.default.removeFromCache(this._cacheData.textureCacheId); - _Texture2.default.removeFromCache(this._cacheData.textureCacheId); - - this._cacheData.textureCacheId = null; -}; - -/** - * Destroys the cached object. - * - * @private - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value. - * Used when destroying containers, see the Container.destroy method. - */ -DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) { - this.cacheAsBitmap = false; - this.destroy(options); -}; - -},{"../core":65,"../core/textures/BaseTexture":112,"../core/textures/Texture":115,"../core/utils":124}],139:[function(require,module,exports){ -'use strict'; - -var _core = require('../core'); - -var core = _interopRequireWildcard(_core); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -/** - * The instance name of the object. - * - * @memberof PIXI.DisplayObject# - * @member {string} - */ -core.DisplayObject.prototype.name = null; - -/** - * Returns the display object in the container - * - * @memberof PIXI.Container# - * @param {string} name - instance name - * @return {PIXI.DisplayObject} The child with the specified name. - */ -core.Container.prototype.getChildByName = function getChildByName(name) { - for (var i = 0; i < this.children.length; i++) { - if (this.children[i].name === name) { - return this.children[i]; - } - } - - return null; -}; - -},{"../core":65}],140:[function(require,module,exports){ -'use strict'; - -var _core = require('../core'); - -var core = _interopRequireWildcard(_core); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -/** - * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. - * - * @memberof PIXI.DisplayObject# - * @param {Point} point - the point to write the global value to. If null a new point will be returned - * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from - * being updated. This means the calculation returned MAY be out of date BUT will give you a - * nice performance boost - * @return {Point} The updated point - */ -core.DisplayObject.prototype.getGlobalPosition = function getGlobalPosition() { - var point = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new core.Point(); - var skipUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - - if (this.parent) { - this.parent.toGlobal(this.position, point, skipUpdate); - } else { - point.x = this.position.x; - point.y = this.position.y; - } - - return point; -}; - -},{"../core":65}],141:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.BitmapText = exports.TilingSpriteRenderer = exports.TilingSprite = exports.TextureTransform = exports.AnimatedSprite = undefined; - -var _AnimatedSprite = require('./AnimatedSprite'); - -Object.defineProperty(exports, 'AnimatedSprite', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_AnimatedSprite).default; - } -}); - -var _TextureTransform = require('./TextureTransform'); - -Object.defineProperty(exports, 'TextureTransform', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_TextureTransform).default; - } -}); - -var _TilingSprite = require('./TilingSprite'); - -Object.defineProperty(exports, 'TilingSprite', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_TilingSprite).default; - } -}); - -var _TilingSpriteRenderer = require('./webgl/TilingSpriteRenderer'); - -Object.defineProperty(exports, 'TilingSpriteRenderer', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_TilingSpriteRenderer).default; - } -}); - -var _BitmapText = require('./BitmapText'); - -Object.defineProperty(exports, 'BitmapText', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_BitmapText).default; - } -}); - -require('./cacheAsBitmap'); - -require('./getChildByName'); - -require('./getGlobalPosition'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// imported for side effect of extending the prototype only, contains no exports - -},{"./AnimatedSprite":134,"./BitmapText":135,"./TextureTransform":136,"./TilingSprite":137,"./cacheAsBitmap":138,"./getChildByName":139,"./getGlobalPosition":140,"./webgl/TilingSpriteRenderer":142}],142:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _core = require('../../core'); - -var core = _interopRequireWildcard(_core); - -var _const = require('../../core/const'); - -var _path = require('path'); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -var tempMat = new core.Matrix(); - -/** - * WebGL renderer plugin for tiling sprites - * - * @class - * @memberof PIXI.extras - * @extends PIXI.ObjectRenderer - */ - -var TilingSpriteRenderer = function (_core$ObjectRenderer) { - _inherits(TilingSpriteRenderer, _core$ObjectRenderer); - - /** - * constructor for renderer - * - * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. - */ - function TilingSpriteRenderer(renderer) { - _classCallCheck(this, TilingSpriteRenderer); - - var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); - - _this.shader = null; - _this.simpleShader = null; - _this.quad = null; - return _this; - } - - /** - * Sets up the renderer context and necessary buffers. - * - * @private - */ - - - TilingSpriteRenderer.prototype.onContextChange = function onContextChange() { - var gl = this.renderer.gl; - - this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n gl_FragColor = sample * uColor;\n}\n'); - this.simpleShader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = sample * uColor;\n}\n'); - - this.renderer.bindVao(null); - this.quad = new core.Quad(gl, this.renderer.state.attribState); - this.quad.initVao(this.shader); - }; - - /** - * - * @param {PIXI.extras.TilingSprite} ts tilingSprite to be rendered - */ - - - TilingSpriteRenderer.prototype.render = function render(ts) { - var renderer = this.renderer; - var quad = this.quad; - - renderer.bindVao(quad.vao); - - var vertices = quad.vertices; - - vertices[0] = vertices[6] = ts._width * -ts.anchor.x; - vertices[1] = vertices[3] = ts._height * -ts.anchor.y; - - vertices[2] = vertices[4] = ts._width * (1.0 - ts.anchor.x); - vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); - - if (ts.uvRespectAnchor) { - vertices = quad.uvs; - - vertices[0] = vertices[6] = -ts.anchor.x; - vertices[1] = vertices[3] = -ts.anchor.y; - - vertices[2] = vertices[4] = 1.0 - ts.anchor.x; - vertices[5] = vertices[7] = 1.0 - ts.anchor.y; - } - - quad.upload(); - - var tex = ts._texture; - var baseTex = tex.baseTexture; - var lt = ts.tileTransform.localTransform; - var uv = ts.uvTransform; - var isSimple = baseTex.isPowerOfTwo && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; - - // auto, force repeat wrapMode for big tiling textures - if (isSimple) { - if (!baseTex._glTextures[renderer.CONTEXT_UID]) { - if (baseTex.wrapMode === _const.WRAP_MODES.CLAMP) { - baseTex.wrapMode = _const.WRAP_MODES.REPEAT; - } - } else { - isSimple = baseTex.wrapMode !== _const.WRAP_MODES.CLAMP; - } - } - - var shader = isSimple ? this.simpleShader : this.shader; - - renderer.bindShader(shader); - - var w = tex.width; - var h = tex.height; - var W = ts._width; - var H = ts._height; - - tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); - - // that part is the same as above: - // tempMat.identity(); - // tempMat.scale(tex.width, tex.height); - // tempMat.prepend(lt); - // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); - - tempMat.invert(); - if (isSimple) { - tempMat.prepend(uv.mapCoord); - } else { - shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); - shader.uniforms.uClampFrame = uv.uClampFrame; - shader.uniforms.uClampOffset = uv.uClampOffset; - } - - shader.uniforms.uTransform = tempMat.toArray(true); - shader.uniforms.uColor = core.utils.premultiplyTintToRgba(ts.tint, ts.worldAlpha, shader.uniforms.uColor, baseTex.premultipliedAlpha); - shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); - - shader.uniforms.uSampler = renderer.bindTexture(tex); - - renderer.setBlendMode(core.utils.correctBlendMode(ts.blendMode, baseTex.premultipliedAlpha)); - - quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); - }; - - return TilingSpriteRenderer; -}(core.ObjectRenderer); - -exports.default = TilingSpriteRenderer; - - -core.WebGLRenderer.registerPlugin('tilingSprite', TilingSpriteRenderer); - -},{"../../core":65,"../../core/const":46,"path":23}],143:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _core = require('../../core'); - -var core = _interopRequireWildcard(_core); - -var _BlurXFilter = require('./BlurXFilter'); - -var _BlurXFilter2 = _interopRequireDefault(_BlurXFilter); - -var _BlurYFilter = require('./BlurYFilter'); - -var _BlurYFilter2 = _interopRequireDefault(_BlurYFilter); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * The BlurFilter applies a Gaussian blur to an object. - * The strength of the blur can be set for x- and y-axis separately. - * - * @class - * @extends PIXI.Filter - * @memberof PIXI.filters - */ -var BlurFilter = function (_core$Filter) { - _inherits(BlurFilter, _core$Filter); - - /** - * @param {number} strength - The strength of the blur filter. - * @param {number} quality - The quality of the blur filter. - * @param {number} resolution - The resolution of the blur filter. - * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. - */ - function BlurFilter(strength, quality, resolution, kernelSize) { - _classCallCheck(this, BlurFilter); - - var _this = _possibleConstructorReturn(this, _core$Filter.call(this)); - - _this.blurXFilter = new _BlurXFilter2.default(strength, quality, resolution, kernelSize); - _this.blurYFilter = new _BlurYFilter2.default(strength, quality, resolution, kernelSize); - - _this.padding = 0; - _this.resolution = resolution || core.settings.RESOLUTION; - _this.quality = quality || 4; - _this.blur = strength || 8; - return _this; - } - - /** - * Applies the filter. - * - * @param {PIXI.FilterManager} filterManager - The manager. - * @param {PIXI.RenderTarget} input - The input target. - * @param {PIXI.RenderTarget} output - The output target. - */ - - - BlurFilter.prototype.apply = function apply(filterManager, input, output) { - var renderTarget = filterManager.getRenderTarget(true); - - this.blurXFilter.apply(filterManager, input, renderTarget, true); - this.blurYFilter.apply(filterManager, renderTarget, output, false); - - filterManager.returnRenderTarget(renderTarget); - }; - - /** - * Sets the strength of both the blurX and blurY properties simultaneously - * - * @member {number} - * @default 2 - */ - - - _createClass(BlurFilter, [{ - key: 'blur', - get: function get() { - return this.blurXFilter.blur; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.blurXFilter.blur = this.blurYFilter.blur = value; - this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; - } - - /** - * Sets the number of passes for blur. More passes means higher quaility bluring. - * - * @member {number} - * @default 1 - */ - - }, { - key: 'quality', - get: function get() { - return this.blurXFilter.quality; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.blurXFilter.quality = this.blurYFilter.quality = value; - } - - /** - * Sets the strength of the blurX property - * - * @member {number} - * @default 2 - */ - - }, { - key: 'blurX', - get: function get() { - return this.blurXFilter.blur; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.blurXFilter.blur = value; - this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; - } - - /** - * Sets the strength of the blurY property - * - * @member {number} - * @default 2 - */ - - }, { - key: 'blurY', - get: function get() { - return this.blurYFilter.blur; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.blurYFilter.blur = value; - this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; - } - - /** - * Sets the blendmode of the filter - * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL - */ - - }, { - key: 'blendMode', - get: function get() { - return this.blurYFilter._blendMode; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.blurYFilter._blendMode = value; - } - }]); - - return BlurFilter; -}(core.Filter); - -exports.default = BlurFilter; - -},{"../../core":65,"./BlurXFilter":144,"./BlurYFilter":145}],144:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _core = require('../../core'); - -var core = _interopRequireWildcard(_core); - -var _generateBlurVertSource = require('./generateBlurVertSource'); - -var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); - -var _generateBlurFragSource = require('./generateBlurFragSource'); - -var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); - -var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); - -var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * The BlurXFilter applies a horizontal Gaussian blur to an object. - * - * @class - * @extends PIXI.Filter - * @memberof PIXI.filters - */ -var BlurXFilter = function (_core$Filter) { - _inherits(BlurXFilter, _core$Filter); - - /** - * @param {number} strength - The strength of the blur filter. - * @param {number} quality - The quality of the blur filter. - * @param {number} resolution - The resolution of the blur filter. - * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. - */ - function BlurXFilter(strength, quality, resolution, kernelSize) { - _classCallCheck(this, BlurXFilter); - - kernelSize = kernelSize || 5; - var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); - var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); - - var _this = _possibleConstructorReturn(this, _core$Filter.call(this, - // vertex shader - vertSrc, - // fragment shader - fragSrc)); - - _this.resolution = resolution || core.settings.RESOLUTION; - - _this._quality = 0; - - _this.quality = quality || 4; - _this.strength = strength || 8; - - _this.firstRun = true; - return _this; - } - - /** - * Applies the filter. - * - * @param {PIXI.FilterManager} filterManager - The manager. - * @param {PIXI.RenderTarget} input - The input target. - * @param {PIXI.RenderTarget} output - The output target. - * @param {boolean} clear - Should the output be cleared before rendering? - */ - - - BlurXFilter.prototype.apply = function apply(filterManager, input, output, clear) { - if (this.firstRun) { - var gl = filterManager.renderer.gl; - var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); - - this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); - this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); - - this.firstRun = false; - } - - this.uniforms.strength = 1 / output.size.width * (output.size.width / input.size.width); - - // screen space! - this.uniforms.strength *= this.strength; - this.uniforms.strength /= this.passes; // / this.passes//Math.pow(1, this.passes); - - if (this.passes === 1) { - filterManager.applyFilter(this, input, output, clear); - } else { - var renderTarget = filterManager.getRenderTarget(true); - var flip = input; - var flop = renderTarget; - - for (var i = 0; i < this.passes - 1; i++) { - filterManager.applyFilter(this, flip, flop, true); - - var temp = flop; - - flop = flip; - flip = temp; - } - - filterManager.applyFilter(this, flip, output, clear); - - filterManager.returnRenderTarget(renderTarget); - } - }; - - /** - * Sets the strength of both the blur. - * - * @member {number} - * @default 16 - */ - - - _createClass(BlurXFilter, [{ - key: 'blur', - get: function get() { - return this.strength; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.padding = Math.abs(value) * 2; - this.strength = value; - } - - /** - * Sets the quality of the blur by modifying the number of passes. More passes means higher - * quaility bluring but the lower the performance. - * - * @member {number} - * @default 4 - */ - - }, { - key: 'quality', - get: function get() { - return this._quality; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._quality = value; - this.passes = value; - } - }]); - - return BlurXFilter; -}(core.Filter); - -exports.default = BlurXFilter; - -},{"../../core":65,"./generateBlurFragSource":146,"./generateBlurVertSource":147,"./getMaxBlurKernelSize":148}],145:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _core = require('../../core'); - -var core = _interopRequireWildcard(_core); - -var _generateBlurVertSource = require('./generateBlurVertSource'); - -var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); - -var _generateBlurFragSource = require('./generateBlurFragSource'); - -var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); - -var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); - -var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * The BlurYFilter applies a horizontal Gaussian blur to an object. - * - * @class - * @extends PIXI.Filter - * @memberof PIXI.filters - */ -var BlurYFilter = function (_core$Filter) { - _inherits(BlurYFilter, _core$Filter); - - /** - * @param {number} strength - The strength of the blur filter. - * @param {number} quality - The quality of the blur filter. - * @param {number} resolution - The resolution of the blur filter. - * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. - */ - function BlurYFilter(strength, quality, resolution, kernelSize) { - _classCallCheck(this, BlurYFilter); - - kernelSize = kernelSize || 5; - var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); - var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); - - var _this = _possibleConstructorReturn(this, _core$Filter.call(this, - // vertex shader - vertSrc, - // fragment shader - fragSrc)); - - _this.resolution = resolution || core.settings.RESOLUTION; - - _this._quality = 0; - - _this.quality = quality || 4; - _this.strength = strength || 8; - - _this.firstRun = true; - return _this; - } - - /** - * Applies the filter. - * - * @param {PIXI.FilterManager} filterManager - The manager. - * @param {PIXI.RenderTarget} input - The input target. - * @param {PIXI.RenderTarget} output - The output target. - * @param {boolean} clear - Should the output be cleared before rendering? - */ - - - BlurYFilter.prototype.apply = function apply(filterManager, input, output, clear) { - if (this.firstRun) { - var gl = filterManager.renderer.gl; - var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); - - this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); - this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); - - this.firstRun = false; - } - - this.uniforms.strength = 1 / output.size.height * (output.size.height / input.size.height); - - this.uniforms.strength *= this.strength; - this.uniforms.strength /= this.passes; - - if (this.passes === 1) { - filterManager.applyFilter(this, input, output, clear); - } else { - var renderTarget = filterManager.getRenderTarget(true); - var flip = input; - var flop = renderTarget; - - for (var i = 0; i < this.passes - 1; i++) { - filterManager.applyFilter(this, flip, flop, true); - - var temp = flop; - - flop = flip; - flip = temp; - } - - filterManager.applyFilter(this, flip, output, clear); - - filterManager.returnRenderTarget(renderTarget); - } - }; - - /** - * Sets the strength of both the blur. - * - * @member {number} - * @default 2 - */ - - - _createClass(BlurYFilter, [{ - key: 'blur', - get: function get() { - return this.strength; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.padding = Math.abs(value) * 2; - this.strength = value; - } - - /** - * Sets the quality of the blur by modifying the number of passes. More passes means higher - * quaility bluring but the lower the performance. - * - * @member {number} - * @default 4 - */ - - }, { - key: 'quality', - get: function get() { - return this._quality; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._quality = value; - this.passes = value; - } - }]); - - return BlurYFilter; -}(core.Filter); - -exports.default = BlurYFilter; - -},{"../../core":65,"./generateBlurFragSource":146,"./generateBlurVertSource":147,"./getMaxBlurKernelSize":148}],146:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.default = generateFragBlurSource; -var GAUSSIAN_VALUES = { - 5: [0.153388, 0.221461, 0.250301], - 7: [0.071303, 0.131514, 0.189879, 0.214607], - 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], - 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], - 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], - 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448] -}; - -var fragTemplate = ['varying vec2 vBlurTexCoords[%size%];', 'uniform sampler2D uSampler;', 'void main(void)', '{', ' gl_FragColor = vec4(0.0);', ' %blur%', '}'].join('\n'); - -function generateFragBlurSource(kernelSize) { - var kernel = GAUSSIAN_VALUES[kernelSize]; - var halfLength = kernel.length; - - var fragSource = fragTemplate; - - var blurLoop = ''; - var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; - var value = void 0; - - for (var i = 0; i < kernelSize; i++) { - var blur = template.replace('%index%', i); - - value = i; - - if (i >= halfLength) { - value = kernelSize - i - 1; - } - - blur = blur.replace('%value%', kernel[value]); - - blurLoop += blur; - blurLoop += '\n'; - } - - fragSource = fragSource.replace('%blur%', blurLoop); - fragSource = fragSource.replace('%size%', kernelSize); - - return fragSource; -} - -},{}],147:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.default = generateVertBlurSource; -var vertTemplate = ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform float strength;', 'uniform mat3 projectionMatrix;', 'varying vec2 vBlurTexCoords[%size%];', 'void main(void)', '{', 'gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);', '%blur%', '}'].join('\n'); - -function generateVertBlurSource(kernelSize, x) { - var halfLength = Math.ceil(kernelSize / 2); - - var vertSource = vertTemplate; - - var blurLoop = ''; - var template = void 0; - // let value; - - if (x) { - template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);'; - } else { - template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);'; - } - - for (var i = 0; i < kernelSize; i++) { - var blur = template.replace('%index%', i); - - // value = i; - - // if(i >= halfLength) - // { - // value = kernelSize - i - 1; - // } - - blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + '.0'); - - blurLoop += blur; - blurLoop += '\n'; - } - - vertSource = vertSource.replace('%blur%', blurLoop); - vertSource = vertSource.replace('%size%', kernelSize); - - return vertSource; -} - -},{}],148:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.default = getMaxKernelSize; -function getMaxKernelSize(gl) { - var maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); - var kernelSize = 15; - - while (kernelSize > maxVaryings) { - kernelSize -= 2; - } - - return kernelSize; -} - -},{}],149:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _core = require('../../core'); - -var core = _interopRequireWildcard(_core); - -var _path = require('path'); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA - * color and alpha values of every pixel on your displayObject to produce a result - * with a new set of RGBA color and alpha values. It's pretty powerful! - * - * ```js - * let colorMatrix = new PIXI.ColorMatrixFilter(); - * container.filters = [colorMatrix]; - * colorMatrix.contrast(2); - * ``` - * @author Clément Chenebault - * @class - * @extends PIXI.Filter - * @memberof PIXI.filters - */ -var ColorMatrixFilter = function (_core$Filter) { - _inherits(ColorMatrixFilter, _core$Filter); - - /** - * - */ - function ColorMatrixFilter() { - _classCallCheck(this, ColorMatrixFilter); - - var _this = _possibleConstructorReturn(this, _core$Filter.call(this, - // vertex shader - 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', - // fragment shader - 'varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n')); - - _this.uniforms.m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; - - _this.alpha = 1; - return _this; - } - - /** - * Transforms current matrix and set the new one - * - * @param {number[]} matrix - 5x4 matrix - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - - - ColorMatrixFilter.prototype._loadMatrix = function _loadMatrix(matrix) { - var multiply = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - - var newMatrix = matrix; - - if (multiply) { - this._multiply(newMatrix, this.uniforms.m, matrix); - newMatrix = this._colorMatrix(newMatrix); - } - - // set the new matrix - this.uniforms.m = newMatrix; - }; - - /** - * Multiplies two mat5's - * - * @private - * @param {number[]} out - 5x4 matrix the receiving matrix - * @param {number[]} a - 5x4 matrix the first operand - * @param {number[]} b - 5x4 matrix the second operand - * @returns {number[]} 5x4 matrix - */ - - - ColorMatrixFilter.prototype._multiply = function _multiply(out, a, b) { - // Red Channel - out[0] = a[0] * b[0] + a[1] * b[5] + a[2] * b[10] + a[3] * b[15]; - out[1] = a[0] * b[1] + a[1] * b[6] + a[2] * b[11] + a[3] * b[16]; - out[2] = a[0] * b[2] + a[1] * b[7] + a[2] * b[12] + a[3] * b[17]; - out[3] = a[0] * b[3] + a[1] * b[8] + a[2] * b[13] + a[3] * b[18]; - out[4] = a[0] * b[4] + a[1] * b[9] + a[2] * b[14] + a[3] * b[19] + a[4]; - - // Green Channel - out[5] = a[5] * b[0] + a[6] * b[5] + a[7] * b[10] + a[8] * b[15]; - out[6] = a[5] * b[1] + a[6] * b[6] + a[7] * b[11] + a[8] * b[16]; - out[7] = a[5] * b[2] + a[6] * b[7] + a[7] * b[12] + a[8] * b[17]; - out[8] = a[5] * b[3] + a[6] * b[8] + a[7] * b[13] + a[8] * b[18]; - out[9] = a[5] * b[4] + a[6] * b[9] + a[7] * b[14] + a[8] * b[19] + a[9]; - - // Blue Channel - out[10] = a[10] * b[0] + a[11] * b[5] + a[12] * b[10] + a[13] * b[15]; - out[11] = a[10] * b[1] + a[11] * b[6] + a[12] * b[11] + a[13] * b[16]; - out[12] = a[10] * b[2] + a[11] * b[7] + a[12] * b[12] + a[13] * b[17]; - out[13] = a[10] * b[3] + a[11] * b[8] + a[12] * b[13] + a[13] * b[18]; - out[14] = a[10] * b[4] + a[11] * b[9] + a[12] * b[14] + a[13] * b[19] + a[14]; - - // Alpha Channel - out[15] = a[15] * b[0] + a[16] * b[5] + a[17] * b[10] + a[18] * b[15]; - out[16] = a[15] * b[1] + a[16] * b[6] + a[17] * b[11] + a[18] * b[16]; - out[17] = a[15] * b[2] + a[16] * b[7] + a[17] * b[12] + a[18] * b[17]; - out[18] = a[15] * b[3] + a[16] * b[8] + a[17] * b[13] + a[18] * b[18]; - out[19] = a[15] * b[4] + a[16] * b[9] + a[17] * b[14] + a[18] * b[19] + a[19]; - - return out; - }; - - /** - * Create a Float32 Array and normalize the offset component to 0-1 - * - * @private - * @param {number[]} matrix - 5x4 matrix - * @return {number[]} 5x4 matrix with all values between 0-1 - */ - - - ColorMatrixFilter.prototype._colorMatrix = function _colorMatrix(matrix) { - // Create a Float32 Array and normalize the offset component to 0-1 - var m = new Float32Array(matrix); - - m[4] /= 255; - m[9] /= 255; - m[14] /= 255; - m[19] /= 255; - - return m; - }; - - /** - * Adjusts brightness - * - * @param {number} b - value of the brigthness (0-1, where 0 is black) - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - - - ColorMatrixFilter.prototype.brightness = function brightness(b, multiply) { - var matrix = [b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, 1, 0]; - - this._loadMatrix(matrix, multiply); - }; - - /** - * Set the matrices in grey scales - * - * @param {number} scale - value of the grey (0-1, where 0 is black) - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - - - ColorMatrixFilter.prototype.greyscale = function greyscale(scale, multiply) { - var matrix = [scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, 0, 0, 0, 1, 0]; - - this._loadMatrix(matrix, multiply); - }; - - /** - * Set the black and white matrice. - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - - - ColorMatrixFilter.prototype.blackAndWhite = function blackAndWhite(multiply) { - var matrix = [0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0, 0, 0, 1, 0]; - - this._loadMatrix(matrix, multiply); - }; - - /** - * Set the hue property of the color - * - * @param {number} rotation - in degrees - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - - - ColorMatrixFilter.prototype.hue = function hue(rotation, multiply) { - rotation = (rotation || 0) / 180 * Math.PI; - - var cosR = Math.cos(rotation); - var sinR = Math.sin(rotation); - var sqrt = Math.sqrt; - - /* a good approximation for hue rotation - This matrix is far better than the versions with magic luminance constants - formerly used here, but also used in the starling framework (flash) and known from this - old part of the internet: quasimondo.com/archives/000565.php - This new matrix is based on rgb cube rotation in space. Look here for a more descriptive - implementation as a shader not a general matrix: - https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js - This is the source for the code: - see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 - */ - - var w = 1 / 3; - var sqrW = sqrt(w); // weight is - - var a00 = cosR + (1.0 - cosR) * w; - var a01 = w * (1.0 - cosR) - sqrW * sinR; - var a02 = w * (1.0 - cosR) + sqrW * sinR; - - var a10 = w * (1.0 - cosR) + sqrW * sinR; - var a11 = cosR + w * (1.0 - cosR); - var a12 = w * (1.0 - cosR) - sqrW * sinR; - - var a20 = w * (1.0 - cosR) - sqrW * sinR; - var a21 = w * (1.0 - cosR) + sqrW * sinR; - var a22 = cosR + w * (1.0 - cosR); - - var matrix = [a00, a01, a02, 0, 0, a10, a11, a12, 0, 0, a20, a21, a22, 0, 0, 0, 0, 0, 1, 0]; - - this._loadMatrix(matrix, multiply); - }; - - /** - * Set the contrast matrix, increase the separation between dark and bright - * Increase contrast : shadows darker and highlights brighter - * Decrease contrast : bring the shadows up and the highlights down - * - * @param {number} amount - value of the contrast (0-1) - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - - - ColorMatrixFilter.prototype.contrast = function contrast(amount, multiply) { - var v = (amount || 0) + 1; - var o = -0.5 * (v - 1); - - var matrix = [v, 0, 0, 0, o, 0, v, 0, 0, o, 0, 0, v, 0, o, 0, 0, 0, 1, 0]; - - this._loadMatrix(matrix, multiply); - }; - - /** - * Set the saturation matrix, increase the separation between colors - * Increase saturation : increase contrast, brightness, and sharpness - * - * @param {number} amount - The saturation amount (0-1) - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - - - ColorMatrixFilter.prototype.saturate = function saturate() { - var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - var multiply = arguments[1]; - - var x = amount * 2 / 3 + 1; - var y = (x - 1) * -0.5; - - var matrix = [x, y, y, 0, 0, y, x, y, 0, 0, y, y, x, 0, 0, 0, 0, 0, 1, 0]; - - this._loadMatrix(matrix, multiply); - }; - - /** - * Desaturate image (remove color) - * - * Call the saturate function - * - */ - - - ColorMatrixFilter.prototype.desaturate = function desaturate() // eslint-disable-line no-unused-vars - { - this.saturate(-1); - }; - - /** - * Negative image (inverse of classic rgb matrix) - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - - - ColorMatrixFilter.prototype.negative = function negative(multiply) { - var matrix = [0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0]; - - this._loadMatrix(matrix, multiply); - }; - - /** - * Sepia image - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - - - ColorMatrixFilter.prototype.sepia = function sepia(multiply) { - var matrix = [0.393, 0.7689999, 0.18899999, 0, 0, 0.349, 0.6859999, 0.16799999, 0, 0, 0.272, 0.5339999, 0.13099999, 0, 0, 0, 0, 0, 1, 0]; - - this._loadMatrix(matrix, multiply); - }; - - /** - * Color motion picture process invented in 1916 (thanks Dominic Szablewski) - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - - - ColorMatrixFilter.prototype.technicolor = function technicolor(multiply) { - var matrix = [1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, 0, 0, 0, 1, 0]; - - this._loadMatrix(matrix, multiply); - }; - - /** - * Polaroid filter - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - - - ColorMatrixFilter.prototype.polaroid = function polaroid(multiply) { - var matrix = [1.438, -0.062, -0.062, 0, 0, -0.122, 1.378, -0.122, 0, 0, -0.016, -0.016, 1.483, 0, 0, 0, 0, 0, 1, 0]; - - this._loadMatrix(matrix, multiply); - }; - - /** - * Filter who transforms : Red -> Blue and Blue -> Red - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - - - ColorMatrixFilter.prototype.toBGR = function toBGR(multiply) { - var matrix = [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0]; - - this._loadMatrix(matrix, multiply); - }; - - /** - * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - - - ColorMatrixFilter.prototype.kodachrome = function kodachrome(multiply) { - var matrix = [1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, 0, 0, 0, 1, 0]; - - this._loadMatrix(matrix, multiply); - }; - - /** - * Brown delicious browni filter (thanks Dominic Szablewski) - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - - - ColorMatrixFilter.prototype.browni = function browni(multiply) { - var matrix = [0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, 0, 0, 0, 1, 0]; - - this._loadMatrix(matrix, multiply); - }; - - /** - * Vintage filter (thanks Dominic Szablewski) - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - - - ColorMatrixFilter.prototype.vintage = function vintage(multiply) { - var matrix = [0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, 0, 0, 0, 1, 0]; - - this._loadMatrix(matrix, multiply); - }; - - /** - * We don't know exactly what it does, kind of gradient map, but funny to play with! - * - * @param {number} desaturation - Tone values. - * @param {number} toned - Tone values. - * @param {string} lightColor - Tone values, example: `0xFFE580` - * @param {string} darkColor - Tone values, example: `0xFFE580` - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - - - ColorMatrixFilter.prototype.colorTone = function colorTone(desaturation, toned, lightColor, darkColor, multiply) { - desaturation = desaturation || 0.2; - toned = toned || 0.15; - lightColor = lightColor || 0xFFE580; - darkColor = darkColor || 0x338000; - - var lR = (lightColor >> 16 & 0xFF) / 255; - var lG = (lightColor >> 8 & 0xFF) / 255; - var lB = (lightColor & 0xFF) / 255; - - var dR = (darkColor >> 16 & 0xFF) / 255; - var dG = (darkColor >> 8 & 0xFF) / 255; - var dB = (darkColor & 0xFF) / 255; - - var matrix = [0.3, 0.59, 0.11, 0, 0, lR, lG, lB, desaturation, 0, dR, dG, dB, toned, 0, lR - dR, lG - dG, lB - dB, 0, 0]; - - this._loadMatrix(matrix, multiply); - }; - - /** - * Night effect - * - * @param {number} intensity - The intensity of the night effect. - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - - - ColorMatrixFilter.prototype.night = function night(intensity, multiply) { - intensity = intensity || 0.1; - var matrix = [intensity * -2.0, -intensity, 0, 0, 0, -intensity, 0, intensity, 0, 0, 0, intensity, intensity * 2.0, 0, 0, 0, 0, 0, 1, 0]; - - this._loadMatrix(matrix, multiply); - }; - - /** - * Predator effect - * - * Erase the current matrix by setting a new indepent one - * - * @param {number} amount - how much the predator feels his future victim - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - - - ColorMatrixFilter.prototype.predator = function predator(amount, multiply) { - var matrix = [ - // row 1 - 11.224130630493164 * amount, -4.794486999511719 * amount, -2.8746118545532227 * amount, 0 * amount, 0.40342438220977783 * amount, - // row 2 - -3.6330697536468506 * amount, 9.193157196044922 * amount, -2.951810836791992 * amount, 0 * amount, -1.316135048866272 * amount, - // row 3 - -3.2184197902679443 * amount, -4.2375030517578125 * amount, 7.476448059082031 * amount, 0 * amount, 0.8044459223747253 * amount, - // row 4 - 0, 0, 0, 1, 0]; - - this._loadMatrix(matrix, multiply); - }; - - /** - * LSD effect - * - * Multiply the current matrix - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - - - ColorMatrixFilter.prototype.lsd = function lsd(multiply) { - var matrix = [2, -0.4, 0.5, 0, 0, -0.5, 2, -0.4, 0, 0, -0.4, -0.5, 3, 0, 0, 0, 0, 0, 1, 0]; - - this._loadMatrix(matrix, multiply); - }; - - /** - * Erase the current matrix by setting the default one - * - */ - - - ColorMatrixFilter.prototype.reset = function reset() { - var matrix = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; - - this._loadMatrix(matrix, false); - }; - - /** - * The matrix of the color matrix filter - * - * @member {number[]} - * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] - */ - - - _createClass(ColorMatrixFilter, [{ - key: 'matrix', - get: function get() { - return this.uniforms.m; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.uniforms.m = value; - } - - /** - * The opacity value to use when mixing the original and resultant colors. - * - * When the value is 0, the original color is used without modification. - * When the value is 1, the result color is used. - * When in the range (0, 1) the color is interpolated between the original and result by this amount. - * - * @member {number} - * @default 1 - */ - - }, { - key: 'alpha', - get: function get() { - return this.uniforms.uAlpha; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.uniforms.uAlpha = value; - } - }]); - - return ColorMatrixFilter; -}(core.Filter); - -// Americanized alias - - -exports.default = ColorMatrixFilter; -ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; - -},{"../../core":65,"path":23}],150:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _core = require('../../core'); - -var core = _interopRequireWildcard(_core); - -var _path = require('path'); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * The DisplacementFilter class uses the pixel values from the specified texture - * (called the displacement map) to perform a displacement of an object. You can - * use this filter to apply all manor of crazy warping effects. Currently the r - * property of the texture is used to offset the x and the g property of the texture - * is used to offset the y. - * - * @class - * @extends PIXI.Filter - * @memberof PIXI.filters - */ -var DisplacementFilter = function (_core$Filter) { - _inherits(DisplacementFilter, _core$Filter); - - /** - * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) - * @param {number} scale - The scale of the displacement - */ - function DisplacementFilter(sprite, scale) { - _classCallCheck(this, DisplacementFilter); - - var maskMatrix = new core.Matrix(); - - sprite.renderable = false; - - var _this = _possibleConstructorReturn(this, _core$Filter.call(this, - // vertex shader - 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\n vTextureCoord = aTextureCoord;\n}', - // fragment shader - 'varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\n\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy *= scale;\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\n}\n')); - - _this.maskSprite = sprite; - _this.maskMatrix = maskMatrix; - - _this.uniforms.mapSampler = sprite._texture; - _this.uniforms.filterMatrix = maskMatrix; - _this.uniforms.scale = { x: 1, y: 1 }; - - if (scale === null || scale === undefined) { - scale = 20; - } - - _this.scale = new core.Point(scale, scale); - return _this; - } - - /** - * Applies the filter. - * - * @param {PIXI.FilterManager} filterManager - The manager. - * @param {PIXI.RenderTarget} input - The input target. - * @param {PIXI.RenderTarget} output - The output target. - */ - - - DisplacementFilter.prototype.apply = function apply(filterManager, input, output) { - var ratio = 1 / output.destinationFrame.width * (output.size.width / input.size.width); - - this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); - this.uniforms.scale.x = this.scale.x * ratio; - this.uniforms.scale.y = this.scale.y * ratio; - - // draw the filter... - filterManager.applyFilter(this, input, output); - }; - - /** - * The texture used for the displacement map. Must be power of 2 sized texture. - * - * @member {PIXI.Texture} - */ - - - _createClass(DisplacementFilter, [{ - key: 'map', - get: function get() { - return this.uniforms.mapSampler; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.uniforms.mapSampler = value; - } - }]); - - return DisplacementFilter; -}(core.Filter); - -exports.default = DisplacementFilter; - -},{"../../core":65,"path":23}],151:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _core = require('../../core'); - -var core = _interopRequireWildcard(_core); - -var _path = require('path'); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * - * Basic FXAA implementation based on the code on geeks3d.com with the - * modification that the texture2DLod stuff was removed since it's - * unsupported by WebGL. - * - * @see https://github.com/mitsuhiko/webgl-meincraft - * - * @class - * @extends PIXI.Filter - * @memberof PIXI.filters - * - */ -var FXAAFilter = function (_core$Filter) { - _inherits(FXAAFilter, _core$Filter); - - /** - * - */ - function FXAAFilter() { - _classCallCheck(this, FXAAFilter); - - // TODO - needs work - return _possibleConstructorReturn(this, _core$Filter.call(this, - // vertex shader - '\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec4 filterArea;\n\nvarying vec2 vTextureCoord;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvoid texcoords(vec2 fragCoord, vec2 resolution,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n vec2 inverseVP = 1.0 / resolution.xy;\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}', - // fragment shader - 'varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it\'s\n unsupported by WebGL.\n \n --\n \n From:\n https://github.com/mitsuhiko/webgl-meincraft\n \n Copyright (c) 2011 by Armin Ronacher.\n \n Some rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n \n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n \n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n \n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n \n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n \n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n \n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n \n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n')); - } - - return FXAAFilter; -}(core.Filter); - -exports.default = FXAAFilter; - -},{"../../core":65,"path":23}],152:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _FXAAFilter = require('./fxaa/FXAAFilter'); - -Object.defineProperty(exports, 'FXAAFilter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_FXAAFilter).default; - } -}); - -var _NoiseFilter = require('./noise/NoiseFilter'); - -Object.defineProperty(exports, 'NoiseFilter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_NoiseFilter).default; - } -}); - -var _DisplacementFilter = require('./displacement/DisplacementFilter'); - -Object.defineProperty(exports, 'DisplacementFilter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_DisplacementFilter).default; - } -}); - -var _BlurFilter = require('./blur/BlurFilter'); - -Object.defineProperty(exports, 'BlurFilter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_BlurFilter).default; - } -}); - -var _BlurXFilter = require('./blur/BlurXFilter'); - -Object.defineProperty(exports, 'BlurXFilter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_BlurXFilter).default; - } -}); - -var _BlurYFilter = require('./blur/BlurYFilter'); - -Object.defineProperty(exports, 'BlurYFilter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_BlurYFilter).default; - } -}); - -var _ColorMatrixFilter = require('./colormatrix/ColorMatrixFilter'); - -Object.defineProperty(exports, 'ColorMatrixFilter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_ColorMatrixFilter).default; - } -}); - -var _VoidFilter = require('./void/VoidFilter'); - -Object.defineProperty(exports, 'VoidFilter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_VoidFilter).default; - } -}); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -},{"./blur/BlurFilter":143,"./blur/BlurXFilter":144,"./blur/BlurYFilter":145,"./colormatrix/ColorMatrixFilter":149,"./displacement/DisplacementFilter":150,"./fxaa/FXAAFilter":151,"./noise/NoiseFilter":153,"./void/VoidFilter":154}],153:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _core = require('../../core'); - -var core = _interopRequireWildcard(_core); - -var _path = require('path'); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * @author Vico @vicocotea - * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js - */ - -/** - * A Noise effect filter. - * - * @class - * @extends PIXI.Filter - * @memberof PIXI.filters - */ -var NoiseFilter = function (_core$Filter) { - _inherits(NoiseFilter, _core$Filter); - - /** - * @param {number} noise - The noise intensity, should be a normalized value in the range [0, 1]. - * @param {number} seed - A random seed for the noise generation. Default is `Math.random()`. - */ - function NoiseFilter() { - var noise = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0.5; - var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Math.random(); - - _classCallCheck(this, NoiseFilter); - - var _this = _possibleConstructorReturn(this, _core$Filter.call(this, - // vertex shader - 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', - // fragment shader - 'precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n')); - - _this.noise = noise; - _this.seed = seed; - return _this; - } - - /** - * The amount of noise to apply, this value should be in the range (0, 1]. - * - * @member {number} - * @default 0.5 - */ - - - _createClass(NoiseFilter, [{ - key: 'noise', - get: function get() { - return this.uniforms.uNoise; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.uniforms.uNoise = value; - } - - /** - * A seed value to apply to the random noise generation. `Math.random()` is a good value to use. - * - * @member {number} - */ - - }, { - key: 'seed', - get: function get() { - return this.uniforms.uSeed; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.uniforms.uSeed = value; - } - }]); - - return NoiseFilter; -}(core.Filter); - -exports.default = NoiseFilter; - -},{"../../core":65,"path":23}],154:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _core = require('../../core'); - -var core = _interopRequireWildcard(_core); - -var _path = require('path'); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * Does nothing. Very handy. - * - * @class - * @extends PIXI.Filter - * @memberof PIXI.filters - */ -var VoidFilter = function (_core$Filter) { - _inherits(VoidFilter, _core$Filter); - - /** - * - */ - function VoidFilter() { - _classCallCheck(this, VoidFilter); - - var _this = _possibleConstructorReturn(this, _core$Filter.call(this, - // vertex shader - 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', - // fragment shader - 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n')); - - _this.glShaderKey = 'void'; - return _this; - } - - return VoidFilter; -}(core.Filter); - -exports.default = VoidFilter; - -},{"../../core":65,"path":23}],155:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _core = require('../core'); - -var core = _interopRequireWildcard(_core); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * Holds all information related to an Interaction event - * - * @class - * @memberof PIXI.interaction - */ -var InteractionData = function () { - /** - * - */ - function InteractionData() { - _classCallCheck(this, InteractionData); - - /** - * This point stores the global coords of where the touch/mouse event happened - * - * @member {PIXI.Point} - */ - this.global = new core.Point(); - - /** - * The target DisplayObject that was interacted with - * - * @member {PIXI.DisplayObject} - */ - this.target = null; - - /** - * When passed to an event handler, this will be the original DOM Event that was captured - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent - * @see https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent - * @member {MouseEvent|TouchEvent|PointerEvent} - */ - this.originalEvent = null; - - /** - * Unique identifier for this interaction - * - * @member {number} - */ - this.identifier = null; - - /** - * Indicates whether or not the pointer device that created the event is the primary pointer. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary - * @type {Boolean} - */ - this.isPrimary = false; - - /** - * Indicates which button was pressed on the mouse or pointer device to trigger the event. - * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button - * @type {number} - */ - this.button = 0; - - /** - * Indicates which buttons are pressed on the mouse or pointer device when the event is triggered. - * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons - * @type {number} - */ - this.buttons = 0; - - /** - * The width of the pointer's contact along the x-axis, measured in CSS pixels. - * radiusX of TouchEvents will be represented by this value. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width - * @type {number} - */ - this.width = 0; - - /** - * The height of the pointer's contact along the y-axis, measured in CSS pixels. - * radiusY of TouchEvents will be represented by this value. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height - * @type {number} - */ - this.height = 0; - - /** - * The angle, in degrees, between the pointer device and the screen. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX - * @type {number} - */ - this.tiltX = 0; - - /** - * The angle, in degrees, between the pointer device and the screen. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY - * @type {number} - */ - this.tiltY = 0; - - /** - * The type of pointer that triggered the event. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType - * @type {string} - */ - this.pointerType = null; - - /** - * Pressure applied by the pointing device during the event. A Touch's force property - * will be represented by this value. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure - * @type {number} - */ - this.pressure = 0; - - /** - * From TouchEvents (not PointerEvents triggered by touches), the rotationAngle of the Touch. - * @see https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle - * @type {number} - */ - this.rotationAngle = 0; - - /** - * Twist of a stylus pointer. - * @see https://w3c.github.io/pointerevents/#pointerevent-interface - * @type {number} - */ - this.twist = 0; - - /** - * Barrel pressure on a stylus pointer. - * @see https://w3c.github.io/pointerevents/#pointerevent-interface - * @type {number} - */ - this.tangentialPressure = 0; - } - - /** - * The unique identifier of the pointer. It will be the same as `identifier`. - * @readonly - * @member {number} - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId - */ - - - /** - * This will return the local coordinates of the specified displayObject for this InteractionData - * - * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local - * coords off - * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise - * will create a new point) - * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional - * (otherwise will use the current global coords) - * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative - * to the DisplayObject - */ - InteractionData.prototype.getLocalPosition = function getLocalPosition(displayObject, point, globalPos) { - return displayObject.worldTransform.applyInverse(globalPos || this.global, point); - }; - - /** - * Copies properties from normalized event data. - * - * @param {Touch|MouseEvent|PointerEvent} event The normalized event data - * @private - */ - - - InteractionData.prototype._copyEvent = function _copyEvent(event) { - // isPrimary should only change on touchstart/pointerdown, so we don't want to overwrite - // it with "false" on later events when our shim for it on touch events might not be - // accurate - if (event.isPrimary) { - this.isPrimary = true; - } - this.button = event.button; - this.buttons = event.buttons; - this.width = event.width; - this.height = event.height; - this.tiltX = event.tiltX; - this.tiltY = event.tiltY; - this.pointerType = event.pointerType; - this.pressure = event.pressure; - this.rotationAngle = event.rotationAngle; - this.twist = event.twist || 0; - this.tangentialPressure = event.tangentialPressure || 0; - }; - - /** - * Resets the data for pooling. - * - * @private - */ - - - InteractionData.prototype._reset = function _reset() { - // isPrimary is the only property that we really need to reset - everything else is - // guaranteed to be overwritten - this.isPrimary = false; - }; - - _createClass(InteractionData, [{ - key: 'pointerId', - get: function get() { - return this.identifier; - } - }]); - - return InteractionData; -}(); - -exports.default = InteractionData; - -},{"../core":65}],156:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * Event class that mimics native DOM events. - * - * @class - * @memberof PIXI.interaction - */ -var InteractionEvent = function () { - /** - * - */ - function InteractionEvent() { - _classCallCheck(this, InteractionEvent); - - /** - * Whether this event will continue propagating in the tree - * - * @member {boolean} - */ - this.stopped = false; - - /** - * The object which caused this event to be dispatched. - * For listener callback see {@link PIXI.interaction.InteractionEvent.currentTarget}. - * - * @member {PIXI.DisplayObject} - */ - this.target = null; - - /** - * The object whose event listener’s callback is currently being invoked. - * - * @member {PIXI.DisplayObject} - */ - this.currentTarget = null; - - /** - * Type of the event - * - * @member {string} - */ - this.type = null; - - /** - * InteractionData related to this event - * - * @member {PIXI.interaction.InteractionData} - */ - this.data = null; - } - - /** - * Prevents event from reaching any objects other than the current object. - * - */ - - - InteractionEvent.prototype.stopPropagation = function stopPropagation() { - this.stopped = true; - }; - - /** - * Resets the event. - * - * @private - */ - - - InteractionEvent.prototype._reset = function _reset() { - this.stopped = false; - this.currentTarget = null; - this.target = null; - }; - - return InteractionEvent; -}(); - -exports.default = InteractionEvent; - -},{}],157:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -var _core = require('../core'); - -var core = _interopRequireWildcard(_core); - -var _InteractionData = require('./InteractionData'); - -var _InteractionData2 = _interopRequireDefault(_InteractionData); - -var _InteractionEvent = require('./InteractionEvent'); - -var _InteractionEvent2 = _interopRequireDefault(_InteractionEvent); - -var _InteractionTrackingData = require('./InteractionTrackingData'); - -var _InteractionTrackingData2 = _interopRequireDefault(_InteractionTrackingData); - -var _eventemitter = require('eventemitter3'); - -var _eventemitter2 = _interopRequireDefault(_eventemitter); - -var _interactiveTarget = require('./interactiveTarget'); - -var _interactiveTarget2 = _interopRequireDefault(_interactiveTarget); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -// Mix interactiveTarget into core.DisplayObject.prototype, after deprecation has been handled -core.utils.mixins.delayMixin(core.DisplayObject.prototype, _interactiveTarget2.default); - -var MOUSE_POINTER_ID = 'MOUSE'; - -// helpers for hitTest() - only used inside hitTest() -var hitTestEvent = { - target: null, - data: { - global: null - } -}; - -/** - * The interaction manager deals with mouse, touch and pointer events. Any DisplayObject can be interactive - * if its interactive parameter is set to true - * This manager also supports multitouch. - * - * An instance of this class is automatically created by default, and can be found at renderer.plugins.interaction - * - * @class - * @extends EventEmitter - * @memberof PIXI.interaction - */ - -var InteractionManager = function (_EventEmitter) { - _inherits(InteractionManager, _EventEmitter); - - /** - * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer - * @param {object} [options] - The options for the manager. - * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. - * @param {number} [options.interactionFrequency=10] - Frequency increases the interaction events will be checked. - */ - function InteractionManager(renderer, options) { - _classCallCheck(this, InteractionManager); - - var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); - - options = options || {}; - - /** - * The renderer this interaction manager works for. - * - * @member {PIXI.SystemRenderer} - */ - _this.renderer = renderer; - - /** - * Should default browser actions automatically be prevented. - * Does not apply to pointer events for backwards compatibility - * preventDefault on pointer events stops mouse events from firing - * Thus, for every pointer event, there will always be either a mouse of touch event alongside it. - * - * @member {boolean} - * @default true - */ - _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; - - /** - * Frequency in milliseconds that the mousemove, moveover & mouseout interaction events will be checked. - * - * @member {number} - * @default 10 - */ - _this.interactionFrequency = options.interactionFrequency || 10; - - /** - * The mouse data - * - * @member {PIXI.interaction.InteractionData} - */ - _this.mouse = new _InteractionData2.default(); - _this.mouse.identifier = MOUSE_POINTER_ID; - - // setting the mouse to start off far off screen will mean that mouse over does - // not get called before we even move the mouse. - _this.mouse.global.set(-999999); - - /** - * Actively tracked InteractionData - * - * @private - * @member {Object.} - */ - _this.activeInteractionData = {}; - _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse; - - /** - * Pool of unused InteractionData - * - * @private - * @member {PIXI.interation.InteractionData[]} - */ - _this.interactionDataPool = []; - - /** - * An event data object to handle all the event tracking/dispatching - * - * @member {object} - */ - _this.eventData = new _InteractionEvent2.default(); - - /** - * The DOM element to bind to. - * - * @private - * @member {HTMLElement} - */ - _this.interactionDOMElement = null; - - /** - * This property determines if mousemove and touchmove events are fired only when the cursor - * is over the object. - * Setting to true will make things work more in line with how the DOM verison works. - * Setting to false can make things easier for things like dragging - * It is currently set to false as this is how PixiJS used to work. This will be set to true in - * future versions of pixi. - * - * @member {boolean} - * @default false - */ - _this.moveWhenInside = false; - - /** - * Have events been attached to the dom element? - * - * @private - * @member {boolean} - */ - _this.eventsAdded = false; - - /** - * Is the mouse hovering over the renderer? - * - * @private - * @member {boolean} - */ - _this.mouseOverRenderer = false; - - /** - * Does the device support touch events - * https://www.w3.org/TR/touch-events/ - * - * @readonly - * @member {boolean} - */ - _this.supportsTouchEvents = 'ontouchstart' in window; - - /** - * Does the device support pointer events - * https://www.w3.org/Submission/pointer-events/ - * - * @readonly - * @member {boolean} - */ - _this.supportsPointerEvents = !!window.PointerEvent; - - // this will make it so that you don't have to call bind all the time - - /** - * @private - * @member {Function} - */ - _this.onPointerUp = _this.onPointerUp.bind(_this); - _this.processPointerUp = _this.processPointerUp.bind(_this); - - /** - * @private - * @member {Function} - */ - _this.onPointerCancel = _this.onPointerCancel.bind(_this); - _this.processPointerCancel = _this.processPointerCancel.bind(_this); - - /** - * @private - * @member {Function} - */ - _this.onPointerDown = _this.onPointerDown.bind(_this); - _this.processPointerDown = _this.processPointerDown.bind(_this); - - /** - * @private - * @member {Function} - */ - _this.onPointerMove = _this.onPointerMove.bind(_this); - _this.processPointerMove = _this.processPointerMove.bind(_this); - - /** - * @private - * @member {Function} - */ - _this.onPointerOut = _this.onPointerOut.bind(_this); - _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); - - /** - * @private - * @member {Function} - */ - _this.onPointerOver = _this.onPointerOver.bind(_this); - - /** - * Dictionary of how different cursor modes are handled. Strings are handled as CSS cursor - * values, objects are handled as dictionaries of CSS values for interactionDOMElement, - * and functions are called instead of changing the CSS. - * Default CSS cursor values are provided for 'default' and 'pointer' modes. - * @member {Object.)>} - */ - _this.cursorStyles = { - default: 'inherit', - pointer: 'pointer' - }; - - /** - * The mode of the cursor that is being used. - * The value of this is a key from the cursorStyles dictionary. - * - * @member {string} - */ - _this.currentCursorMode = null; - - /** - * Internal cached let. - * - * @private - * @member {string} - */ - _this.cursor = null; - - /** - * Internal cached let. - * - * @private - * @member {PIXI.Point} - */ - _this._tempPoint = new core.Point(); - - /** - * The current resolution / device pixel ratio. - * - * @member {number} - * @default 1 - */ - _this.resolution = 1; - - _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); - - /** - * Fired when a pointer device button (usually a mouse left-button) is pressed on the display - * object. - * - * @event PIXI.interaction.InteractionManager#mousedown - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is pressed - * on the display object. - * - * @event PIXI.interaction.InteractionManager#rightdown - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button (usually a mouse left-button) is released over the display - * object. - * - * @event PIXI.interaction.InteractionManager#mouseup - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is released - * over the display object. - * - * @event PIXI.interaction.InteractionManager#rightup - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button (usually a mouse left-button) is pressed and released on - * the display object. - * - * @event PIXI.interaction.InteractionManager#click - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is pressed - * and released on the display object. - * - * @event PIXI.interaction.InteractionManager#rightclick - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button (usually a mouse left-button) is released outside the - * display object that initially registered a - * [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}. - * - * @event PIXI.interaction.InteractionManager#mouseupoutside - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is released - * outside the display object that initially registered a - * [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}. - * - * @event PIXI.interaction.InteractionManager#rightupoutside - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device (usually a mouse) is moved while over the display object - * - * @event PIXI.interaction.InteractionManager#mousemove - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device (usually a mouse) is moved onto the display object - * - * @event PIXI.interaction.InteractionManager#mouseover - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device (usually a mouse) is moved off the display object - * - * @event PIXI.interaction.InteractionManager#mouseout - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button is pressed on the display object. - * - * @event PIXI.interaction.InteractionManager#pointerdown - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button is released over the display object. - * - * @event PIXI.interaction.InteractionManager#pointerup - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when the operating system cancels a pointer event - * - * @event PIXI.interaction.InteractionManager#pointercancel - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button is pressed and released on the display object. - * - * @event PIXI.interaction.InteractionManager#pointertap - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button is released outside the display object that initially - * registered a [pointerdown]{@link PIXI.interaction.InteractionManager#event:pointerdown}. - * - * @event PIXI.interaction.InteractionManager#pointerupoutside - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device is moved while over the display object - * - * @event PIXI.interaction.InteractionManager#pointermove - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device is moved onto the display object - * - * @event PIXI.interaction.InteractionManager#pointerover - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device is moved off the display object - * - * @event PIXI.interaction.InteractionManager#pointerout - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a touch point is placed on the display object. - * - * @event PIXI.interaction.InteractionManager#touchstart - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a touch point is removed from the display object. - * - * @event PIXI.interaction.InteractionManager#touchend - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when the operating system cancels a touch - * - * @event PIXI.interaction.InteractionManager#touchcancel - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a touch point is placed and removed from the display object. - * - * @event PIXI.interaction.InteractionManager#tap - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a touch point is removed outside of the display object that initially - * registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}. - * - * @event PIXI.interaction.InteractionManager#touchendoutside - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a touch point is moved along the display object. - * - * @event PIXI.interaction.InteractionManager#touchmove - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button (usually a mouse left-button) is pressed on the display. - * object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#mousedown - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is pressed - * on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#rightdown - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button (usually a mouse left-button) is released over the display - * object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#mouseup - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is released - * over the display object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#rightup - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button (usually a mouse left-button) is pressed and released on - * the display object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#click - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is pressed - * and released on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#rightclick - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button (usually a mouse left-button) is released outside the - * display object that initially registered a - * [mousedown]{@link PIXI.DisplayObject#event:mousedown}. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#mouseupoutside - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is released - * outside the display object that initially registered a - * [rightdown]{@link PIXI.DisplayObject#event:rightdown}. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#rightupoutside - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device (usually a mouse) is moved while over the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#mousemove - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device (usually a mouse) is moved onto the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#mouseover - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device (usually a mouse) is moved off the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#mouseout - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button is pressed on the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointerdown - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button is released over the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointerup - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when the operating system cancels a pointer event. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointercancel - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button is pressed and released on the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointertap - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button is released outside the display object that initially - * registered a [pointerdown]{@link PIXI.DisplayObject#event:pointerdown}. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointerupoutside - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device is moved while over the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointermove - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device is moved onto the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointerover - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device is moved off the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointerout - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a touch point is placed on the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#touchstart - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a touch point is removed from the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#touchend - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when the operating system cancels a touch. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#touchcancel - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a touch point is placed and removed from the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#tap - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a touch point is removed outside of the display object that initially - * registered a [touchstart]{@link PIXI.DisplayObject#event:touchstart}. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#touchendoutside - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a touch point is moved along the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#touchmove - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - return _this; - } - - /** - * Hit tests a point against the display tree, returning the first interactive object that is hit. - * - * @param {PIXI.Point} globalPoint - A point to hit test with, in global space. - * @param {PIXI.Container} [root] - The root display object to start from. If omitted, defaults - * to the last rendered root of the associated renderer. - * @return {PIXI.DisplayObject} The hit display object, if any. - */ - - - InteractionManager.prototype.hitTest = function hitTest(globalPoint, root) { - // clear the target for our hit test - hitTestEvent.target = null; - // assign the global point - hitTestEvent.data.global = globalPoint; - // ensure safety of the root - if (!root) { - root = this.renderer._lastObjectRendered; - } - // run the hit test - this.processInteractive(hitTestEvent, root, null, true); - // return our found object - it'll be null if we didn't hit anything - - return hitTestEvent.target; - }; - - /** - * Sets the DOM element which will receive mouse/touch events. This is useful for when you have - * other DOM elements on top of the renderers Canvas element. With this you'll be bale to deletegate - * another DOM element to receive those events. - * - * @param {HTMLCanvasElement} element - the DOM element which will receive mouse and touch events. - * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas). - * @private - */ - - - InteractionManager.prototype.setTargetElement = function setTargetElement(element) { - var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; - - this.removeEvents(); - - this.interactionDOMElement = element; - - this.resolution = resolution; - - this.addEvents(); - }; - - /** - * Registers all the DOM events - * - * @private - */ - - - InteractionManager.prototype.addEvents = function addEvents() { - if (!this.interactionDOMElement) { - return; - } - - core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.INTERACTION); - - if (window.navigator.msPointerEnabled) { - this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; - this.interactionDOMElement.style['-ms-touch-action'] = 'none'; - } else if (this.supportsPointerEvents) { - this.interactionDOMElement.style['touch-action'] = 'none'; - } - - /** - * These events are added first, so that if pointer events are normalised, they are fired - * in the same order as non-normalised events. ie. pointer event 1st, mouse / touch 2nd - */ - if (this.supportsPointerEvents) { - window.document.addEventListener('pointermove', this.onPointerMove, true); - this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, true); - // pointerout is fired in addition to pointerup (for touch events) and pointercancel - // we already handle those, so for the purposes of what we do in onPointerOut, we only - // care about the pointerleave event - this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, true); - this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, true); - window.addEventListener('pointercancel', this.onPointerCancel, true); - window.addEventListener('pointerup', this.onPointerUp, true); - } else { - window.document.addEventListener('mousemove', this.onPointerMove, true); - this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, true); - this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, true); - this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, true); - window.addEventListener('mouseup', this.onPointerUp, true); - } - - // always look directly for touch events so that we can provide original data - // In a future version we should change this to being just a fallback and rely solely on - // PointerEvents whenever available - if (this.supportsTouchEvents) { - this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, true); - this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, true); - this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, true); - this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, true); - } - - this.eventsAdded = true; - }; - - /** - * Removes all the DOM events that were previously registered - * - * @private - */ - - - InteractionManager.prototype.removeEvents = function removeEvents() { - if (!this.interactionDOMElement) { - return; - } - - core.ticker.shared.remove(this.update, this); - - if (window.navigator.msPointerEnabled) { - this.interactionDOMElement.style['-ms-content-zooming'] = ''; - this.interactionDOMElement.style['-ms-touch-action'] = ''; - } else if (this.supportsPointerEvents) { - this.interactionDOMElement.style['touch-action'] = ''; - } - - if (this.supportsPointerEvents) { - window.document.removeEventListener('pointermove', this.onPointerMove, true); - this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, true); - this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, true); - this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, true); - window.removeEventListener('pointercancel', this.onPointerCancel, true); - window.removeEventListener('pointerup', this.onPointerUp, true); - } else { - window.document.removeEventListener('mousemove', this.onPointerMove, true); - this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, true); - this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, true); - this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, true); - window.removeEventListener('mouseup', this.onPointerUp, true); - } - - if (this.supportsTouchEvents) { - this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, true); - this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, true); - this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, true); - this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, true); - } - - this.interactionDOMElement = null; - - this.eventsAdded = false; - }; - - /** - * Updates the state of interactive objects. - * Invoked by a throttled ticker update from {@link PIXI.ticker.shared}. - * - * @param {number} deltaTime - time delta since last tick - */ - - - InteractionManager.prototype.update = function update(deltaTime) { - this._deltaTime += deltaTime; - - if (this._deltaTime < this.interactionFrequency) { - return; - } - - this._deltaTime = 0; - - if (!this.interactionDOMElement) { - return; - } - - // if the user move the mouse this check has already been done using the mouse move! - if (this.didMove) { - this.didMove = false; - - return; - } - - this.cursor = null; - - // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, - // but there was a scenario of a display object moving under a static mouse cursor. - // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function - for (var k in this.activeInteractionData) { - // eslint-disable-next-line no-prototype-builtins - if (this.activeInteractionData.hasOwnProperty(k)) { - var interactionData = this.activeInteractionData[k]; - - if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData); - - this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, true); - } - } - } - - this.setCursorMode(this.cursor); - - // TODO - }; - - /** - * Sets the current cursor mode, handling any callbacks or CSS style changes. - * - * @param {string} mode - cursor mode, a key from the cursorStyles dictionary - */ - - - InteractionManager.prototype.setCursorMode = function setCursorMode(mode) { - mode = mode || 'default'; - // if the mode didn't actually change, bail early - if (this.currentCursorMode === mode) { - return; - } - this.currentCursorMode = mode; - var style = this.cursorStyles[mode]; - - // only do things if there is a cursor style for it - if (style) { - switch (typeof style === 'undefined' ? 'undefined' : _typeof(style)) { - case 'string': - // string styles are handled as cursor CSS - this.interactionDOMElement.style.cursor = style; - break; - case 'function': - // functions are just called, and passed the cursor mode - style(mode); - break; - case 'object': - // if it is an object, assume that it is a dictionary of CSS styles, - // apply it to the interactionDOMElement - Object.assign(this.interactionDOMElement.style, style); - break; - } - } else if (typeof mode === 'string' && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) { - // if it mode is a string (not a Symbol) and cursorStyles doesn't have any entry - // for the mode, then assume that the dev wants it to be CSS for the cursor. - this.interactionDOMElement.style.cursor = mode; - } - }; - - /** - * Dispatches an event on the display object that was interacted with - * - * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the display object in question - * @param {string} eventString - the name of the event (e.g, mousedown) - * @param {object} eventData - the event data object - * @private - */ - - - InteractionManager.prototype.dispatchEvent = function dispatchEvent(displayObject, eventString, eventData) { - if (!eventData.stopped) { - eventData.currentTarget = displayObject; - eventData.type = eventString; - - displayObject.emit(eventString, eventData); - - if (displayObject[eventString]) { - displayObject[eventString](eventData); - } - } - }; - - /** - * Maps x and y coords from a DOM object and maps them correctly to the PixiJS view. The - * resulting value is stored in the point. This takes into account the fact that the DOM - * element could be scaled and positioned anywhere on the screen. - * - * @param {PIXI.Point} point - the point that the result will be stored in - * @param {number} x - the x coord of the position to map - * @param {number} y - the y coord of the position to map - */ - - - InteractionManager.prototype.mapPositionToPoint = function mapPositionToPoint(point, x, y) { - var rect = void 0; - - // IE 11 fix - if (!this.interactionDOMElement.parentElement) { - rect = { x: 0, y: 0, width: 0, height: 0 }; - } else { - rect = this.interactionDOMElement.getBoundingClientRect(); - } - - var resolutionMultiplier = navigator.isCocoonJS ? this.resolution : 1.0 / this.resolution; - - point.x = (x - rect.left) * (this.interactionDOMElement.width / rect.width) * resolutionMultiplier; - point.y = (y - rect.top) * (this.interactionDOMElement.height / rect.height) * resolutionMultiplier; - }; - - /** - * This function is provides a neat way of crawling through the scene graph and running a - * specified function on all interactive objects it finds. It will also take care of hit - * testing the interactive objects and passes the hit across in the function. - * - * @private - * @param {PIXI.interaction.InteractionEvent} interactionEvent - event containing the point that - * is tested for collision - * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the displayObject - * that will be hit test (recursively crawls its children) - * @param {Function} [func] - the function that will be called on each interactive object. The - * interactionEvent, displayObject and hit will be passed to the function - * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point - * @param {boolean} [interactive] - Whether the displayObject is interactive - * @return {boolean} returns true if the displayObject hit the point - */ - - - InteractionManager.prototype.processInteractive = function processInteractive(interactionEvent, displayObject, func, hitTest, interactive) { - if (!displayObject || !displayObject.visible) { - return false; - } - - var point = interactionEvent.data.global; - - // Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^ - // - // This function will now loop through all objects and then only hit test the objects it HAS - // to, not all of them. MUCH faster.. - // An object will be hit test if the following is true: - // - // 1: It is interactive. - // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. - // - // As another little optimisation once an interactive object has been hit we can carry on - // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests - // A final optimisation is that an object is not hit test directly if a child has already been hit. - - interactive = displayObject.interactive || interactive; - - var hit = false; - var interactiveParent = interactive; - - // if the displayobject has a hitArea, then it does not need to hitTest children. - if (displayObject.hitArea) { - interactiveParent = false; - } - // it has a mask! Then lets hit test that before continuing - else if (hitTest && displayObject._mask) { - if (!displayObject._mask.containsPoint(point)) { - hitTest = false; - } - } - - // ** FREE TIP **! If an object is not interactive or has no buttons in it - // (such as a game scene!) set interactiveChildren to false for that displayObject. - // This will allow PixiJS to completely ignore and bypass checking the displayObjects children. - if (displayObject.interactiveChildren && displayObject.children) { - var children = displayObject.children; - - for (var i = children.length - 1; i >= 0; i--) { - var child = children[i]; - - // time to get recursive.. if this function will return if something is hit.. - var childHit = this.processInteractive(interactionEvent, child, func, hitTest, interactiveParent); - - if (childHit) { - // 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 (!child.parent) { - continue; - } - - // we no longer need to hit test any more objects in this container as we we - // now know the parent has been hit - interactiveParent = false; - - // If the child is interactive , that means that the object hit was actually - // interactive and not just the child of an interactive object. - // This means we no longer need to hit test anything else. We still need to run - // through all objects, but we don't need to perform any hit tests. - - if (childHit) { - if (interactionEvent.target) { - hitTest = false; - } - hit = true; - } - } - } - } - - // no point running this if the item is not interactive or does not have an interactive parent. - if (interactive) { - // if we are hit testing (as in we have no hit any objects yet) - // We also don't need to worry about hit testing if once of the displayObjects children - // has already been hit - but only if it was interactive, otherwise we need to keep - // looking for an interactive child, just in case we hit one - if (hitTest && !interactionEvent.target) { - if (displayObject.hitArea) { - displayObject.worldTransform.applyInverse(point, this._tempPoint); - if (displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { - hit = true; - } - } else if (displayObject.containsPoint) { - if (displayObject.containsPoint(point)) { - hit = true; - } - } - } - - if (displayObject.interactive) { - if (hit && !interactionEvent.target) { - interactionEvent.target = displayObject; - } - - if (func) { - func(interactionEvent, displayObject, !!hit); - } - } - } - - return hit; - }; - - /** - * Is called when the pointer button is pressed down on the renderer element - * - * @private - * @param {PointerEvent} originalEvent - The DOM event of a pointer button being pressed down - */ - - - InteractionManager.prototype.onPointerDown = function onPointerDown(originalEvent) { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; - - var events = this.normalizeToPointerData(originalEvent); - - /** - * No need to prevent default on natural pointer events, as there are no side effects - * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, - * so still need to be prevented. - */ - - // Guaranteed that there will be at least one event in events, and all events must have the same pointer type - - if (this.autoPreventDefault && events[0].isNormalized) { - originalEvent.preventDefault(); - } - - var eventLen = events.length; - - for (var i = 0; i < eventLen; i++) { - var event = events[i]; - - var interactionData = this.getInteractionDataForPointerId(event); - - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); - - interactionEvent.data.originalEvent = originalEvent; - - this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerDown, true); - - this.emit('pointerdown', interactionEvent); - if (event.pointerType === 'touch') { - this.emit('touchstart', interactionEvent); - } - // emit a mouse event for "pen" pointers, the way a browser would emit a fallback event - else if (event.pointerType === 'mouse' || event.pointerType === 'pen') { - var isRightButton = event.button === 2; - - this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); - } - } - }; - - /** - * Processes the result of the pointer down check and dispatches the event if need be - * - * @private - * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event - * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested - * @param {boolean} hit - the result of the hit test on the display object - */ - - - InteractionManager.prototype.processPointerDown = function processPointerDown(interactionEvent, displayObject, hit) { - var data = interactionEvent.data; - var id = interactionEvent.data.identifier; - - if (hit) { - if (!displayObject.trackedPointers[id]) { - displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); - } - this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); - - if (data.pointerType === 'touch') { - this.dispatchEvent(displayObject, 'touchstart', interactionEvent); - } else if (data.pointerType === 'mouse' || data.pointerType === 'pen') { - var isRightButton = data.button === 2; - - if (isRightButton) { - displayObject.trackedPointers[id].rightDown = true; - } else { - displayObject.trackedPointers[id].leftDown = true; - } - - this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); - } - } - }; - - /** - * Is called when the pointer button is released on the renderer element - * - * @private - * @param {PointerEvent} originalEvent - The DOM event of a pointer button being released - * @param {boolean} cancelled - true if the pointer is cancelled - * @param {Function} func - Function passed to {@link processInteractive} - */ - - - InteractionManager.prototype.onPointerComplete = function onPointerComplete(originalEvent, cancelled, func) { - var events = this.normalizeToPointerData(originalEvent); - - var eventLen = events.length; - - // if the event wasn't targeting our canvas, then consider it to be pointerupoutside - // in all cases (unless it was a pointercancel) - var eventAppend = originalEvent.target !== this.interactionDOMElement ? 'outside' : ''; - - for (var i = 0; i < eventLen; i++) { - var event = events[i]; - - var interactionData = this.getInteractionDataForPointerId(event); - - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); - - interactionEvent.data.originalEvent = originalEvent; - - // perform hit testing for events targeting our canvas or cancel events - this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, func, cancelled || !eventAppend); - - this.emit(cancelled ? 'pointercancel' : 'pointerup' + eventAppend, interactionEvent); - - if (event.pointerType === 'mouse' || event.pointerType === 'pen') { - var isRightButton = event.button === 2; - - this.emit(isRightButton ? 'rightup' + eventAppend : 'mouseup' + eventAppend, interactionEvent); - } else if (event.pointerType === 'touch') { - this.emit(cancelled ? 'touchcancel' : 'touchend' + eventAppend, interactionEvent); - this.releaseInteractionDataForPointerId(event.pointerId, interactionData); - } - } - }; - - /** - * Is called when the pointer button is cancelled - * - * @private - * @param {PointerEvent} event - The DOM event of a pointer button being released - */ - - - InteractionManager.prototype.onPointerCancel = function onPointerCancel(event) { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && event.pointerType === 'touch') return; - - this.onPointerComplete(event, true, this.processPointerCancel); - }; - - /** - * Processes the result of the pointer cancel check and dispatches the event if need be - * - * @private - * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event - * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested - */ - - - InteractionManager.prototype.processPointerCancel = function processPointerCancel(interactionEvent, displayObject) { - var data = interactionEvent.data; - - var id = interactionEvent.data.identifier; - - if (displayObject.trackedPointers[id] !== undefined) { - delete displayObject.trackedPointers[id]; - this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); - - if (data.pointerType === 'touch') { - this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); - } - } - }; - - /** - * Is called when the pointer button is released on the renderer element - * - * @private - * @param {PointerEvent} event - The DOM event of a pointer button being released - */ - - - InteractionManager.prototype.onPointerUp = function onPointerUp(event) { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && event.pointerType === 'touch') return; - - this.onPointerComplete(event, false, this.processPointerUp); - }; - - /** - * Processes the result of the pointer up check and dispatches the event if need be - * - * @private - * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event - * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested - * @param {boolean} hit - the result of the hit test on the display object - */ - - - InteractionManager.prototype.processPointerUp = function processPointerUp(interactionEvent, displayObject, hit) { - var data = interactionEvent.data; - - var id = interactionEvent.data.identifier; - - var trackingData = displayObject.trackedPointers[id]; - - var isTouch = data.pointerType === 'touch'; - - var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; - - // Mouse only - if (isMouse) { - var isRightButton = data.button === 2; - - var flags = _InteractionTrackingData2.default.FLAGS; - - var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; - - var isDown = trackingData !== undefined && trackingData.flags & test; - - if (hit) { - this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); - - if (isDown) { - this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); - } - } else if (isDown) { - this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); - } - // update the down state of the tracking data - if (trackingData) { - if (isRightButton) { - trackingData.rightDown = false; - } else { - trackingData.leftDown = false; - } - } - } - - // Pointers and Touches, and Mouse - if (hit) { - this.dispatchEvent(displayObject, 'pointerup', interactionEvent); - if (isTouch) this.dispatchEvent(displayObject, 'touchend', interactionEvent); - - if (trackingData) { - this.dispatchEvent(displayObject, 'pointertap', interactionEvent); - if (isTouch) { - this.dispatchEvent(displayObject, 'tap', interactionEvent); - // touches are no longer over (if they ever were) when we get the touchend - // so we should ensure that we don't keep pretending that they are - trackingData.over = false; - } - } - } else if (trackingData) { - this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); - if (isTouch) this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); - } - // Only remove the tracking data if there is no over/down state still associated with it - if (trackingData && trackingData.none) { - delete displayObject.trackedPointers[id]; - } - }; - - /** - * Is called when the pointer moves across the renderer element - * - * @private - * @param {PointerEvent} originalEvent - The DOM event of a pointer moving - */ - - - InteractionManager.prototype.onPointerMove = function onPointerMove(originalEvent) { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; - - var events = this.normalizeToPointerData(originalEvent); - - if (events[0].pointerType === 'mouse') { - this.didMove = true; - - this.cursor = null; - } - - var eventLen = events.length; - - for (var i = 0; i < eventLen; i++) { - var event = events[i]; - - var interactionData = this.getInteractionDataForPointerId(event); - - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); - - interactionEvent.data.originalEvent = originalEvent; - - var interactive = event.pointerType === 'touch' ? this.moveWhenInside : true; - - this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerMove, interactive); - this.emit('pointermove', interactionEvent); - if (event.pointerType === 'touch') this.emit('touchmove', interactionEvent); - if (event.pointerType === 'mouse' || event.pointerType === 'pen') this.emit('mousemove', interactionEvent); - } - - if (events[0].pointerType === 'mouse') { - this.setCursorMode(this.cursor); - - // TODO BUG for parents interactive object (border order issue) - } - }; - - /** - * Processes the result of the pointer move check and dispatches the event if need be - * - * @private - * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event - * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested - * @param {boolean} hit - the result of the hit test on the display object - */ - - - InteractionManager.prototype.processPointerMove = function processPointerMove(interactionEvent, displayObject, hit) { - var data = interactionEvent.data; - - var isTouch = data.pointerType === 'touch'; - - var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; - - if (isMouse) { - this.processPointerOverOut(interactionEvent, displayObject, hit); - } - - if (!this.moveWhenInside || hit) { - this.dispatchEvent(displayObject, 'pointermove', interactionEvent); - if (isTouch) this.dispatchEvent(displayObject, 'touchmove', interactionEvent); - if (isMouse) this.dispatchEvent(displayObject, 'mousemove', interactionEvent); - } - }; - - /** - * Is called when the pointer is moved out of the renderer element - * - * @private - * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out - */ - - - InteractionManager.prototype.onPointerOut = function onPointerOut(originalEvent) { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; - - var events = this.normalizeToPointerData(originalEvent); - - // Only mouse and pointer can call onPointerOut, so events will always be length 1 - var event = events[0]; - - if (event.pointerType === 'mouse') { - this.mouseOverRenderer = false; - this.setCursorMode(null); - } - - var interactionData = this.getInteractionDataForPointerId(event); - - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); - - interactionEvent.data.originalEvent = event; - - this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, false); - - this.emit('pointerout', interactionEvent); - if (event.pointerType === 'mouse' || event.pointerType === 'pen') { - this.emit('mouseout', interactionEvent); - } else { - // we can get touchleave events after touchend, so we want to make sure we don't - // introduce memory leaks - this.releaseInteractionDataForPointerId(interactionData.identifier); - } - }; - - /** - * Processes the result of the pointer over/out check and dispatches the event if need be - * - * @private - * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event - * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested - * @param {boolean} hit - the result of the hit test on the display object - */ - - - InteractionManager.prototype.processPointerOverOut = function processPointerOverOut(interactionEvent, displayObject, hit) { - var data = interactionEvent.data; - - var id = interactionEvent.data.identifier; - - var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; - - var trackingData = displayObject.trackedPointers[id]; - - // if we just moused over the display object, then we need to track that state - if (hit && !trackingData) { - trackingData = displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); - } - - if (trackingData === undefined) return; - - if (hit && this.mouseOverRenderer) { - if (!trackingData.over) { - trackingData.over = true; - this.dispatchEvent(displayObject, 'pointerover', interactionEvent); - if (isMouse) { - this.dispatchEvent(displayObject, 'mouseover', interactionEvent); - } - } - - // only change the cursor if it has not already been changed (by something deeper in the - // display tree) - if (isMouse && this.cursor === null) { - this.cursor = displayObject.cursor; - } - } else if (trackingData.over) { - trackingData.over = false; - this.dispatchEvent(displayObject, 'pointerout', this.eventData); - if (isMouse) { - this.dispatchEvent(displayObject, 'mouseout', interactionEvent); - } - // if there is no mouse down information for the pointer, then it is safe to delete - if (trackingData.none) { - delete displayObject.trackedPointers[id]; - } - } - }; - - /** - * Is called when the pointer is moved into the renderer element - * - * @private - * @param {PointerEvent} originalEvent - The DOM event of a pointer button being moved into the renderer view - */ - - - InteractionManager.prototype.onPointerOver = function onPointerOver(originalEvent) { - var events = this.normalizeToPointerData(originalEvent); - - // Only mouse and pointer can call onPointerOver, so events will always be length 1 - var event = events[0]; - - var interactionData = this.getInteractionDataForPointerId(event); - - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); - - interactionEvent.data.originalEvent = event; - - if (event.pointerType === 'mouse') { - this.mouseOverRenderer = true; - } - - this.emit('pointerover', interactionEvent); - if (event.pointerType === 'mouse' || event.pointerType === 'pen') { - this.emit('mouseover', interactionEvent); - } - }; - - /** - * Get InteractionData for a given pointerId. Store that data as well - * - * @private - * @param {PointerEvent} event - Normalized pointer event, output from normalizeToPointerData - * @return {PIXI.interaction.InteractionData} - Interaction data for the given pointer identifier - */ - - - InteractionManager.prototype.getInteractionDataForPointerId = function getInteractionDataForPointerId(event) { - var pointerId = event.pointerId; - - var interactionData = void 0; - - if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') { - interactionData = this.mouse; - } else if (this.activeInteractionData[pointerId]) { - interactionData = this.activeInteractionData[pointerId]; - } else { - interactionData = this.interactionDataPool.pop() || new _InteractionData2.default(); - interactionData.identifier = pointerId; - this.activeInteractionData[pointerId] = interactionData; - } - // copy properties from the event, so that we can make sure that touch/pointer specific - // data is available - interactionData._copyEvent(event); - - return interactionData; - }; - - /** - * Return unused InteractionData to the pool, for a given pointerId - * - * @private - * @param {number} pointerId - Identifier from a pointer event - */ - - - InteractionManager.prototype.releaseInteractionDataForPointerId = function releaseInteractionDataForPointerId(pointerId) { - var interactionData = this.activeInteractionData[pointerId]; - - if (interactionData) { - delete this.activeInteractionData[pointerId]; - interactionData._reset(); - this.interactionDataPool.push(interactionData); - } - }; - - /** - * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData - * - * @private - * @param {PIXI.interaction.InteractionEvent} interactionEvent - The event to be configured - * @param {PointerEvent} pointerEvent - The DOM event that will be paired with the InteractionEvent - * @param {PIXI.interaction.InteractionData} interactionData - The InteractionData that will be paired - * with the InteractionEvent - * @return {PIXI.interaction.InteractionEvent} the interaction event that was passed in - */ - - - InteractionManager.prototype.configureInteractionEventForDOMEvent = function configureInteractionEventForDOMEvent(interactionEvent, pointerEvent, interactionData) { - interactionEvent.data = interactionData; - - this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); - - // This is the way InteractionManager processed touch events before the refactoring, so I've kept - // it here. But it doesn't make that much sense to me, since mapPositionToPoint already factors - // in this.resolution, so this just divides by this.resolution twice for touch events... - if (navigator.isCocoonJS && pointerEvent.pointerType === 'touch') { - interactionData.global.x = interactionData.global.x / this.resolution; - interactionData.global.y = interactionData.global.y / this.resolution; - } - - // Not really sure why this is happening, but it's how a previous version handled things - if (pointerEvent.pointerType === 'touch') { - pointerEvent.globalX = interactionData.global.x; - pointerEvent.globalY = interactionData.global.y; - } - - interactionData.originalEvent = pointerEvent; - interactionEvent._reset(); - - return interactionEvent; - }; - - /** - * Ensures that the original event object contains all data that a regular pointer event would have - * - * @private - * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event - * @return {PointerEvent[]} An array containing a single normalized pointer event, in the case of a pointer - * or mouse event, or a multiple normalized pointer events if there are multiple changed touches - */ - - - InteractionManager.prototype.normalizeToPointerData = function normalizeToPointerData(event) { - var normalizedEvents = []; - - if (this.supportsTouchEvents && event instanceof TouchEvent) { - for (var i = 0, li = event.changedTouches.length; i < li; i++) { - var touch = event.changedTouches[i]; - - if (typeof touch.button === 'undefined') touch.button = event.touches.length ? 1 : 0; - if (typeof touch.buttons === 'undefined') touch.buttons = event.touches.length ? 1 : 0; - if (typeof touch.isPrimary === 'undefined') { - touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart'; - } - if (typeof touch.width === 'undefined') touch.width = touch.radiusX || 1; - if (typeof touch.height === 'undefined') touch.height = touch.radiusY || 1; - if (typeof touch.tiltX === 'undefined') touch.tiltX = 0; - if (typeof touch.tiltY === 'undefined') touch.tiltY = 0; - if (typeof touch.pointerType === 'undefined') touch.pointerType = 'touch'; - if (typeof touch.pointerId === 'undefined') touch.pointerId = touch.identifier || 0; - if (typeof touch.pressure === 'undefined') touch.pressure = touch.force || 0.5; - touch.twist = 0; - touch.tangentialPressure = 0; - // TODO: Remove these, as layerX/Y is not a standard, is deprecated, has uneven - // support, and the fill ins are not quite the same - // offsetX/Y might be okay, but is not the same as clientX/Y when the canvas's top - // left is not 0,0 on the page - if (typeof touch.layerX === 'undefined') touch.layerX = touch.offsetX = touch.clientX; - if (typeof touch.layerY === 'undefined') touch.layerY = touch.offsetY = touch.clientY; - - // mark the touch as normalized, just so that we know we did it - touch.isNormalized = true; - - normalizedEvents.push(touch); - } - } - // apparently PointerEvent subclasses MouseEvent, so yay - else if (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof window.PointerEvent))) { - if (typeof event.isPrimary === 'undefined') event.isPrimary = true; - if (typeof event.width === 'undefined') event.width = 1; - if (typeof event.height === 'undefined') event.height = 1; - if (typeof event.tiltX === 'undefined') event.tiltX = 0; - if (typeof event.tiltY === 'undefined') event.tiltY = 0; - if (typeof event.pointerType === 'undefined') event.pointerType = 'mouse'; - if (typeof event.pointerId === 'undefined') event.pointerId = MOUSE_POINTER_ID; - if (typeof event.pressure === 'undefined') event.pressure = 0.5; - event.twist = 0; - event.tangentialPressure = 0; - - // mark the mouse event as normalized, just so that we know we did it - event.isNormalized = true; - - normalizedEvents.push(event); - } else { - normalizedEvents.push(event); - } - - return normalizedEvents; - }; - - /** - * Destroys the interaction manager - * - */ - - - InteractionManager.prototype.destroy = function destroy() { - this.removeEvents(); - - this.removeAllListeners(); - - this.renderer = null; - - this.mouse = null; - - this.eventData = null; - - this.interactionDOMElement = null; - - this.onPointerDown = null; - this.processPointerDown = null; - - this.onPointerUp = null; - this.processPointerUp = null; - - this.onPointerCancel = null; - this.processPointerCancel = null; - - this.onPointerMove = null; - this.processPointerMove = null; - - this.onPointerOut = null; - this.processPointerOverOut = null; - - this.onPointerOver = null; - - this._tempPoint = null; - }; - - return InteractionManager; -}(_eventemitter2.default); - -exports.default = InteractionManager; - - -core.WebGLRenderer.registerPlugin('interaction', InteractionManager); -core.CanvasRenderer.registerPlugin('interaction', InteractionManager); - -},{"../core":65,"./InteractionData":155,"./InteractionEvent":156,"./InteractionTrackingData":158,"./interactiveTarget":160,"eventemitter3":3}],158:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * DisplayObjects with the {@link PIXI.interaction.interactiveTarget} mixin use this class to track interactions - * - * @class - * @private - * @memberof PIXI.interaction - */ -var InteractionTrackingData = function () { - /** - * @param {number} pointerId - Unique pointer id of the event - */ - function InteractionTrackingData(pointerId) { - _classCallCheck(this, InteractionTrackingData); - - this._pointerId = pointerId; - this._flags = InteractionTrackingData.FLAGS.NONE; - } - - /** - * - * @private - * @param {number} flag - The interaction flag to set - * @param {boolean} yn - Should the flag be set or unset - */ - - - InteractionTrackingData.prototype._doSet = function _doSet(flag, yn) { - if (yn) { - this._flags = this._flags | flag; - } else { - this._flags = this._flags & ~flag; - } - }; - - /** - * Unique pointer id of the event - * - * @readonly - * @member {number} - */ - - - _createClass(InteractionTrackingData, [{ - key: "pointerId", - get: function get() { - return this._pointerId; - } - - /** - * State of the tracking data, expressed as bit flags - * - * @member {number} - * @memberof PIXI.interaction.InteractionTrackingData# - */ - - }, { - key: "flags", - get: function get() { - return this._flags; - } - - /** - * Set the flags for the tracking data - * - * @param {number} flags - Flags to set - */ - , - set: function set(flags) { - this._flags = flags; - } - - /** - * Is the tracked event inactive (not over or down)? - * - * @member {number} - * @memberof PIXI.interaction.InteractionTrackingData# - */ - - }, { - key: "none", - get: function get() { - return this._flags === this.constructor.FLAGS.NONE; - } - - /** - * Is the tracked event over the DisplayObject? - * - * @member {boolean} - * @memberof PIXI.interaction.InteractionTrackingData# - */ - - }, { - key: "over", - get: function get() { - return (this._flags & this.constructor.FLAGS.OVER) !== 0; - } - - /** - * Set the over flag - * - * @param {boolean} yn - Is the event over? - */ - , - set: function set(yn) { - this._doSet(this.constructor.FLAGS.OVER, yn); - } - - /** - * Did the right mouse button come down in the DisplayObject? - * - * @member {boolean} - * @memberof PIXI.interaction.InteractionTrackingData# - */ - - }, { - key: "rightDown", - get: function get() { - return (this._flags & this.constructor.FLAGS.RIGHT_DOWN) !== 0; - } - - /** - * Set the right down flag - * - * @param {boolean} yn - Is the right mouse button down? - */ - , - set: function set(yn) { - this._doSet(this.constructor.FLAGS.RIGHT_DOWN, yn); - } - - /** - * Did the left mouse button come down in the DisplayObject? - * - * @member {boolean} - * @memberof PIXI.interaction.InteractionTrackingData# - */ - - }, { - key: "leftDown", - get: function get() { - return (this._flags & this.constructor.FLAGS.LEFT_DOWN) !== 0; - } - - /** - * Set the left down flag - * - * @param {boolean} yn - Is the left mouse button down? - */ - , - set: function set(yn) { - this._doSet(this.constructor.FLAGS.LEFT_DOWN, yn); - } - }]); - - return InteractionTrackingData; -}(); - -exports.default = InteractionTrackingData; - - -InteractionTrackingData.FLAGS = Object.freeze({ - NONE: 0, - OVER: 1 << 0, - LEFT_DOWN: 1 << 1, - RIGHT_DOWN: 1 << 2 -}); - -},{}],159:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _InteractionData = require('./InteractionData'); - -Object.defineProperty(exports, 'InteractionData', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_InteractionData).default; - } -}); - -var _InteractionManager = require('./InteractionManager'); - -Object.defineProperty(exports, 'InteractionManager', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_InteractionManager).default; - } -}); - -var _interactiveTarget = require('./interactiveTarget'); - -Object.defineProperty(exports, 'interactiveTarget', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_interactiveTarget).default; - } -}); - -var _InteractionTrackingData = require('./InteractionTrackingData'); - -Object.defineProperty(exports, 'InteractionTrackingData', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_InteractionTrackingData).default; - } -}); - -var _InteractionEvent = require('./InteractionEvent'); - -Object.defineProperty(exports, 'InteractionEvent', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_InteractionEvent).default; - } -}); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -},{"./InteractionData":155,"./InteractionEvent":156,"./InteractionManager":157,"./InteractionTrackingData":158,"./interactiveTarget":160}],160:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -/** - * Default property values of interactive objects - * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties - * - * @private - * @name interactiveTarget - * @memberof PIXI.interaction - * @example - * function MyObject() {} - * - * Object.assign( - * core.DisplayObject.prototype, - * PIXI.interaction.interactiveTarget - * ); - */ -exports.default = { - - /** - * Enable interaction events for the DisplayObject. Touch, pointer and mouse - * events will not be emitted unless `interactive` is set to `true`. - * - * @example - * const sprite = new PIXI.Sprite(texture); - * sprite.interactive = true; - * sprite.on('tap', (event) => { - * //handle event - * }); - * @member {boolean} - * @memberof PIXI.DisplayObject# - */ - interactive: false, - - /** - * Determines if the children to the displayObject can be clicked/touched - * Setting this to false allows PixiJS to bypass a recursive `hitTest` function - * - * @member {boolean} - * @memberof PIXI.Container# - */ - interactiveChildren: true, - - /** - * Interaction shape. Children will be hit first, then this shape will be checked. - * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. - * - * @example - * const sprite = new PIXI.Sprite(texture); - * sprite.interactive = true; - * sprite.hitArea = new PIXI.Rectangle(0, 0, 100, 100); - * @member {PIXI.Rectangle|PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.RoundedRectangle} - * @memberof PIXI.DisplayObject# - */ - hitArea: null, - - /** - * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive - * Setting this changes the 'cursor' property to `'pointer'`. - * - * @example - * const sprite = new PIXI.Sprite(texture); - * sprite.interactive = true; - * sprite.buttonMode = true; - * @member {boolean} - * @memberof PIXI.DisplayObject# - */ - get buttonMode() { - return this.cursor === 'pointer'; - }, - set buttonMode(value) { - if (value) { - this.cursor = 'pointer'; - } else if (this.cursor === 'pointer') { - this.cursor = null; - } - }, - - /** - * This defines what cursor mode is used when the mouse cursor - * is hovered over the displayObject. - * - * @example - * const sprite = new PIXI.Sprite(texture); - * sprite.interactive = true; - * sprite.cursor = 'wait'; - * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor - * - * @member {string} - * @memberof PIXI.DisplayObject# - */ - cursor: null, - - /** - * Internal set of all active pointers, by identifier - * - * @member {Map} - * @memberof PIXI.DisplayObject# - * @private - */ - get trackedPointers() { - if (this._trackedPointers === undefined) this._trackedPointers = {}; - - return this._trackedPointers; - }, - - /** - * Map of all tracked pointers, by identifier. Use trackedPointers to access. - * - * @private - * @type {Map} - */ - _trackedPointers: undefined -}; - -},{}],161:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.parse = parse; - -exports.default = function () { - return function bitmapFontParser(resource, next) { - // skip if no data or not xml data - if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.XML) { - next(); - - return; - } - - // skip if not bitmap font data, using some silly duck-typing - if (resource.data.getElementsByTagName('page').length === 0 || resource.data.getElementsByTagName('info').length === 0 || resource.data.getElementsByTagName('info')[0].getAttribute('face') === null) { - next(); - - return; - } - - var xmlUrl = !resource.isDataUrl ? path.dirname(resource.url) : ''; - - if (resource.isDataUrl) { - if (xmlUrl === '.') { - xmlUrl = ''; - } - - if (this.baseUrl && xmlUrl) { - // if baseurl has a trailing slash then add one to xmlUrl so the replace works below - if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') { - xmlUrl += '/'; - } - } - } - - // remove baseUrl from xmlUrl - xmlUrl = xmlUrl.replace(this.baseUrl, ''); - - // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. - if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') { - xmlUrl += '/'; - } - - var textureUrl = xmlUrl + resource.data.getElementsByTagName('page')[0].getAttribute('file'); - - if (_core.utils.TextureCache[textureUrl]) { - // reuse existing texture - parse(resource, _core.utils.TextureCache[textureUrl]); - next(); - } else { - var loadOptions = { - crossOrigin: resource.crossOrigin, - loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, - metadata: resource.metadata.imageMetadata, - parentResource: resource - }; - - // load the texture for the font - this.add(resource.name + '_image', textureUrl, loadOptions, function (res) { - parse(resource, res.texture); - next(); - }); - } - }; -}; - -var _path = require('path'); - -var path = _interopRequireWildcard(_path); - -var _core = require('../core'); - -var _resourceLoader = require('resource-loader'); - -var _extras = require('../extras'); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -/** - * Register a BitmapText font from loader resource. - * - * @function parseBitmapFontData - * @memberof PIXI.loaders - * @param {PIXI.loaders.Resource} resource - Loader resource. - * @param {PIXI.Texture} texture - Reference to texture. - */ -function parse(resource, texture) { - resource.bitmapFont = _extras.BitmapText.registerFont(resource.data, texture); -} - -},{"../core":65,"../extras":141,"path":23,"resource-loader":36}],162:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; -exports.shared = exports.Resource = exports.textureParser = exports.getResourcePath = exports.spritesheetParser = exports.parseBitmapFontData = exports.bitmapFontParser = exports.Loader = undefined; - -var _bitmapFontParser = require('./bitmapFontParser'); - -Object.defineProperty(exports, 'bitmapFontParser', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_bitmapFontParser).default; - } -}); -Object.defineProperty(exports, 'parseBitmapFontData', { - enumerable: true, - get: function get() { - return _bitmapFontParser.parse; - } -}); - -var _spritesheetParser = require('./spritesheetParser'); - -Object.defineProperty(exports, 'spritesheetParser', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_spritesheetParser).default; - } -}); -Object.defineProperty(exports, 'getResourcePath', { - enumerable: true, - get: function get() { - return _spritesheetParser.getResourcePath; - } -}); - -var _textureParser = require('./textureParser'); - -Object.defineProperty(exports, 'textureParser', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_textureParser).default; - } -}); - -var _resourceLoader = require('resource-loader'); - -Object.defineProperty(exports, 'Resource', { - enumerable: true, - get: function get() { - return _resourceLoader.Resource; - } -}); - -var _Application = require('../core/Application'); - -var _Application2 = _interopRequireDefault(_Application); - -var _loader = require('./loader'); - -var _loader2 = _interopRequireDefault(_loader); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * This namespace contains APIs which extends the {@link https://github.com/englercj/resource-loader resource-loader} module - * for loading assets, data, and other resources dynamically. - * @example - * const loader = new PIXI.loaders.Loader(); - * loader.add('bunny', 'data/bunny.png') - * .add('spaceship', 'assets/spritesheet.json'); - * loader.load((loader, resources) => { - * // resources.bunny - * // resources.spaceship - * }); - * @namespace PIXI.loaders - */ -exports.Loader = _loader2.default; - - -/** - * A premade instance of the loader that can be used to load resources. - * @name shared - * @memberof PIXI.loaders - * @type {PIXI.loaders.Loader} - */ -var shared = new _loader2.default(); - -shared.destroy = function () { - // protect destroying shared loader -}; - -exports.shared = shared; - -// Mixin the loader construction - -var AppPrototype = _Application2.default.prototype; - -AppPrototype._loader = null; - -/** - * Loader instance to help with asset loading. - * @name PIXI.Application#loader - * @type {PIXI.loaders.Loader} - */ -Object.defineProperty(AppPrototype, 'loader', { - get: function get() { - if (!this._loader) { - var sharedLoader = this._options.sharedLoader; - - this._loader = sharedLoader ? shared : new _loader2.default(); - } - - return this._loader; - } -}); - -// Override the destroy function -// making sure to destroy the current Loader -AppPrototype._parentDestroy = AppPrototype.destroy; -AppPrototype.destroy = function destroy(removeView) { - if (this._loader) { - this._loader.destroy(); - this._loader = null; - } - this._parentDestroy(removeView); -}; - -},{"../core/Application":43,"./bitmapFontParser":161,"./loader":163,"./spritesheetParser":164,"./textureParser":165,"resource-loader":36}],163:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _resourceLoader = require('resource-loader'); - -var _resourceLoader2 = _interopRequireDefault(_resourceLoader); - -var _blob = require('resource-loader/lib/middlewares/parsing/blob'); - -var _eventemitter = require('eventemitter3'); - -var _eventemitter2 = _interopRequireDefault(_eventemitter); - -var _textureParser = require('./textureParser'); - -var _textureParser2 = _interopRequireDefault(_textureParser); - -var _spritesheetParser = require('./spritesheetParser'); - -var _spritesheetParser2 = _interopRequireDefault(_spritesheetParser); - -var _bitmapFontParser = require('./bitmapFontParser'); - -var _bitmapFontParser2 = _interopRequireDefault(_bitmapFontParser); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * - * The new loader, extends Resource Loader by Chad Engler: https://github.com/englercj/resource-loader - * - * ```js - * const loader = PIXI.loader; // PixiJS exposes a premade instance for you to use. - * //or - * const loader = new PIXI.loaders.Loader(); // you can also create your own if you want - * - * const sprites = {}; - * - * // Chainable `add` to enqueue a resource - * loader.add('bunny', 'data/bunny.png') - * .add('spaceship', 'assets/spritesheet.json'); - * loader.add('scoreFont', 'assets/score.fnt'); - * - * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource. - * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc). - * loader.pre(cachingMiddleware); - * - * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource. - * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc). - * loader.use(parsingMiddleware); - * - * // The `load` method loads the queue of resources, and calls the passed in callback called once all - * // resources have loaded. - * loader.load((loader, resources) => { - * // resources is an object where the key is the name of the resource loaded and the value is the resource object. - * // They have a couple default properties: - * // - `url`: The URL that the resource was loaded from - * // - `error`: The error that happened when trying to load (if any) - * // - `data`: The raw data that was loaded - * // also may contain other properties based on the middleware that runs. - * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture); - * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture); - * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture); - * }); - * - * // throughout the process multiple signals can be dispatched. - * loader.onProgress.add(() => {}); // called once per loaded/errored file - * loader.onError.add(() => {}); // called once per errored file - * loader.onLoad.add(() => {}); // called once per loaded file - * loader.onComplete.add(() => {}); // called once when the queued resources all load. - * ``` - * - * @see https://github.com/englercj/resource-loader - * - * @class - * @extends module:resource-loader.ResourceLoader - * @memberof PIXI.loaders - */ -var Loader = function (_ResourceLoader) { - _inherits(Loader, _ResourceLoader); - - /** - * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. - * @param {number} [concurrency=10] - The number of resources to load concurrently. - */ - function Loader(baseUrl, concurrency) { - _classCallCheck(this, Loader); - - var _this = _possibleConstructorReturn(this, _ResourceLoader.call(this, baseUrl, concurrency)); - - _eventemitter2.default.call(_this); - - for (var i = 0; i < Loader._pixiMiddleware.length; ++i) { - _this.use(Loader._pixiMiddleware[i]()); - } - - // Compat layer, translate the new v2 signals into old v1 events. - _this.onStart.add(function (l) { - return _this.emit('start', l); - }); - _this.onProgress.add(function (l, r) { - return _this.emit('progress', l, r); - }); - _this.onError.add(function (e, l, r) { - return _this.emit('error', e, l, r); - }); - _this.onLoad.add(function (l, r) { - return _this.emit('load', l, r); - }); - _this.onComplete.add(function (l, r) { - return _this.emit('complete', l, r); - }); - return _this; - } - - /** - * Adds a default middleware to the PixiJS loader. - * - * @static - * @param {Function} fn - The middleware to add. - */ - - - Loader.addPixiMiddleware = function addPixiMiddleware(fn) { - Loader._pixiMiddleware.push(fn); - }; - - /** - * Destroy the loader, removes references. - */ - - - Loader.prototype.destroy = function destroy() { - this.removeAllListeners(); - this.reset(); - }; - - return Loader; -}(_resourceLoader2.default); - -// Copy EE3 prototype (mixin) - - -exports.default = Loader; -for (var k in _eventemitter2.default.prototype) { - Loader.prototype[k] = _eventemitter2.default.prototype[k]; -} - -Loader._pixiMiddleware = [ -// parse any blob into more usable objects (e.g. Image) -_blob.blobMiddlewareFactory, -// parse any Image objects into textures -_textureParser2.default, -// parse any spritesheet data into multiple textures -_spritesheetParser2.default, -// parse bitmap font data into multiple textures -_bitmapFontParser2.default]; - -// Add custom extentions -var Resource = _resourceLoader2.default.Resource; - -Resource.setExtensionXhrType('fnt', Resource.XHR_RESPONSE_TYPE.DOCUMENT); - -},{"./bitmapFontParser":161,"./spritesheetParser":164,"./textureParser":165,"eventemitter3":3,"resource-loader":36,"resource-loader/lib/middlewares/parsing/blob":37}],164:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -exports.default = function () { - return function spritesheetParser(resource, next) { - var imageResourceName = resource.name + '_image'; - - // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists - if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.JSON || !resource.data.frames || this.resources[imageResourceName]) { - next(); - - return; - } - - var loadOptions = { - crossOrigin: resource.crossOrigin, - loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, - metadata: resource.metadata.imageMetadata, - parentResource: resource - }; - - var resourcePath = getResourcePath(resource, this.baseUrl); - - // load the image for this sheet - this.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { - var spritesheet = new _core.Spritesheet(res.texture.baseTexture, resource.data, resource.url); - - spritesheet.parse(function () { - resource.spritesheet = spritesheet; - resource.textures = spritesheet.textures; - next(); - }); - }); - }; -}; - -exports.getResourcePath = getResourcePath; - -var _resourceLoader = require('resource-loader'); - -var _url = require('url'); - -var _url2 = _interopRequireDefault(_url); - -var _core = require('../core'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function getResourcePath(resource, baseUrl) { - // Prepend url path unless the resource image is a data url - if (resource.isDataUrl) { - return resource.data.meta.image; - } - - return _url2.default.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image); -} - -},{"../core":65,"resource-loader":36,"url":29}],165:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -exports.default = function () { - return function textureParser(resource, next) { - // create a new texture if the data is an Image object - if (resource.data && resource.type === _resourceLoader.Resource.TYPE.IMAGE) { - resource.texture = _Texture2.default.fromLoader(resource.data, resource.url, resource.name); - } - next(); - }; -}; - -var _resourceLoader = require('resource-loader'); - -var _Texture = require('../core/textures/Texture'); - -var _Texture2 = _interopRequireDefault(_Texture); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -},{"../core/textures/Texture":115,"resource-loader":36}],166:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _core = require('../core'); - -var core = _interopRequireWildcard(_core); - -var _TextureTransform = require('../extras/TextureTransform'); - -var _TextureTransform2 = _interopRequireDefault(_TextureTransform); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -var tempPoint = new core.Point(); -var tempPolygon = new core.Polygon(); - -/** - * Base mesh class - * @class - * @extends PIXI.Container - * @memberof PIXI.mesh - */ - -var Mesh = function (_core$Container) { - _inherits(Mesh, _core$Container); - - /** - * @param {PIXI.Texture} texture - The texture to use - * @param {Float32Array} [vertices] - if you want to specify the vertices - * @param {Float32Array} [uvs] - if you want to specify the uvs - * @param {Uint16Array} [indices] - if you want to specify the indices - * @param {number} [drawMode] - the drawMode, can be any of the Mesh.DRAW_MODES consts - */ - function Mesh(texture, vertices, uvs, indices, drawMode) { - _classCallCheck(this, Mesh); - - /** - * The texture of the Mesh - * - * @member {PIXI.Texture} - * @private - */ - var _this = _possibleConstructorReturn(this, _core$Container.call(this)); - - _this._texture = texture; - - /** - * The Uvs of the Mesh - * - * @member {Float32Array} - */ - _this.uvs = uvs || new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); - - /** - * An array of vertices - * - * @member {Float32Array} - */ - _this.vertices = vertices || new Float32Array([0, 0, 100, 0, 100, 100, 0, 100]); - - /** - * An array containing the indices of the vertices - * - * @member {Uint16Array} - */ - // TODO auto generate this based on draw mode! - _this.indices = indices || new Uint16Array([0, 1, 3, 2]); - - /** - * Version of mesh uvs are dirty or not - * - * @member {number} - */ - _this.dirty = 0; - - /** - * Version of mesh indices - * - * @member {number} - */ - _this.indexDirty = 0; - - /** - * The blend mode to be applied to the sprite. Set to `PIXI.BLEND_MODES.NORMAL` to remove - * any blend mode. - * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL - * @see PIXI.BLEND_MODES - */ - _this.blendMode = core.BLEND_MODES.NORMAL; - - /** - * Triangles in canvas mode are automatically antialiased, use this value to force triangles - * to overlap a bit with each other. - * - * @member {number} - */ - _this.canvasPadding = 0; - - /** - * The way the Mesh should be drawn, can be any of the {@link PIXI.mesh.Mesh.DRAW_MODES} consts - * - * @member {number} - * @see PIXI.mesh.Mesh.DRAW_MODES - */ - _this.drawMode = drawMode || Mesh.DRAW_MODES.TRIANGLE_MESH; - - /** - * The default shader that is used if a mesh doesn't have a more specific one. - * - * @member {PIXI.Shader} - */ - _this.shader = null; - - /** - * The tint applied to the mesh. This is a [r,g,b] value. A value of [1,1,1] will remove any - * tint effect. - * - * @member {number} - */ - _this.tintRgb = new Float32Array([1, 1, 1]); - - /** - * A map of renderer IDs to webgl render data - * - * @private - * @member {object} - */ - _this._glDatas = {}; - - /** - * transform that is applied to UV to get the texture coords - * its updated independently from texture uvTransform - * updates of uvs are tied to that thing - * - * @member {PIXI.extras.TextureTransform} - * @private - */ - _this._uvTransform = new _TextureTransform2.default(texture); - - /** - * whether or not upload uvTransform to shader - * if its false, then uvs should be pre-multiplied - * if you change it for generated mesh, please call 'refresh(true)' - * @member {boolean} - * @default false - */ - _this.uploadUvTransform = false; - - /** - * Plugin that is responsible for rendering this element. - * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. - * @member {string} - * @default 'mesh' - */ - _this.pluginName = 'mesh'; - return _this; - } - - /** - * Renders the object using the WebGL renderer - * - * @private - * @param {PIXI.WebGLRenderer} renderer - a reference to the WebGL renderer - */ - - - Mesh.prototype._renderWebGL = function _renderWebGL(renderer) { - this.refresh(); - renderer.setObjectRenderer(renderer.plugins[this.pluginName]); - renderer.plugins[this.pluginName].render(this); - }; - - /** - * Renders the object using the Canvas renderer - * - * @private - * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. - */ - - - Mesh.prototype._renderCanvas = function _renderCanvas(renderer) { - this.refresh(); - renderer.plugins[this.pluginName].render(this); - }; - - /** - * When the texture is updated, this event will fire to update the scale and frame - * - * @private - */ - - - Mesh.prototype._onTextureUpdate = function _onTextureUpdate() { - this._uvTransform.texture = this._texture; - this.refresh(); - }; - - /** - * multiplies uvs only if uploadUvTransform is false - * call it after you change uvs manually - * make sure that texture is valid - */ - - - Mesh.prototype.multiplyUvs = function multiplyUvs() { - if (!this.uploadUvTransform) { - this._uvTransform.multiplyUvs(this.uvs); - } - }; - - /** - * Refreshes uvs for generated meshes (rope, plane) - * sometimes refreshes vertices too - * - * @param {boolean} [forceUpdate=false] if true, matrices will be updated any case - */ - - - Mesh.prototype.refresh = function refresh(forceUpdate) { - if (this._uvTransform.update(forceUpdate)) { - this._refresh(); - } - }; - - /** - * re-calculates mesh coords - * @protected - */ - - - Mesh.prototype._refresh = function _refresh() {} - /* empty */ - - - /** - * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. - * - */ - ; - - Mesh.prototype._calculateBounds = function _calculateBounds() { - // TODO - we can cache local bounds and use them if they are dirty (like graphics) - this._bounds.addVertices(this.transform, this.vertices, 0, this.vertices.length); - }; - - /** - * Tests if a point is inside this mesh. Works only for TRIANGLE_MESH - * - * @param {PIXI.Point} point - the point to test - * @return {boolean} the result of the test - */ - - - Mesh.prototype.containsPoint = function containsPoint(point) { - if (!this.getBounds().contains(point.x, point.y)) { - return false; - } - - this.worldTransform.applyInverse(point, tempPoint); - - var vertices = this.vertices; - var points = tempPolygon.points; - var indices = this.indices; - var len = this.indices.length; - var step = this.drawMode === Mesh.DRAW_MODES.TRIANGLES ? 3 : 1; - - for (var i = 0; i + 2 < len; i += step) { - var ind0 = indices[i] * 2; - var ind1 = indices[i + 1] * 2; - var ind2 = indices[i + 2] * 2; - - points[0] = vertices[ind0]; - points[1] = vertices[ind0 + 1]; - points[2] = vertices[ind1]; - points[3] = vertices[ind1 + 1]; - points[4] = vertices[ind2]; - points[5] = vertices[ind2 + 1]; - - if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { - return true; - } - } - - return false; - }; - - /** - * The texture that the mesh uses. - * - * @member {PIXI.Texture} - */ - - - _createClass(Mesh, [{ - key: 'texture', - get: function get() { - return this._texture; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - if (this._texture === value) { - return; - } - - this._texture = value; - - if (value) { - // wait for the texture to load - if (value.baseTexture.hasLoaded) { - this._onTextureUpdate(); - } else { - value.once('update', this._onTextureUpdate, this); - } - } - } - - /** - * The tint applied to the mesh. This is a hex value. A value of 0xFFFFFF will remove any tint effect. - * - * @member {number} - * @default 0xFFFFFF - */ - - }, { - key: 'tint', - get: function get() { - return core.utils.rgb2hex(this.tintRgb); - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.tintRgb = core.utils.hex2rgb(value, this.tintRgb); - } - }]); - - return Mesh; -}(core.Container); - -/** - * Different drawing buffer modes supported - * - * @static - * @constant - * @type {object} - * @property {number} TRIANGLE_MESH - * @property {number} TRIANGLES - */ - - -exports.default = Mesh; -Mesh.DRAW_MODES = { - TRIANGLE_MESH: 0, - TRIANGLES: 1 -}; - -},{"../core":65,"../extras/TextureTransform":136}],167:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _Plane2 = require('./Plane'); - -var _Plane3 = _interopRequireDefault(_Plane2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -var DEFAULT_BORDER_SIZE = 10; - -/** - * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful - * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically - * - *```js - * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.fromImage('BoxWithRoundedCorners.png'), 15, 15, 15, 15); - * ``` - *
- *      A                          B
- *    +---+----------------------+---+
- *  C | 1 |          2           | 3 |
- *    +---+----------------------+---+
- *    |   |                      |   |
- *    | 4 |          5           | 6 |
- *    |   |                      |   |
- *    +---+----------------------+---+
- *  D | 7 |          8           | 9 |
- *    +---+----------------------+---+
-
- *  When changing this objects width and/or height:
- *     areas 1 3 7 and 9 will remain unscaled.
- *     areas 2 and 8 will be stretched horizontally
- *     areas 4 and 6 will be stretched vertically
- *     area 5 will be stretched both horizontally and vertically
- * 
- * - * @class - * @extends PIXI.mesh.Plane - * @memberof PIXI.mesh - * - */ - -var NineSlicePlane = function (_Plane) { - _inherits(NineSlicePlane, _Plane); - - /** - * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane. - * @param {int} [leftWidth=10] size of the left vertical bar (A) - * @param {int} [topHeight=10] size of the top horizontal bar (C) - * @param {int} [rightWidth=10] size of the right vertical bar (B) - * @param {int} [bottomHeight=10] size of the bottom horizontal bar (D) - */ - function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { - _classCallCheck(this, NineSlicePlane); - - var _this = _possibleConstructorReturn(this, _Plane.call(this, texture, 4, 4)); - - _this._origWidth = texture.orig.width; - _this._origHeight = texture.orig.height; - - /** - * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane - * - * @member {number} - * @memberof PIXI.NineSlicePlane# - * @override - */ - _this._width = _this._origWidth; - - /** - * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane - * - * @member {number} - * @memberof PIXI.NineSlicePlane# - * @override - */ - _this._height = _this._origHeight; - - /** - * The width of the left column (a) - * - * @member {number} - * @memberof PIXI.NineSlicePlane# - * @override - */ - _this.leftWidth = typeof leftWidth !== 'undefined' ? leftWidth : DEFAULT_BORDER_SIZE; - - /** - * The width of the right column (b) - * - * @member {number} - * @memberof PIXI.NineSlicePlane# - * @override - */ - _this.rightWidth = typeof rightWidth !== 'undefined' ? rightWidth : DEFAULT_BORDER_SIZE; - - /** - * The height of the top row (c) - * - * @member {number} - * @memberof PIXI.NineSlicePlane# - * @override - */ - _this.topHeight = typeof topHeight !== 'undefined' ? topHeight : DEFAULT_BORDER_SIZE; - - /** - * The height of the bottom row (d) - * - * @member {number} - * @memberof PIXI.NineSlicePlane# - * @override - */ - _this.bottomHeight = typeof bottomHeight !== 'undefined' ? bottomHeight : DEFAULT_BORDER_SIZE; - - _this.refresh(true); - return _this; - } - - /** - * Updates the horizontal vertices. - * - */ - - - NineSlicePlane.prototype.updateHorizontalVertices = function updateHorizontalVertices() { - var vertices = this.vertices; - - vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight; - vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - this._bottomHeight; - vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; - }; - - /** - * Updates the vertical vertices. - * - */ - - - NineSlicePlane.prototype.updateVerticalVertices = function updateVerticalVertices() { - var vertices = this.vertices; - - vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth; - vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - this._rightWidth; - vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; - }; - - /** - * Renders the object using the Canvas renderer - * - * @private - * @param {PIXI.CanvasRenderer} renderer - The canvas renderer to render with. - */ - - - NineSlicePlane.prototype._renderCanvas = function _renderCanvas(renderer) { - var context = renderer.context; - - context.globalAlpha = this.worldAlpha; - - var transform = this.worldTransform; - var res = renderer.resolution; - - if (renderer.roundPixels) { - context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); - } else { - context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); - } - - var base = this._texture.baseTexture; - var textureSource = base.source; - var w = base.width; - var h = base.height; - - this.drawSegment(context, textureSource, w, h, 0, 1, 10, 11); - this.drawSegment(context, textureSource, w, h, 2, 3, 12, 13); - this.drawSegment(context, textureSource, w, h, 4, 5, 14, 15); - this.drawSegment(context, textureSource, w, h, 8, 9, 18, 19); - this.drawSegment(context, textureSource, w, h, 10, 11, 20, 21); - this.drawSegment(context, textureSource, w, h, 12, 13, 22, 23); - this.drawSegment(context, textureSource, w, h, 16, 17, 26, 27); - this.drawSegment(context, textureSource, w, h, 18, 19, 28, 29); - this.drawSegment(context, textureSource, w, h, 20, 21, 30, 31); - }; - - /** - * Renders one segment of the plane. - * to mimic the exact drawing behavior of stretching the image like WebGL does, we need to make sure - * that the source area is at least 1 pixel in size, otherwise nothing gets drawn when a slice size of 0 is used. - * - * @private - * @param {CanvasRenderingContext2D} context - The context to draw with. - * @param {CanvasImageSource} textureSource - The source to draw. - * @param {number} w - width of the texture - * @param {number} h - height of the texture - * @param {number} x1 - x index 1 - * @param {number} y1 - y index 1 - * @param {number} x2 - x index 2 - * @param {number} y2 - y index 2 - */ - - - NineSlicePlane.prototype.drawSegment = function drawSegment(context, textureSource, w, h, x1, y1, x2, y2) { - // otherwise you get weird results when using slices of that are 0 wide or high. - var uvs = this.uvs; - var vertices = this.vertices; - - var sw = (uvs[x2] - uvs[x1]) * w; - var sh = (uvs[y2] - uvs[y1]) * h; - var dw = vertices[x2] - vertices[x1]; - var dh = vertices[y2] - vertices[y1]; - - // make sure the source is at least 1 pixel wide and high, otherwise nothing will be drawn. - if (sw < 1) { - sw = 1; - } - - if (sh < 1) { - sh = 1; - } - - // make sure destination is at least 1 pixel wide and high, otherwise you get - // lines when rendering close to original size. - if (dw < 1) { - dw = 1; - } - - if (dh < 1) { - dh = 1; - } - - context.drawImage(textureSource, uvs[x1] * w, uvs[y1] * h, sw, sh, vertices[x1], vertices[y1], dw, dh); - }; - - /** - * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane - * - * @member {number} - */ - - - /** - * Refreshes NineSlicePlane coords. All of them. - */ - NineSlicePlane.prototype._refresh = function _refresh() { - _Plane.prototype._refresh.call(this); - - var uvs = this.uvs; - var texture = this._texture; - - this._origWidth = texture.orig.width; - this._origHeight = texture.orig.height; - - var _uvw = 1.0 / this._origWidth; - var _uvh = 1.0 / this._origHeight; - - uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0; - uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0; - uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; - uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; - - uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth; - uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - _uvw * this._rightWidth; - uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight; - uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - _uvh * this._bottomHeight; - - this.updateHorizontalVertices(); - this.updateVerticalVertices(); - - this.dirty = true; - - this.multiplyUvs(); - }; - - _createClass(NineSlicePlane, [{ - key: 'width', - get: function get() { - return this._width; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._width = value; - this._refresh(); - } - - /** - * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane - * - * @member {number} - */ - - }, { - key: 'height', - get: function get() { - return this._height; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._height = value; - this._refresh(); - } - - /** - * The width of the left column - * - * @member {number} - */ - - }, { - key: 'leftWidth', - get: function get() { - return this._leftWidth; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._leftWidth = value; - this._refresh(); - } - - /** - * The width of the right column - * - * @member {number} - */ - - }, { - key: 'rightWidth', - get: function get() { - return this._rightWidth; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._rightWidth = value; - this._refresh(); - } - - /** - * The height of the top row - * - * @member {number} - */ - - }, { - key: 'topHeight', - get: function get() { - return this._topHeight; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._topHeight = value; - this._refresh(); - } - - /** - * The height of the bottom row - * - * @member {number} - */ - - }, { - key: 'bottomHeight', - get: function get() { - return this._bottomHeight; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._bottomHeight = value; - this._refresh(); - } - }]); - - return NineSlicePlane; -}(_Plane3.default); - -exports.default = NineSlicePlane; - -},{"./Plane":168}],168:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _Mesh2 = require('./Mesh'); - -var _Mesh3 = _interopRequireDefault(_Mesh2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * The Plane allows you to draw a texture across several points and them manipulate these points - * - *```js - * for (let i = 0; i < 20; i++) { - * points.push(new PIXI.Point(i * 50, 0)); - * }; - * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points); - * ``` - * - * @class - * @extends PIXI.mesh.Mesh - * @memberof PIXI.mesh - * - */ -var Plane = function (_Mesh) { - _inherits(Plane, _Mesh); - - /** - * @param {PIXI.Texture} texture - The texture to use on the Plane. - * @param {number} verticesX - The number of vertices in the x-axis - * @param {number} verticesY - The number of vertices in the y-axis - */ - function Plane(texture, verticesX, verticesY) { - _classCallCheck(this, Plane); - - /** - * Tracker for if the Plane is ready to be drawn. Needed because Mesh ctor can - * call _onTextureUpdated which could call refresh too early. - * - * @member {boolean} - * @private - */ - var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); - - _this._ready = true; - - _this.verticesX = verticesX || 10; - _this.verticesY = verticesY || 10; - - _this.drawMode = _Mesh3.default.DRAW_MODES.TRIANGLES; - _this.refresh(); - return _this; - } - - /** - * Refreshes plane coordinates - * - */ - - - Plane.prototype._refresh = function _refresh() { - var texture = this._texture; - var total = this.verticesX * this.verticesY; - var verts = []; - var colors = []; - var uvs = []; - var indices = []; - - var segmentsX = this.verticesX - 1; - var segmentsY = this.verticesY - 1; - - var sizeX = texture.width / segmentsX; - var sizeY = texture.height / segmentsY; - - for (var i = 0; i < total; i++) { - var x = i % this.verticesX; - var y = i / this.verticesX | 0; - - verts.push(x * sizeX, y * sizeY); - - uvs.push(x / segmentsX, y / segmentsY); - } - - // cons - - var totalSub = segmentsX * segmentsY; - - for (var _i = 0; _i < totalSub; _i++) { - var xpos = _i % segmentsX; - var ypos = _i / segmentsX | 0; - - var value = ypos * this.verticesX + xpos; - var value2 = ypos * this.verticesX + xpos + 1; - var value3 = (ypos + 1) * this.verticesX + xpos; - var value4 = (ypos + 1) * this.verticesX + xpos + 1; - - indices.push(value, value2, value3); - indices.push(value2, value4, value3); - } - - // console.log(indices) - this.vertices = new Float32Array(verts); - this.uvs = new Float32Array(uvs); - this.colors = new Float32Array(colors); - this.indices = new Uint16Array(indices); - this.indexDirty = true; - - this.multiplyUvs(); - }; - - /** - * Clear texture UVs when new texture is set - * - * @private - */ - - - Plane.prototype._onTextureUpdate = function _onTextureUpdate() { - _Mesh3.default.prototype._onTextureUpdate.call(this); - - // wait for the Plane ctor to finish before calling refresh - if (this._ready) { - this.refresh(); - } - }; - - return Plane; -}(_Mesh3.default); - -exports.default = Plane; - -},{"./Mesh":166}],169:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _Mesh2 = require('./Mesh'); - -var _Mesh3 = _interopRequireDefault(_Mesh2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * The rope allows you to draw a texture across several points and them manipulate these points - * - *```js - * for (let i = 0; i < 20; i++) { - * points.push(new PIXI.Point(i * 50, 0)); - * }; - * let rope = new PIXI.Rope(PIXI.Texture.fromImage("snake.png"), points); - * ``` - * - * @class - * @extends PIXI.mesh.Mesh - * @memberof PIXI.mesh - * - */ -var Rope = function (_Mesh) { - _inherits(Rope, _Mesh); - - /** - * @param {PIXI.Texture} texture - The texture to use on the rope. - * @param {PIXI.Point[]} points - An array of {@link PIXI.Point} objects to construct this rope. - */ - function Rope(texture, points) { - _classCallCheck(this, Rope); - - /** - * An array of points that determine the rope - * - * @member {PIXI.Point[]} - */ - var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); - - _this.points = points; - - /** - * An array of vertices used to construct this rope. - * - * @member {Float32Array} - */ - _this.vertices = new Float32Array(points.length * 4); - - /** - * The WebGL Uvs of the rope. - * - * @member {Float32Array} - */ - _this.uvs = new Float32Array(points.length * 4); - - /** - * An array containing the color components - * - * @member {Float32Array} - */ - _this.colors = new Float32Array(points.length * 2); - - /** - * An array containing the indices of the vertices - * - * @member {Uint16Array} - */ - _this.indices = new Uint16Array(points.length * 2); - - /** - * refreshes vertices on every updateTransform - * @member {boolean} - * @default true - */ - _this.autoUpdate = true; - - _this.refresh(); - return _this; - } - - /** - * Refreshes - * - */ - - - Rope.prototype._refresh = function _refresh() { - var points = this.points; - - // if too little points, or texture hasn't got UVs set yet just move on. - if (points.length < 1 || !this._texture._uvs) { - return; - } - - // if the number of points has changed we will need to recreate the arraybuffers - if (this.vertices.length / 4 !== points.length) { - this.vertices = new Float32Array(points.length * 4); - this.uvs = new Float32Array(points.length * 4); - this.colors = new Float32Array(points.length * 2); - this.indices = new Uint16Array(points.length * 2); - } - - var uvs = this.uvs; - - var indices = this.indices; - var colors = this.colors; - - uvs[0] = 0; - uvs[1] = 0; - uvs[2] = 0; - uvs[3] = 1; - - colors[0] = 1; - colors[1] = 1; - - indices[0] = 0; - indices[1] = 1; - - var total = points.length; - - for (var i = 1; i < total; i++) { - // time to do some smart drawing! - var index = i * 4; - var amount = i / (total - 1); - - uvs[index] = amount; - uvs[index + 1] = 0; - - uvs[index + 2] = amount; - uvs[index + 3] = 1; - - index = i * 2; - colors[index] = 1; - colors[index + 1] = 1; - - index = i * 2; - indices[index] = index; - indices[index + 1] = index + 1; - } - - // ensure that the changes are uploaded - this.dirty++; - this.indexDirty++; - - this.multiplyUvs(); - this.refreshVertices(); - }; - - /** - * refreshes vertices of Rope mesh - */ - - - Rope.prototype.refreshVertices = function refreshVertices() { - var points = this.points; - - if (points.length < 1) { - return; - } - - var lastPoint = points[0]; - var nextPoint = void 0; - var perpX = 0; - var perpY = 0; - - // this.count -= 0.2; - - var vertices = this.vertices; - var total = points.length; - - for (var i = 0; i < total; i++) { - var point = points[i]; - var index = i * 4; - - if (i < points.length - 1) { - nextPoint = points[i + 1]; - } else { - nextPoint = point; - } - - perpY = -(nextPoint.x - lastPoint.x); - perpX = nextPoint.y - lastPoint.y; - - var ratio = (1 - i / (total - 1)) * 10; - - if (ratio > 1) { - ratio = 1; - } - - var perpLength = Math.sqrt(perpX * perpX + perpY * perpY); - var num = this._texture.height / 2; // (20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio; - - perpX /= perpLength; - perpY /= perpLength; - - perpX *= num; - perpY *= num; - - vertices[index] = point.x + perpX; - vertices[index + 1] = point.y + perpY; - vertices[index + 2] = point.x - perpX; - vertices[index + 3] = point.y - perpY; - - lastPoint = point; - } - }; - - /** - * Updates the object transform for rendering - * - * @private - */ - - - Rope.prototype.updateTransform = function updateTransform() { - if (this.autoUpdate) { - this.refreshVertices(); - } - this.containerUpdateTransform(); - }; - - return Rope; -}(_Mesh3.default); - -exports.default = Rope; - -},{"./Mesh":166}],170:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _core = require('../../core'); - -var core = _interopRequireWildcard(_core); - -var _Mesh = require('../Mesh'); - -var _Mesh2 = _interopRequireDefault(_Mesh); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * Renderer dedicated to meshes. - * - * @class - * @private - * @memberof PIXI - */ -var MeshSpriteRenderer = function () { - /** - * @param {PIXI.CanvasRenderer} renderer - The renderer this downport works for - */ - function MeshSpriteRenderer(renderer) { - _classCallCheck(this, MeshSpriteRenderer); - - this.renderer = renderer; - } - - /** - * Renders the Mesh - * - * @param {PIXI.mesh.Mesh} mesh - the Mesh to render - */ - - - MeshSpriteRenderer.prototype.render = function render(mesh) { - var renderer = this.renderer; - var context = renderer.context; - - var transform = mesh.worldTransform; - var res = renderer.resolution; - - if (renderer.roundPixels) { - context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); - } else { - context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); - } - - renderer.setBlendMode(mesh.blendMode); - - if (mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH) { - this._renderTriangleMesh(mesh); - } else { - this._renderTriangles(mesh); - } - }; - - /** - * Draws the object in Triangle Mesh mode - * - * @private - * @param {PIXI.mesh.Mesh} mesh - the Mesh to render - */ - - - MeshSpriteRenderer.prototype._renderTriangleMesh = function _renderTriangleMesh(mesh) { - // draw triangles!! - var length = mesh.vertices.length / 2; - - for (var i = 0; i < length - 2; i++) { - // draw some triangles! - var index = i * 2; - - this._renderDrawTriangle(mesh, index, index + 2, index + 4); - } - }; - - /** - * Draws the object in triangle mode using canvas - * - * @private - * @param {PIXI.mesh.Mesh} mesh - the current mesh - */ - - - MeshSpriteRenderer.prototype._renderTriangles = function _renderTriangles(mesh) { - // draw triangles!! - var indices = mesh.indices; - var length = indices.length; - - for (var i = 0; i < length; i += 3) { - // draw some triangles! - var index0 = indices[i] * 2; - var index1 = indices[i + 1] * 2; - var index2 = indices[i + 2] * 2; - - this._renderDrawTriangle(mesh, index0, index1, index2); - } - }; - - /** - * Draws one of the triangles that from the Mesh - * - * @private - * @param {PIXI.mesh.Mesh} mesh - the current mesh - * @param {number} index0 - the index of the first vertex - * @param {number} index1 - the index of the second vertex - * @param {number} index2 - the index of the third vertex - */ - - - MeshSpriteRenderer.prototype._renderDrawTriangle = function _renderDrawTriangle(mesh, index0, index1, index2) { - var context = this.renderer.context; - var uvs = mesh.uvs; - var vertices = mesh.vertices; - var texture = mesh._texture; - - if (!texture.valid) { - return; - } - - var base = texture.baseTexture; - var textureSource = base.source; - var textureWidth = base.width; - var textureHeight = base.height; - - var u0 = void 0; - var u1 = void 0; - var u2 = void 0; - var v0 = void 0; - var v1 = void 0; - var v2 = void 0; - - if (mesh.uploadUvTransform) { - var ut = mesh._uvTransform.mapCoord; - - u0 = (uvs[index0] * ut.a + uvs[index0 + 1] * ut.c + ut.tx) * base.width; - u1 = (uvs[index1] * ut.a + uvs[index1 + 1] * ut.c + ut.tx) * base.width; - u2 = (uvs[index2] * ut.a + uvs[index2 + 1] * ut.c + ut.tx) * base.width; - v0 = (uvs[index0] * ut.b + uvs[index0 + 1] * ut.d + ut.ty) * base.height; - v1 = (uvs[index1] * ut.b + uvs[index1 + 1] * ut.d + ut.ty) * base.height; - v2 = (uvs[index2] * ut.b + uvs[index2 + 1] * ut.d + ut.ty) * base.height; - } else { - u0 = uvs[index0] * base.width; - u1 = uvs[index1] * base.width; - u2 = uvs[index2] * base.width; - v0 = uvs[index0 + 1] * base.height; - v1 = uvs[index1 + 1] * base.height; - v2 = uvs[index2 + 1] * base.height; - } - - var x0 = vertices[index0]; - var x1 = vertices[index1]; - var x2 = vertices[index2]; - var y0 = vertices[index0 + 1]; - var y1 = vertices[index1 + 1]; - var y2 = vertices[index2 + 1]; - - if (mesh.canvasPadding > 0) { - var paddingX = mesh.canvasPadding / mesh.worldTransform.a; - var paddingY = mesh.canvasPadding / mesh.worldTransform.d; - var centerX = (x0 + x1 + x2) / 3; - var centerY = (y0 + y1 + y2) / 3; - - var normX = x0 - centerX; - var normY = y0 - centerY; - - var dist = Math.sqrt(normX * normX + normY * normY); - - x0 = centerX + normX / dist * (dist + paddingX); - y0 = centerY + normY / dist * (dist + paddingY); - - // - - normX = x1 - centerX; - normY = y1 - centerY; - - dist = Math.sqrt(normX * normX + normY * normY); - x1 = centerX + normX / dist * (dist + paddingX); - y1 = centerY + normY / dist * (dist + paddingY); - - normX = x2 - centerX; - normY = y2 - centerY; - - dist = Math.sqrt(normX * normX + normY * normY); - x2 = centerX + normX / dist * (dist + paddingX); - y2 = centerY + normY / dist * (dist + paddingY); - } - - context.save(); - context.beginPath(); - - context.moveTo(x0, y0); - context.lineTo(x1, y1); - context.lineTo(x2, y2); - - context.closePath(); - - context.clip(); - - // Compute matrix transform - var delta = u0 * v1 + v0 * u2 + u1 * v2 - v1 * u2 - v0 * u1 - u0 * v2; - var deltaA = x0 * v1 + v0 * x2 + x1 * v2 - v1 * x2 - v0 * x1 - x0 * v2; - var deltaB = u0 * x1 + x0 * u2 + u1 * x2 - x1 * u2 - x0 * u1 - u0 * x2; - var deltaC = u0 * v1 * x2 + v0 * x1 * u2 + x0 * u1 * v2 - x0 * v1 * u2 - v0 * u1 * x2 - u0 * x1 * v2; - var deltaD = y0 * v1 + v0 * y2 + y1 * v2 - v1 * y2 - v0 * y1 - y0 * v2; - var deltaE = u0 * y1 + y0 * u2 + u1 * y2 - y1 * u2 - y0 * u1 - u0 * y2; - var deltaF = u0 * v1 * y2 + v0 * y1 * u2 + y0 * u1 * v2 - y0 * v1 * u2 - v0 * u1 * y2 - u0 * y1 * v2; - - context.transform(deltaA / delta, deltaD / delta, deltaB / delta, deltaE / delta, deltaC / delta, deltaF / delta); - - context.drawImage(textureSource, 0, 0, textureWidth * base.resolution, textureHeight * base.resolution, 0, 0, textureWidth, textureHeight); - - context.restore(); - }; - - /** - * Renders a flat Mesh - * - * @private - * @param {PIXI.mesh.Mesh} mesh - The Mesh to render - */ - - - MeshSpriteRenderer.prototype.renderMeshFlat = function renderMeshFlat(mesh) { - var context = this.renderer.context; - var vertices = mesh.vertices; - var length = vertices.length / 2; - - // this.count++; - - context.beginPath(); - - for (var i = 1; i < length - 2; ++i) { - // draw some triangles! - var index = i * 2; - - var x0 = vertices[index]; - var y0 = vertices[index + 1]; - - var x1 = vertices[index + 2]; - var y1 = vertices[index + 3]; - - var x2 = vertices[index + 4]; - var y2 = vertices[index + 5]; - - context.moveTo(x0, y0); - context.lineTo(x1, y1); - context.lineTo(x2, y2); - } - - context.fillStyle = '#FF0000'; - context.fill(); - context.closePath(); - }; - - /** - * destroy the the renderer. - * - */ - - - MeshSpriteRenderer.prototype.destroy = function destroy() { - this.renderer = null; - }; - - return MeshSpriteRenderer; -}(); - -exports.default = MeshSpriteRenderer; - - -core.CanvasRenderer.registerPlugin('mesh', MeshSpriteRenderer); - -},{"../../core":65,"../Mesh":166}],171:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _Mesh = require('./Mesh'); - -Object.defineProperty(exports, 'Mesh', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Mesh).default; - } -}); - -var _MeshRenderer = require('./webgl/MeshRenderer'); - -Object.defineProperty(exports, 'MeshRenderer', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_MeshRenderer).default; - } -}); - -var _CanvasMeshRenderer = require('./canvas/CanvasMeshRenderer'); - -Object.defineProperty(exports, 'CanvasMeshRenderer', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_CanvasMeshRenderer).default; - } -}); - -var _Plane = require('./Plane'); - -Object.defineProperty(exports, 'Plane', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Plane).default; - } -}); - -var _NineSlicePlane = require('./NineSlicePlane'); - -Object.defineProperty(exports, 'NineSlicePlane', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_NineSlicePlane).default; - } -}); - -var _Rope = require('./Rope'); - -Object.defineProperty(exports, 'Rope', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Rope).default; - } -}); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -},{"./Mesh":166,"./NineSlicePlane":167,"./Plane":168,"./Rope":169,"./canvas/CanvasMeshRenderer":170,"./webgl/MeshRenderer":172}],172:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _core = require('../../core'); - -var core = _interopRequireWildcard(_core); - -var _pixiGlCore = require('pixi-gl-core'); - -var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); - -var _Mesh = require('../Mesh'); - -var _Mesh2 = _interopRequireDefault(_Mesh); - -var _path = require('path'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -var matrixIdentity = core.Matrix.IDENTITY; - -/** - * WebGL renderer plugin for tiling sprites - * - * @class - * @memberof PIXI - * @extends PIXI.ObjectRenderer - */ - -var MeshRenderer = function (_core$ObjectRenderer) { - _inherits(MeshRenderer, _core$ObjectRenderer); - - /** - * constructor for renderer - * - * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. - */ - function MeshRenderer(renderer) { - _classCallCheck(this, MeshRenderer); - - var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); - - _this.shader = null; - return _this; - } - - /** - * Sets up the renderer context and necessary buffers. - * - * @private - */ - - - MeshRenderer.prototype.onContextChange = function onContextChange() { - var gl = this.renderer.gl; - - this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n'); - }; - - /** - * renders mesh - * - * @param {PIXI.mesh.Mesh} mesh mesh instance - */ - - - MeshRenderer.prototype.render = function render(mesh) { - var renderer = this.renderer; - var gl = renderer.gl; - var texture = mesh._texture; - - if (!texture.valid) { - return; - } - - var glData = mesh._glDatas[renderer.CONTEXT_UID]; - - if (!glData) { - renderer.bindVao(null); - - glData = { - shader: this.shader, - vertexBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.vertices, gl.STREAM_DRAW), - uvBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.uvs, gl.STREAM_DRAW), - indexBuffer: _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, mesh.indices, gl.STATIC_DRAW), - // build the vao object that will render.. - vao: null, - dirty: mesh.dirty, - indexDirty: mesh.indexDirty - }; - - // build the vao object that will render.. - glData.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(glData.indexBuffer).addAttribute(glData.vertexBuffer, glData.shader.attributes.aVertexPosition, gl.FLOAT, false, 2 * 4, 0).addAttribute(glData.uvBuffer, glData.shader.attributes.aTextureCoord, gl.FLOAT, false, 2 * 4, 0); - - mesh._glDatas[renderer.CONTEXT_UID] = glData; - } - - renderer.bindVao(glData.vao); - - if (mesh.dirty !== glData.dirty) { - glData.dirty = mesh.dirty; - glData.uvBuffer.upload(mesh.uvs); - } - - if (mesh.indexDirty !== glData.indexDirty) { - glData.indexDirty = mesh.indexDirty; - glData.indexBuffer.upload(mesh.indices); - } - - glData.vertexBuffer.upload(mesh.vertices); - - renderer.bindShader(glData.shader); - - glData.shader.uniforms.uSampler = renderer.bindTexture(texture); - - renderer.state.setBlendMode(core.utils.correctBlendMode(mesh.blendMode, texture.baseTexture.premultipliedAlpha)); - - if (glData.shader.uniforms.uTransform) { - if (mesh.uploadUvTransform) { - glData.shader.uniforms.uTransform = mesh._uvTransform.mapCoord.toArray(true); - } else { - glData.shader.uniforms.uTransform = matrixIdentity.toArray(true); - } - } - glData.shader.uniforms.translationMatrix = mesh.worldTransform.toArray(true); - - glData.shader.uniforms.uColor = core.utils.premultiplyRgba(mesh.tintRgb, mesh.worldAlpha, glData.shader.uniforms.uColor, texture.baseTexture.premultipliedAlpha); - - var drawMode = mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH ? gl.TRIANGLE_STRIP : gl.TRIANGLES; - - glData.vao.draw(drawMode, mesh.indices.length, 0); - }; - - return MeshRenderer; -}(core.ObjectRenderer); - -exports.default = MeshRenderer; - - -core.WebGLRenderer.registerPlugin('mesh', MeshRenderer); - -},{"../../core":65,"../Mesh":166,"path":23,"pixi-gl-core":12}],173:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _core = require('../core'); - -var core = _interopRequireWildcard(_core); - -var _utils = require('../core/utils'); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * The ParticleContainer class is a really fast version of the Container built solely for speed, - * so use when you need a lot of sprites or particles. The tradeoff of the ParticleContainer is that advanced - * functionality will not work. ParticleContainer implements only the basic object transform (position, scale, rotation). - * Any other functionality like tinting, masking, etc will not work on sprites in this batch. - * - * It's extremely easy to use : - * - * ```js - * let container = new ParticleContainer(); - * - * for (let i = 0; i < 100; ++i) - * { - * let sprite = new PIXI.Sprite.fromImage("myImage.png"); - * container.addChild(sprite); - * } - * ``` - * - * And here you have a hundred sprites that will be rendered at the speed of light. - * - * @class - * @extends PIXI.Container - * @memberof PIXI.particles - */ -var ParticleContainer = function (_core$Container) { - _inherits(ParticleContainer, _core$Container); - - /** - * @param {number} [maxSize=15000] - The maximum number of particles that can be renderer by the container. - * @param {object} [properties] - The properties of children that should be uploaded to the gpu and applied. - * @param {boolean} [properties.scale=false] - When true, scale be uploaded and applied. - * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. - * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. - * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. - * @param {boolean} [properties.alpha=false] - When true, alpha be uploaded and applied. - * @param {number} [batchSize=15000] - Number of particles per batch. - */ - function ParticleContainer() { - var maxSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1500; - var properties = arguments[1]; - var batchSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 16384; - - _classCallCheck(this, ParticleContainer); - - // Making sure the batch size is valid - // 65535 is max vertex index in the index buffer (see ParticleRenderer) - // so max number of particles is 65536 / 4 = 16384 - var _this = _possibleConstructorReturn(this, _core$Container.call(this)); - - var maxBatchSize = 16384; - - if (batchSize > maxBatchSize) { - batchSize = maxBatchSize; - } - - if (batchSize > maxSize) { - batchSize = maxSize; - } - - /** - * Set properties to be dynamic (true) / static (false) - * - * @member {boolean[]} - * @private - */ - _this._properties = [false, true, false, false, false]; - - /** - * @member {number} - * @private - */ - _this._maxSize = maxSize; - - /** - * @member {number} - * @private - */ - _this._batchSize = batchSize; - - /** - * @member {object} - * @private - */ - _this._glBuffers = {}; - - /** - * @member {number} - * @private - */ - _this._bufferToUpdate = 0; - - /** - * @member {boolean} - * - */ - _this.interactiveChildren = false; - - /** - * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` - * to reset the blend mode. - * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL - * @see PIXI.BLEND_MODES - */ - _this.blendMode = core.BLEND_MODES.NORMAL; - - /** - * Used for canvas renderering. If true then the elements will be positioned at the - * nearest pixel. This provides a nice speed boost. - * - * @member {boolean} - * @default true; - */ - _this.roundPixels = true; - - /** - * The texture used to render the children. - * - * @readonly - * @member {BaseTexture} - */ - _this.baseTexture = null; - - _this.setProperties(properties); - - /** - * The tint applied to the container. - * This is a hex value. A value of 0xFFFFFF will remove any tint effect. - * - * @private - * @member {number} - * @default 0xFFFFFF - */ - _this._tint = 0; - _this.tintRgb = new Float32Array(4); - _this.tint = 0xFFFFFF; - return _this; - } - - /** - * Sets the private properties array to dynamic / static based on the passed properties object - * - * @param {object} properties - The properties to be uploaded - */ - - - ParticleContainer.prototype.setProperties = function setProperties(properties) { - if (properties) { - this._properties[0] = 'scale' in properties ? !!properties.scale : this._properties[0]; - this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; - this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; - this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; - this._properties[4] = 'alpha' in properties ? !!properties.alpha : this._properties[4]; - } - }; - - /** - * Updates the object transform for rendering - * - * @private - */ - - - ParticleContainer.prototype.updateTransform = function updateTransform() { - // TODO don't need to! - this.displayObjectUpdateTransform(); - // PIXI.Container.prototype.updateTransform.call( this ); - }; - - /** - * The tint applied to the container. This is a hex value. - * A value of 0xFFFFFF will remove any tint effect. - ** IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. - * @member {number} - * @default 0xFFFFFF - */ - - - /** - * Renders the container using the WebGL renderer - * - * @private - * @param {PIXI.WebGLRenderer} renderer - The webgl renderer - */ - ParticleContainer.prototype.renderWebGL = function renderWebGL(renderer) { - var _this2 = this; - - if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { - return; - } - - if (!this.baseTexture) { - this.baseTexture = this.children[0]._texture.baseTexture; - if (!this.baseTexture.hasLoaded) { - this.baseTexture.once('update', function () { - return _this2.onChildrenChange(0); - }); - } - } - - renderer.setObjectRenderer(renderer.plugins.particle); - renderer.plugins.particle.render(this); - }; - - /** - * Set the flag that static data should be updated to true - * - * @private - * @param {number} smallestChildIndex - The smallest child index - */ - - - ParticleContainer.prototype.onChildrenChange = function onChildrenChange(smallestChildIndex) { - var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); - - if (bufferIndex < this._bufferToUpdate) { - this._bufferToUpdate = bufferIndex; - } - }; - - /** - * Renders the object using the Canvas renderer - * - * @private - * @param {PIXI.CanvasRenderer} renderer - The canvas renderer - */ - - - ParticleContainer.prototype.renderCanvas = function renderCanvas(renderer) { - if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { - return; - } - - var context = renderer.context; - var transform = this.worldTransform; - var isRotated = true; - - var positionX = 0; - var positionY = 0; - - var finalWidth = 0; - var finalHeight = 0; - - var compositeOperation = renderer.blendModes[this.blendMode]; - - if (compositeOperation !== context.globalCompositeOperation) { - context.globalCompositeOperation = compositeOperation; - } - - context.globalAlpha = this.worldAlpha; - - this.displayObjectUpdateTransform(); - - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i]; - - if (!child.visible) { - continue; - } - - var frame = child._texture.frame; - - context.globalAlpha = this.worldAlpha * child.alpha; - - if (child.rotation % (Math.PI * 2) === 0) { - // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { - context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx * renderer.resolution, transform.ty * renderer.resolution); - - isRotated = false; - } - - positionX = child.anchor.x * (-frame.width * child.scale.x) + child.position.x + 0.5; - positionY = child.anchor.y * (-frame.height * child.scale.y) + child.position.y + 0.5; - - finalWidth = frame.width * child.scale.x; - finalHeight = frame.height * child.scale.y; - } else { - if (!isRotated) { - isRotated = true; - } - - child.displayObjectUpdateTransform(); - - var childTransform = child.worldTransform; - - if (renderer.roundPixels) { - context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution | 0, childTransform.ty * renderer.resolution | 0); - } else { - context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution, childTransform.ty * renderer.resolution); - } - - positionX = child.anchor.x * -frame.width + 0.5; - positionY = child.anchor.y * -frame.height + 0.5; - - finalWidth = frame.width; - finalHeight = frame.height; - } - - var resolution = child._texture.baseTexture.resolution; - - context.drawImage(child._texture.baseTexture.source, frame.x * resolution, frame.y * resolution, frame.width * resolution, frame.height * resolution, positionX * renderer.resolution, positionY * renderer.resolution, finalWidth * renderer.resolution, finalHeight * renderer.resolution); - } - }; - - /** - * Destroys the container - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their - * destroy method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the texture of the child sprite - * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the base texture of the child sprite - */ - - - ParticleContainer.prototype.destroy = function destroy(options) { - _core$Container.prototype.destroy.call(this, options); - - if (this._buffers) { - for (var i = 0; i < this._buffers.length; ++i) { - this._buffers[i].destroy(); - } - } - - this._properties = null; - this._buffers = null; - }; - - _createClass(ParticleContainer, [{ - key: 'tint', - get: function get() { - return this._tint; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._tint = value; - (0, _utils.hex2rgb)(value, this.tintRgb); - } - }]); - - return ParticleContainer; -}(core.Container); - -exports.default = ParticleContainer; - -},{"../core":65,"../core/utils":124}],174:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _ParticleContainer = require('./ParticleContainer'); - -Object.defineProperty(exports, 'ParticleContainer', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_ParticleContainer).default; - } -}); - -var _ParticleRenderer = require('./webgl/ParticleRenderer'); - -Object.defineProperty(exports, 'ParticleRenderer', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_ParticleRenderer).default; - } -}); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -},{"./ParticleContainer":173,"./webgl/ParticleRenderer":176}],175:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _pixiGlCore = require('pixi-gl-core'); - -var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); - -var _createIndicesForQuads = require('../../core/utils/createIndicesForQuads'); - -var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * @author Mat Groves - * - * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ - * for creating the original PixiJS version! - * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that - * they now share 4 bytes on the vertex buffer - * - * Heavily inspired by LibGDX's ParticleBuffer: - * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java - */ - -/** - * The particle buffer manages the static and dynamic buffers for a particle container. - * - * @class - * @private - * @memberof PIXI - */ -var ParticleBuffer = function () { - /** - * @param {WebGLRenderingContext} gl - The rendering context. - * @param {object} properties - The properties to upload. - * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. - * @param {number} size - The size of the batch. - */ - function ParticleBuffer(gl, properties, dynamicPropertyFlags, size) { - _classCallCheck(this, ParticleBuffer); - - /** - * The current WebGL drawing context. - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * Size of a single vertex. - * - * @member {number} - */ - this.vertSize = 2; - - /** - * Size of a single vertex in bytes. - * - * @member {number} - */ - this.vertByteSize = this.vertSize * 4; - - /** - * The number of particles the buffer can hold - * - * @member {number} - */ - this.size = size; - - /** - * A list of the properties that are dynamic. - * - * @member {object[]} - */ - this.dynamicProperties = []; - - /** - * A list of the properties that are static. - * - * @member {object[]} - */ - this.staticProperties = []; - - for (var i = 0; i < properties.length; ++i) { - var property = properties[i]; - - // Make copy of properties object so that when we edit the offset it doesn't - // change all other instances of the object literal - property = { - attribute: property.attribute, - size: property.size, - uploadFunction: property.uploadFunction, - offset: property.offset - }; - - if (dynamicPropertyFlags[i]) { - this.dynamicProperties.push(property); - } else { - this.staticProperties.push(property); - } - } - - this.staticStride = 0; - this.staticBuffer = null; - this.staticData = null; - - this.dynamicStride = 0; - this.dynamicBuffer = null; - this.dynamicData = null; - - this.initBuffers(); - } - - /** - * Sets up the renderer context and necessary buffers. - * - * @private - */ - - - ParticleBuffer.prototype.initBuffers = function initBuffers() { - var gl = this.gl; - var dynamicOffset = 0; - - /** - * Holds the indices of the geometry (quads) to draw - * - * @member {Uint16Array} - */ - this.indices = (0, _createIndicesForQuads2.default)(this.size); - this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); - - this.dynamicStride = 0; - - for (var i = 0; i < this.dynamicProperties.length; ++i) { - var property = this.dynamicProperties[i]; - - property.offset = dynamicOffset; - dynamicOffset += property.size; - this.dynamicStride += property.size; - } - - this.dynamicData = new Float32Array(this.size * this.dynamicStride * 4); - this.dynamicBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.dynamicData, gl.STREAM_DRAW); - - // static // - var staticOffset = 0; - - this.staticStride = 0; - - for (var _i = 0; _i < this.staticProperties.length; ++_i) { - var _property = this.staticProperties[_i]; - - _property.offset = staticOffset; - staticOffset += _property.size; - this.staticStride += _property.size; - } - - this.staticData = new Float32Array(this.size * this.staticStride * 4); - this.staticBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.staticData, gl.STATIC_DRAW); - - this.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(this.indexBuffer); - - for (var _i2 = 0; _i2 < this.dynamicProperties.length; ++_i2) { - var _property2 = this.dynamicProperties[_i2]; - - this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.FLOAT, false, this.dynamicStride * 4, _property2.offset * 4); - } - - for (var _i3 = 0; _i3 < this.staticProperties.length; ++_i3) { - var _property3 = this.staticProperties[_i3]; - - this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.FLOAT, false, this.staticStride * 4, _property3.offset * 4); - } - }; - - /** - * Uploads the dynamic properties. - * - * @param {PIXI.DisplayObject[]} children - The children to upload. - * @param {number} startIndex - The index to start at. - * @param {number} amount - The number to upload. - */ - - - ParticleBuffer.prototype.uploadDynamic = function uploadDynamic(children, startIndex, amount) { - for (var i = 0; i < this.dynamicProperties.length; i++) { - var property = this.dynamicProperties[i]; - - property.uploadFunction(children, startIndex, amount, this.dynamicData, this.dynamicStride, property.offset); - } - - this.dynamicBuffer.upload(); - }; - - /** - * Uploads the static properties. - * - * @param {PIXI.DisplayObject[]} children - The children to upload. - * @param {number} startIndex - The index to start at. - * @param {number} amount - The number to upload. - */ - - - ParticleBuffer.prototype.uploadStatic = function uploadStatic(children, startIndex, amount) { - for (var i = 0; i < this.staticProperties.length; i++) { - var property = this.staticProperties[i]; - - property.uploadFunction(children, startIndex, amount, this.staticData, this.staticStride, property.offset); - } - - this.staticBuffer.upload(); - }; - - /** - * Destroys the ParticleBuffer. - * - */ - - - ParticleBuffer.prototype.destroy = function destroy() { - this.dynamicProperties = null; - this.dynamicData = null; - this.dynamicBuffer.destroy(); - - this.staticProperties = null; - this.staticData = null; - this.staticBuffer.destroy(); - }; - - return ParticleBuffer; -}(); - -exports.default = ParticleBuffer; - -},{"../../core/utils/createIndicesForQuads":122,"pixi-gl-core":12}],176:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _core = require('../../core'); - -var core = _interopRequireWildcard(_core); - -var _ParticleShader = require('./ParticleShader'); - -var _ParticleShader2 = _interopRequireDefault(_ParticleShader); - -var _ParticleBuffer = require('./ParticleBuffer'); - -var _ParticleBuffer2 = _interopRequireDefault(_ParticleBuffer); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * @author Mat Groves - * - * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ - * for creating the original PixiJS version! - * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now - * share 4 bytes on the vertex buffer - * - * Heavily inspired by LibGDX's ParticleRenderer: - * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java - */ - -/** - * - * @class - * @private - * @memberof PIXI - */ -var ParticleRenderer = function (_core$ObjectRenderer) { - _inherits(ParticleRenderer, _core$ObjectRenderer); - - /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. - */ - function ParticleRenderer(renderer) { - _classCallCheck(this, ParticleRenderer); - - // 65535 is max vertex index in the index buffer (see ParticleRenderer) - // so max number of particles is 65536 / 4 = 16384 - // and max number of element in the index buffer is 16384 * 6 = 98304 - // Creating a full index buffer, overhead is 98304 * 2 = 196Ko - // let numIndices = 98304; - - /** - * The default shader that is used if a sprite doesn't have a more specific one. - * - * @member {PIXI.Shader} - */ - var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); - - _this.shader = null; - - _this.indexBuffer = null; - - _this.properties = null; - - _this.tempMatrix = new core.Matrix(); - - _this.CONTEXT_UID = 0; - return _this; - } - - /** - * When there is a WebGL context change - * - * @private - */ - - - ParticleRenderer.prototype.onContextChange = function onContextChange() { - var gl = this.renderer.gl; - - this.CONTEXT_UID = this.renderer.CONTEXT_UID; - - // setup default shader - this.shader = new _ParticleShader2.default(gl); - - this.properties = [ - // verticesData - { - attribute: this.shader.attributes.aVertexPosition, - size: 2, - uploadFunction: this.uploadVertices, - offset: 0 - }, - // positionData - { - attribute: this.shader.attributes.aPositionCoord, - size: 2, - uploadFunction: this.uploadPosition, - offset: 0 - }, - // rotationData - { - attribute: this.shader.attributes.aRotation, - size: 1, - uploadFunction: this.uploadRotation, - offset: 0 - }, - // uvsData - { - attribute: this.shader.attributes.aTextureCoord, - size: 2, - uploadFunction: this.uploadUvs, - offset: 0 - }, - // alphaData - { - attribute: this.shader.attributes.aColor, - size: 1, - uploadFunction: this.uploadAlpha, - offset: 0 - }]; - }; - - /** - * Starts a new particle batch. - * - */ - - - ParticleRenderer.prototype.start = function start() { - this.renderer.bindShader(this.shader); - }; - - /** - * Renders the particle container object. - * - * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer - */ - - - ParticleRenderer.prototype.render = function render(container) { - var children = container.children; - var maxSize = container._maxSize; - var batchSize = container._batchSize; - var renderer = this.renderer; - var totalChildren = children.length; - - if (totalChildren === 0) { - return; - } else if (totalChildren > maxSize) { - totalChildren = maxSize; - } - - var buffers = container._glBuffers[renderer.CONTEXT_UID]; - - if (!buffers) { - buffers = container._glBuffers[renderer.CONTEXT_UID] = this.generateBuffers(container); - } - - var baseTexture = children[0]._texture.baseTexture; - - // if the uvs have not updated then no point rendering just yet! - this.renderer.setBlendMode(core.utils.correctBlendMode(container.blendMode, baseTexture.premultipliedAlpha)); - - var gl = renderer.gl; - - var m = container.worldTransform.copy(this.tempMatrix); - - m.prepend(renderer._activeRenderTarget.projectionMatrix); - - this.shader.uniforms.projectionMatrix = m.toArray(true); - - this.shader.uniforms.uColor = core.utils.premultiplyRgba(container.tintRgb, container.worldAlpha, this.shader.uniforms.uColor, baseTexture.premultipliedAlpha); - - // make sure the texture is bound.. - this.shader.uniforms.uSampler = renderer.bindTexture(baseTexture); - - // now lets upload and render the buffers.. - for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { - var amount = totalChildren - i; - - if (amount > batchSize) { - amount = batchSize; - } - - var buffer = buffers[j]; - - // we always upload the dynamic - buffer.uploadDynamic(children, i, amount); - - // we only upload the static content when we have to! - if (container._bufferToUpdate === j) { - buffer.uploadStatic(children, i, amount); - container._bufferToUpdate = j + 1; - } - - // bind the buffer - renderer.bindVao(buffer.vao); - buffer.vao.draw(gl.TRIANGLES, amount * 6); - } - }; - - /** - * Creates one particle buffer for each child in the container we want to render and updates internal properties - * - * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer - * @return {PIXI.ParticleBuffer[]} The buffers - */ - - - ParticleRenderer.prototype.generateBuffers = function generateBuffers(container) { - var gl = this.renderer.gl; - var buffers = []; - var size = container._maxSize; - var batchSize = container._batchSize; - var dynamicPropertyFlags = container._properties; - - for (var i = 0; i < size; i += batchSize) { - buffers.push(new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize)); - } + /** + * The ObservablePoint object represents a location in a two-dimensional coordinate system, where `x` represents + * the position on the horizontal axis and `y` represents the position on the vertical axis. + * + * An `ObservablePoint` is a point that triggers a callback when the point's position is changed. + * @memberof PIXI + */ + var ObservablePoint = /** @class */ (function () { + /** + * Creates a new `ObservablePoint` + * @param cb - callback function triggered when `x` and/or `y` are changed + * @param scope - owner of callback + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function ObservablePoint(cb, scope, x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + this._x = x; + this._y = y; + this.cb = cb; + this.scope = scope; + } + /** + * Creates a clone of this point. + * The callback and scope params can be overridden otherwise they will default + * to the clone object's values. + * @override + * @param cb - The callback function triggered when `x` and/or `y` are changed + * @param scope - The owner of the callback + * @returns a copy of this observable point + */ + ObservablePoint.prototype.clone = function (cb, scope) { + if (cb === void 0) { cb = this.cb; } + if (scope === void 0) { scope = this.scope; } + return new ObservablePoint(cb, scope, this._x, this._y); + }; + /** + * Sets the point to a new `x` and `y` position. + * If `y` is omitted, both `x` and `y` will be set to `x`. + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=x] - position of the point on the y axis + * @returns The observable point instance itself + */ + ObservablePoint.prototype.set = function (x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = x; } + if (this._x !== x || this._y !== y) { + this._x = x; + this._y = y; + this.cb.call(this.scope); + } + return this; + }; + /** + * Copies x and y from the given point (`p`) + * @param p - The point to copy from. Can be any of type that is or extends `IPointData` + * @returns The observable point instance itself + */ + ObservablePoint.prototype.copyFrom = function (p) { + if (this._x !== p.x || this._y !== p.y) { + this._x = p.x; + this._y = p.y; + this.cb.call(this.scope); + } + return this; + }; + /** + * Copies this point's x and y into that of the given point (`p`) + * @param p - The point to copy to. Can be any of type that is or extends `IPointData` + * @returns The point (`p`) with values updated + */ + ObservablePoint.prototype.copyTo = function (p) { + p.set(this._x, this._y); + return p; + }; + /** + * Accepts another point (`p`) and returns `true` if the given point is equal to this point + * @param p - The point to check + * @returns Returns `true` if both `x` and `y` are equal + */ + ObservablePoint.prototype.equals = function (p) { + return (p.x === this._x) && (p.y === this._y); + }; + ObservablePoint.prototype.toString = function () { + return "[@pixi/math:ObservablePoint x=" + 0 + " y=" + 0 + " scope=" + this.scope + "]"; + }; + Object.defineProperty(ObservablePoint.prototype, "x", { + /** Position of the observable point on the x axis. */ + get: function () { + return this._x; + }, + set: function (value) { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ObservablePoint.prototype, "y", { + /** Position of the observable point on the y axis. */ + get: function () { + return this._y; + }, + set: function (value) { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + }, + enumerable: false, + configurable: true + }); + return ObservablePoint; + }()); - return buffers; - }; + /** + * The PixiJS Matrix as a class makes it a lot faster. + * + * Here is a representation of it: + * ```js + * | a | c | tx| + * | b | d | ty| + * | 0 | 0 | 1 | + * ``` + * @memberof PIXI + */ + var Matrix = /** @class */ (function () { + /** + * @param a - x scale + * @param b - y skew + * @param c - x skew + * @param d - y scale + * @param tx - x translation + * @param ty - y translation + */ + function Matrix(a, b, c, d, tx, ty) { + if (a === void 0) { a = 1; } + if (b === void 0) { b = 0; } + if (c === void 0) { c = 0; } + if (d === void 0) { d = 1; } + if (tx === void 0) { tx = 0; } + if (ty === void 0) { ty = 0; } + this.array = null; + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + } + /** + * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * @param array - The array that the matrix will be populated from. + */ + Matrix.prototype.fromArray = function (array) { + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; + }; + /** + * Sets the matrix properties. + * @param a - Matrix component + * @param b - Matrix component + * @param c - Matrix component + * @param d - Matrix component + * @param tx - Matrix component + * @param ty - Matrix component + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.set = function (a, b, c, d, tx, ty) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + return this; + }; + /** + * Creates an array from the current Matrix object. + * @param transpose - Whether we need to transpose the matrix or not + * @param [out=new Float32Array(9)] - If provided the array will be assigned to out + * @returns The newly created array which contains the matrix + */ + Matrix.prototype.toArray = function (transpose, out) { + if (!this.array) { + this.array = new Float32Array(9); + } + var array = out || this.array; + if (transpose) { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } + else { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + return array; + }; + /** + * Get a new position with the current transformation applied. + * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) + * @param pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @returns {PIXI.Point} The new point, transformed through this matrix + */ + Matrix.prototype.apply = function (pos, newPos) { + newPos = (newPos || new Point()); + var x = pos.x; + var y = pos.y; + newPos.x = (this.a * x) + (this.c * y) + this.tx; + newPos.y = (this.b * x) + (this.d * y) + this.ty; + return newPos; + }; + /** + * Get a new position with the inverse of the current transformation applied. + * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) + * @param pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @returns {PIXI.Point} The new point, inverse-transformed through this matrix + */ + Matrix.prototype.applyInverse = function (pos, newPos) { + newPos = (newPos || new Point()); + var id = 1 / ((this.a * this.d) + (this.c * -this.b)); + var x = pos.x; + var y = pos.y; + newPos.x = (this.d * id * x) + (-this.c * id * y) + (((this.ty * this.c) - (this.tx * this.d)) * id); + newPos.y = (this.a * id * y) + (-this.b * id * x) + (((-this.ty * this.a) + (this.tx * this.b)) * id); + return newPos; + }; + /** + * Translates the matrix on the x and y. + * @param x - How much to translate x by + * @param y - How much to translate y by + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.translate = function (x, y) { + this.tx += x; + this.ty += y; + return this; + }; + /** + * Applies a scale transformation to the matrix. + * @param x - The amount to scale horizontally + * @param y - The amount to scale vertically + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.scale = function (x, y) { + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + return this; + }; + /** + * Applies a rotation transformation to the matrix. + * @param angle - The angle in radians. + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.rotate = function (angle) { + var cos = Math.cos(angle); + var sin = Math.sin(angle); + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + this.a = (a1 * cos) - (this.b * sin); + this.b = (a1 * sin) + (this.b * cos); + this.c = (c1 * cos) - (this.d * sin); + this.d = (c1 * sin) + (this.d * cos); + this.tx = (tx1 * cos) - (this.ty * sin); + this.ty = (tx1 * sin) + (this.ty * cos); + return this; + }; + /** + * Appends the given Matrix to this Matrix. + * @param matrix - The matrix to append. + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.append = function (matrix) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + this.a = (matrix.a * a1) + (matrix.b * c1); + this.b = (matrix.a * b1) + (matrix.b * d1); + this.c = (matrix.c * a1) + (matrix.d * c1); + this.d = (matrix.c * b1) + (matrix.d * d1); + this.tx = (matrix.tx * a1) + (matrix.ty * c1) + this.tx; + this.ty = (matrix.tx * b1) + (matrix.ty * d1) + this.ty; + return this; + }; + /** + * Sets the matrix based on all the available properties + * @param x - Position on the x axis + * @param y - Position on the y axis + * @param pivotX - Pivot on the x axis + * @param pivotY - Pivot on the y axis + * @param scaleX - Scale on the x axis + * @param scaleY - Scale on the y axis + * @param rotation - Rotation in radians + * @param skewX - Skew on the x axis + * @param skewY - Skew on the y axis + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.setTransform = function (x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { + this.a = Math.cos(rotation + skewY) * scaleX; + this.b = Math.sin(rotation + skewY) * scaleX; + this.c = -Math.sin(rotation - skewX) * scaleY; + this.d = Math.cos(rotation - skewX) * scaleY; + this.tx = x - ((pivotX * this.a) + (pivotY * this.c)); + this.ty = y - ((pivotX * this.b) + (pivotY * this.d)); + return this; + }; + /** + * Prepends the given Matrix to this Matrix. + * @param matrix - The matrix to prepend + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.prepend = function (matrix) { + var tx1 = this.tx; + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { + var a1 = this.a; + var c1 = this.c; + this.a = (a1 * matrix.a) + (this.b * matrix.c); + this.b = (a1 * matrix.b) + (this.b * matrix.d); + this.c = (c1 * matrix.a) + (this.d * matrix.c); + this.d = (c1 * matrix.b) + (this.d * matrix.d); + } + this.tx = (tx1 * matrix.a) + (this.ty * matrix.c) + matrix.tx; + this.ty = (tx1 * matrix.b) + (this.ty * matrix.d) + matrix.ty; + return this; + }; + /** + * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * @param transform - The transform to apply the properties to. + * @returns The transform with the newly applied properties + */ + Matrix.prototype.decompose = function (transform) { + // sort out rotation / skew.. + var a = this.a; + var b = this.b; + var c = this.c; + var d = this.d; + var pivot = transform.pivot; + var skewX = -Math.atan2(-c, d); + var skewY = Math.atan2(b, a); + var delta = Math.abs(skewX + skewY); + if (delta < 0.00001 || Math.abs(PI_2 - delta) < 0.00001) { + transform.rotation = skewY; + transform.skew.x = transform.skew.y = 0; + } + else { + transform.rotation = 0; + transform.skew.x = skewX; + transform.skew.y = skewY; + } + // next set scale + transform.scale.x = Math.sqrt((a * a) + (b * b)); + transform.scale.y = Math.sqrt((c * c) + (d * d)); + // next set position + transform.position.x = this.tx + ((pivot.x * a) + (pivot.y * c)); + transform.position.y = this.ty + ((pivot.x * b) + (pivot.y * d)); + return transform; + }; + /** + * Inverts this matrix + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.invert = function () { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = (a1 * d1) - (b1 * c1); + this.a = d1 / n; + this.b = -b1 / n; + this.c = -c1 / n; + this.d = a1 / n; + this.tx = ((c1 * this.ty) - (d1 * tx1)) / n; + this.ty = -((a1 * this.ty) - (b1 * tx1)) / n; + return this; + }; + /** + * Resets this Matrix to an identity (default) matrix. + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.identity = function () { + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + return this; + }; + /** + * Creates a new Matrix object with the same values as this one. + * @returns A copy of this matrix. Good for chaining method calls. + */ + Matrix.prototype.clone = function () { + var matrix = new Matrix(); + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + return matrix; + }; + /** + * Changes the values of the given matrix to be the same as the ones in this matrix + * @param matrix - The matrix to copy to. + * @returns The matrix given in parameter with its values updated. + */ + Matrix.prototype.copyTo = function (matrix) { + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + return matrix; + }; + /** + * Changes the values of the matrix to be the same as the ones in given matrix + * @param {PIXI.Matrix} matrix - The matrix to copy from. + * @returns {PIXI.Matrix} this + */ + Matrix.prototype.copyFrom = function (matrix) { + this.a = matrix.a; + this.b = matrix.b; + this.c = matrix.c; + this.d = matrix.d; + this.tx = matrix.tx; + this.ty = matrix.ty; + return this; + }; + Matrix.prototype.toString = function () { + return "[@pixi/math:Matrix a=" + this.a + " b=" + this.b + " c=" + this.c + " d=" + this.d + " tx=" + this.tx + " ty=" + this.ty + "]"; + }; + Object.defineProperty(Matrix, "IDENTITY", { + /** + * A default (identity) matrix + * @readonly + */ + get: function () { + return new Matrix(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Matrix, "TEMP_MATRIX", { + /** + * A temp matrix + * @readonly + */ + get: function () { + return new Matrix(); + }, + enumerable: false, + configurable: true + }); + return Matrix; + }()); + + // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group + /* + * Transform matrix for operation n is: + * | ux | vx | + * | uy | vy | + */ + var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; + var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; + var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; + var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; + /** + * [Cayley Table]{@link https://en.wikipedia.org/wiki/Cayley_table} + * for the composition of each rotation in the dihederal group D8. + * @type {number[][]} + * @private + */ + var rotationCayley = []; + /** + * Matrices for each `GD8Symmetry` rotation. + * @type {PIXI.Matrix[]} + * @private + */ + var rotationMatrices = []; + /* + * Alias for {@code Math.sign}. + */ + var signum = Math.sign; + /* + * Initializes `rotationCayley` and `rotationMatrices`. It is called + * only once below. + */ + function init() { + for (var i = 0; i < 16; i++) { + var row = []; + rotationCayley.push(row); + for (var j = 0; j < 16; j++) { + /* Multiplies rotation matrices i and j. */ + var _ux = signum((ux[i] * ux[j]) + (vx[i] * uy[j])); + var _uy = signum((uy[i] * ux[j]) + (vy[i] * uy[j])); + var _vx = signum((ux[i] * vx[j]) + (vx[i] * vy[j])); + var _vy = signum((uy[i] * vx[j]) + (vy[i] * vy[j])); + /* Finds rotation matrix matching the product and pushes it. */ + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy + && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } + for (var i = 0; i < 16; i++) { + var mat = new Matrix(); + mat.set(ux[i], uy[i], vx[i], vy[i], 0, 0); + rotationMatrices.push(mat); + } + } + init(); + /** + * @memberof PIXI + * @typedef {number} GD8Symmetry + * @see PIXI.groupD8 + */ + /** + * Implements the dihedral group D8, which is similar to + * [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}; + * D8 is the same but with diagonals, and it is used for texture + * rotations. + * + * The directions the U- and V- axes after rotation + * of an angle of `a: GD8Constant` are the vectors `(uX(a), uY(a))` + * and `(vX(a), vY(a))`. These aren't necessarily unit vectors. + * + * **Origin:**
+ * This is the small part of gameofbombs.com portal system. It works. + * @see PIXI.groupD8.E + * @see PIXI.groupD8.SE + * @see PIXI.groupD8.S + * @see PIXI.groupD8.SW + * @see PIXI.groupD8.W + * @see PIXI.groupD8.NW + * @see PIXI.groupD8.N + * @see PIXI.groupD8.NE + * @author Ivan @ivanpopelyshev + * @namespace PIXI.groupD8 + * @memberof PIXI + */ + var groupD8 = { + /** + * | Rotation | Direction | + * |----------|-----------| + * | 0° | East | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + E: 0, + /** + * | Rotation | Direction | + * |----------|-----------| + * | 45°↻ | Southeast | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + SE: 1, + /** + * | Rotation | Direction | + * |----------|-----------| + * | 90°↻ | South | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + S: 2, + /** + * | Rotation | Direction | + * |----------|-----------| + * | 135°↻ | Southwest | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + SW: 3, + /** + * | Rotation | Direction | + * |----------|-----------| + * | 180° | West | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + W: 4, + /** + * | Rotation | Direction | + * |-------------|--------------| + * | -135°/225°↻ | Northwest | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + NW: 5, + /** + * | Rotation | Direction | + * |-------------|--------------| + * | -90°/270°↻ | North | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + N: 6, + /** + * | Rotation | Direction | + * |-------------|--------------| + * | -45°/315°↻ | Northeast | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + NE: 7, + /** + * Reflection about Y-axis. + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + MIRROR_VERTICAL: 8, + /** + * Reflection about the main diagonal. + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + MAIN_DIAGONAL: 10, + /** + * Reflection about X-axis. + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + MIRROR_HORIZONTAL: 12, + /** + * Reflection about reverse diagonal. + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + REVERSE_DIAGONAL: 14, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. + * @returns {PIXI.GD8Symmetry} The X-component of the U-axis + * after rotating the axes. + */ + uX: function (ind) { return ux[ind]; }, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. + * @returns {PIXI.GD8Symmetry} The Y-component of the U-axis + * after rotating the axes. + */ + uY: function (ind) { return uy[ind]; }, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. + * @returns {PIXI.GD8Symmetry} The X-component of the V-axis + * after rotating the axes. + */ + vX: function (ind) { return vx[ind]; }, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. + * @returns {PIXI.GD8Symmetry} The Y-component of the V-axis + * after rotating the axes. + */ + vY: function (ind) { return vy[ind]; }, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} rotation - symmetry whose opposite + * is needed. Only rotations have opposite symmetries while + * reflections don't. + * @returns {PIXI.GD8Symmetry} The opposite symmetry of `rotation` + */ + inv: function (rotation) { + if (rotation & 8) // true only if between 8 & 15 (reflections) + { + return rotation & 15; // or rotation % 16 + } + return (-rotation) & 7; // or (8 - rotation) % 8 + }, + /** + * Composes the two D8 operations. + * + * Taking `^` as reflection: + * + * | | E=0 | S=2 | W=4 | N=6 | E^=8 | S^=10 | W^=12 | N^=14 | + * |-------|-----|-----|-----|-----|------|-------|-------|-------| + * | E=0 | E | S | W | N | E^ | S^ | W^ | N^ | + * | S=2 | S | W | N | E | S^ | W^ | N^ | E^ | + * | W=4 | W | N | E | S | W^ | N^ | E^ | S^ | + * | N=6 | N | E | S | W | N^ | E^ | S^ | W^ | + * | E^=8 | E^ | N^ | W^ | S^ | E | N | W | S | + * | S^=10 | S^ | E^ | N^ | W^ | S | E | N | W | + * | W^=12 | W^ | S^ | E^ | N^ | W | S | E | N | + * | N^=14 | N^ | W^ | S^ | E^ | N | W | S | E | + * + * [This is a Cayley table]{@link https://en.wikipedia.org/wiki/Cayley_table} + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} rotationSecond - Second operation, which + * is the row in the above cayley table. + * @param {PIXI.GD8Symmetry} rotationFirst - First operation, which + * is the column in the above cayley table. + * @returns {PIXI.GD8Symmetry} Composed operation + */ + add: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][rotationFirst]); }, + /** + * Reverse of `add`. + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} rotationSecond - Second operation + * @param {PIXI.GD8Symmetry} rotationFirst - First operation + * @returns {PIXI.GD8Symmetry} Result + */ + sub: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][groupD8.inv(rotationFirst)]); }, + /** + * Adds 180 degrees to rotation, which is a commutative + * operation. + * @memberof PIXI.groupD8 + * @param {number} rotation - The number to rotate. + * @returns {number} Rotated number + */ + rotate180: function (rotation) { return rotation ^ 4; }, + /** + * Checks if the rotation angle is vertical, i.e. south + * or north. It doesn't work for reflections. + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} rotation - The number to check. + * @returns {boolean} Whether or not the direction is vertical + */ + isVertical: function (rotation) { return (rotation & 3) === 2; }, + /** + * Approximates the vector `V(dx,dy)` into one of the + * eight directions provided by `groupD8`. + * @memberof PIXI.groupD8 + * @param {number} dx - X-component of the vector + * @param {number} dy - Y-component of the vector + * @returns {PIXI.GD8Symmetry} Approximation of the vector into + * one of the eight symmetries. + */ + byDirection: function (dx, dy) { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return groupD8.S; + } + return groupD8.N; + } + else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return groupD8.E; + } + return groupD8.W; + } + else if (dy > 0) { + if (dx > 0) { + return groupD8.SE; + } + return groupD8.SW; + } + else if (dx > 0) { + return groupD8.NE; + } + return groupD8.NW; + }, + /** + * Helps sprite to compensate texture packer rotation. + * @memberof PIXI.groupD8 + * @param {PIXI.Matrix} matrix - sprite world matrix + * @param {PIXI.GD8Symmetry} rotation - The rotation factor to use. + * @param {number} tx - sprite anchoring + * @param {number} ty - sprite anchoring + */ + matrixAppendRotationInv: function (matrix, rotation, tx, ty) { + if (tx === void 0) { tx = 0; } + if (ty === void 0) { ty = 0; } + // Packer used "rotation", we use "inv(rotation)" + var mat = rotationMatrices[groupD8.inv(rotation)]; + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + }, + }; - /** - * Uploads the verticies. - * - * @param {PIXI.DisplayObject[]} children - the array of display objects to render - * @param {number} startIndex - the index to start from in the children array - * @param {number} amount - the amount of children that will have their vertices uploaded - * @param {number[]} array - The vertices to upload. - * @param {number} stride - Stride to use for iteration. - * @param {number} offset - Offset to start at. - */ - - - ParticleRenderer.prototype.uploadVertices = function uploadVertices(children, startIndex, amount, array, stride, offset) { - var w0 = 0; - var w1 = 0; - var h0 = 0; - var h1 = 0; - - for (var i = 0; i < amount; ++i) { - var sprite = children[startIndex + i]; - var texture = sprite._texture; - var sx = sprite.scale.x; - var sy = sprite.scale.y; - var trim = texture.trim; - var orig = texture.orig; - - if (trim) { - // if the sprite is trimmed and is not a tilingsprite then we need to add the - // extra space before transforming the sprite coords.. - w1 = trim.x - sprite.anchor.x * orig.width; - w0 = w1 + trim.width; - - h1 = trim.y - sprite.anchor.y * orig.height; - h0 = h1 + trim.height; - } else { - w0 = orig.width * (1 - sprite.anchor.x); - w1 = orig.width * -sprite.anchor.x; - - h0 = orig.height * (1 - sprite.anchor.y); - h1 = orig.height * -sprite.anchor.y; - } + /** + * Transform that takes care about its versions. + * @memberof PIXI + */ + var Transform = /** @class */ (function () { + function Transform() { + this.worldTransform = new Matrix(); + this.localTransform = new Matrix(); + this.position = new ObservablePoint(this.onChange, this, 0, 0); + this.scale = new ObservablePoint(this.onChange, this, 1, 1); + this.pivot = new ObservablePoint(this.onChange, this, 0, 0); + this.skew = new ObservablePoint(this.updateSkew, this, 0, 0); + this._rotation = 0; + this._cx = 1; + this._sx = 0; + this._cy = 0; + this._sy = 1; + this._localID = 0; + this._currentLocalID = 0; + this._worldID = 0; + this._parentID = 0; + } + /** Called when a value changes. */ + Transform.prototype.onChange = function () { + this._localID++; + }; + /** Called when the skew or the rotation changes. */ + Transform.prototype.updateSkew = function () { + this._cx = Math.cos(this._rotation + this.skew.y); + this._sx = Math.sin(this._rotation + this.skew.y); + this._cy = -Math.sin(this._rotation - this.skew.x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew.x); // sin, added PI/2 + this._localID++; + }; + Transform.prototype.toString = function () { + return "[@pixi/math:Transform " + + ("position=(" + this.position.x + ", " + this.position.y + ") ") + + ("rotation=" + this.rotation + " ") + + ("scale=(" + this.scale.x + ", " + this.scale.y + ") ") + + ("skew=(" + this.skew.x + ", " + this.skew.y + ") ") + + "]"; + }; + /** Updates the local transformation matrix. */ + Transform.prototype.updateLocalTransform = function () { + var lt = this.localTransform; + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c)); + lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d)); + this._currentLocalID = this._localID; + // force an update.. + this._parentID = -1; + } + }; + /** + * Updates the local and the world transformation matrices. + * @param parentTransform - The parent transform + */ + Transform.prototype.updateTransform = function (parentTransform) { + var lt = this.localTransform; + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c)); + lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d)); + this._currentLocalID = this._localID; + // force an update.. + this._parentID = -1; + } + if (this._parentID !== parentTransform._worldID) { + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + wt.a = (lt.a * pt.a) + (lt.b * pt.c); + wt.b = (lt.a * pt.b) + (lt.b * pt.d); + wt.c = (lt.c * pt.a) + (lt.d * pt.c); + wt.d = (lt.c * pt.b) + (lt.d * pt.d); + wt.tx = (lt.tx * pt.a) + (lt.ty * pt.c) + pt.tx; + wt.ty = (lt.tx * pt.b) + (lt.ty * pt.d) + pt.ty; + this._parentID = parentTransform._worldID; + // update the id of the transform.. + this._worldID++; + } + }; + /** + * Decomposes a matrix and sets the transforms properties based on it. + * @param matrix - The matrix to decompose + */ + Transform.prototype.setFromMatrix = function (matrix) { + matrix.decompose(this); + this._localID++; + }; + Object.defineProperty(Transform.prototype, "rotation", { + /** The rotation of the object in radians. */ + get: function () { + return this._rotation; + }, + set: function (value) { + if (this._rotation !== value) { + this._rotation = value; + this.updateSkew(); + } + }, + enumerable: false, + configurable: true + }); + /** A default (identity) transform. */ + Transform.IDENTITY = new Transform(); + return Transform; + }()); + + /*! + * @pixi/display - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/display is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ - array[offset] = w1 * sx; - array[offset + 1] = h1 * sy; + /** + * Sets the default value for the container property 'sortableChildren'. + * If set to true, the container will sort its children by zIndex value + * when updateTransform() is called, or manually if sortChildren() is called. + * + * This actually changes the order of elements in the array, so should be treated + * as a basic solution that is not performant compared to other solutions, + * such as @link https://github.com/pixijs/pixi-display + * + * Also be aware of that this may not work nicely with the addChildAt() function, + * as the zIndex sorting may cause the child to automatically sorted to another position. + * @static + * @constant + * @name SORTABLE_CHILDREN + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + settings.SORTABLE_CHILDREN = false; - array[offset + stride] = w0 * sx; - array[offset + stride + 1] = h1 * sy; + /** + * 'Builder' pattern for bounds rectangles. + * + * This could be called an Axis-Aligned Bounding Box. + * It is not an actual shape. It is a mutable thing; no 'EMPTY' or those kind of problems. + * @memberof PIXI + */ + var Bounds = /** @class */ (function () { + function Bounds() { + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + this.rect = null; + this.updateID = -1; + } + /** + * Checks if bounds are empty. + * @returns - True if empty. + */ + Bounds.prototype.isEmpty = function () { + return this.minX > this.maxX || this.minY > this.maxY; + }; + /** Clears the bounds and resets. */ + Bounds.prototype.clear = function () { + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + }; + /** + * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle + * It is not guaranteed that it will return tempRect + * @param rect - Temporary object will be used if AABB is not empty + * @returns - A rectangle of the bounds + */ + Bounds.prototype.getRectangle = function (rect) { + if (this.minX > this.maxX || this.minY > this.maxY) { + return Rectangle.EMPTY; + } + rect = rect || new Rectangle(0, 0, 1, 1); + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + return rect; + }; + /** + * This function should be inlined when its possible. + * @param point - The point to add. + */ + Bounds.prototype.addPoint = function (point) { + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); + }; + /** + * Adds a point, after transformed. This should be inlined when its possible. + * @param matrix + * @param point + */ + Bounds.prototype.addPointMatrix = function (matrix, point) { + var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d, tx = matrix.tx, ty = matrix.ty; + var x = (a * point.x) + (c * point.y) + tx; + var y = (b * point.x) + (d * point.y) + ty; + this.minX = Math.min(this.minX, x); + this.maxX = Math.max(this.maxX, x); + this.minY = Math.min(this.minY, y); + this.maxY = Math.max(this.maxY, y); + }; + /** + * Adds a quad, not transformed + * @param vertices - The verts to add. + */ + Bounds.prototype.addQuad = function (vertices) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + var x = vertices[0]; + var y = vertices[1]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + /** + * Adds sprite frame, transformed. + * @param transform - transform to apply + * @param x0 - left X of frame + * @param y0 - top Y of frame + * @param x1 - right X of frame + * @param y1 - bottom Y of frame + */ + Bounds.prototype.addFrame = function (transform, x0, y0, x1, y1) { + this.addFrameMatrix(transform.worldTransform, x0, y0, x1, y1); + }; + /** + * Adds sprite frame, multiplied by matrix + * @param matrix - matrix to apply + * @param x0 - left X of frame + * @param y0 - top Y of frame + * @param x1 - right X of frame + * @param y1 - bottom Y of frame + */ + Bounds.prototype.addFrameMatrix = function (matrix, x0, y0, x1, y1) { + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + var x = (a * x0) + (c * y0) + tx; + var y = (b * x0) + (d * y0) + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = (a * x1) + (c * y0) + tx; + y = (b * x1) + (d * y0) + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = (a * x0) + (c * y1) + tx; + y = (b * x0) + (d * y1) + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = (a * x1) + (c * y1) + tx; + y = (b * x1) + (d * y1) + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + /** + * Adds screen vertices from array + * @param vertexData - calculated vertices + * @param beginOffset - begin offset + * @param endOffset - end offset, excluded + */ + Bounds.prototype.addVertexData = function (vertexData, beginOffset, endOffset) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + for (var i = beginOffset; i < endOffset; i += 2) { + var x = vertexData[i]; + var y = vertexData[i + 1]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + /** + * Add an array of mesh vertices + * @param transform - mesh transform + * @param vertices - mesh coordinates in array + * @param beginOffset - begin offset + * @param endOffset - end offset, excluded + */ + Bounds.prototype.addVertices = function (transform, vertices, beginOffset, endOffset) { + this.addVerticesMatrix(transform.worldTransform, vertices, beginOffset, endOffset); + }; + /** + * Add an array of mesh vertices. + * @param matrix - mesh matrix + * @param vertices - mesh coordinates in array + * @param beginOffset - begin offset + * @param endOffset - end offset, excluded + * @param padX - x padding + * @param padY - y padding + */ + Bounds.prototype.addVerticesMatrix = function (matrix, vertices, beginOffset, endOffset, padX, padY) { + if (padX === void 0) { padX = 0; } + if (padY === void 0) { padY = padX; } + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + for (var i = beginOffset; i < endOffset; i += 2) { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = (a * rawX) + (c * rawY) + tx; + var y = (d * rawY) + (b * rawX) + ty; + minX = Math.min(minX, x - padX); + maxX = Math.max(maxX, x + padX); + minY = Math.min(minY, y - padY); + maxY = Math.max(maxY, y + padY); + } + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + /** + * Adds other {@link Bounds}. + * @param bounds - The Bounds to be added + */ + Bounds.prototype.addBounds = function (bounds) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; + }; + /** + * Adds other Bounds, masked with Bounds. + * @param bounds - The Bounds to be added. + * @param mask - TODO + */ + Bounds.prototype.addBoundsMask = function (bounds, mask) { + var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; + var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; + var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; + var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + /** + * Adds other Bounds, multiplied by matrix. Bounds shouldn't be empty. + * @param bounds - other bounds + * @param matrix - multiplicator + */ + Bounds.prototype.addBoundsMatrix = function (bounds, matrix) { + this.addFrameMatrix(matrix, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY); + }; + /** + * Adds other Bounds, masked with Rectangle. + * @param bounds - TODO + * @param area - TODO + */ + Bounds.prototype.addBoundsArea = function (bounds, area) { + var _minX = bounds.minX > area.x ? bounds.minX : area.x; + var _minY = bounds.minY > area.y ? bounds.minY : area.y; + var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : (area.x + area.width); + var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : (area.y + area.height); + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + /** + * Pads bounds object, making it grow in all directions. + * If paddingY is omitted, both paddingX and paddingY will be set to paddingX. + * @param paddingX - The horizontal padding amount. + * @param paddingY - The vertical padding amount. + */ + Bounds.prototype.pad = function (paddingX, paddingY) { + if (paddingX === void 0) { paddingX = 0; } + if (paddingY === void 0) { paddingY = paddingX; } + if (!this.isEmpty()) { + this.minX -= paddingX; + this.maxX += paddingX; + this.minY -= paddingY; + this.maxY += paddingY; + } + }; + /** + * Adds padded frame. (x0, y0) should be strictly less than (x1, y1) + * @param x0 - left X of frame + * @param y0 - top Y of frame + * @param x1 - right X of frame + * @param y1 - bottom Y of frame + * @param padX - padding X + * @param padY - padding Y + */ + Bounds.prototype.addFramePad = function (x0, y0, x1, y1, padX, padY) { + x0 -= padX; + y0 -= padY; + x1 += padX; + y1 += padY; + this.minX = this.minX < x0 ? this.minX : x0; + this.maxX = this.maxX > x1 ? this.maxX : x1; + this.minY = this.minY < y0 ? this.minY : y0; + this.maxY = this.maxY > y1 ? this.maxY : y1; + }; + return Bounds; + }()); + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$j = function(d, b) { + extendStatics$j = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$j(d, b); + }; - array[offset + stride * 2] = w0 * sx; - array[offset + stride * 2 + 1] = h0 * sy; + function __extends$j(d, b) { + extendStatics$j(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } - array[offset + stride * 3] = w1 * sx; - array[offset + stride * 3 + 1] = h0 * sy; + /** + * The base class for all objects that are rendered on the screen. + * + * This is an abstract class and can not be used on its own; rather it should be extended. + * + * ## Display objects implemented in PixiJS + * + * | Display Object | Description | + * | ------------------------------- | --------------------------------------------------------------------- | + * | {@link PIXI.Container} | Adds support for `children` to DisplayObject | + * | {@link PIXI.Graphics} | Shape-drawing display object similar to the Canvas API | + * | {@link PIXI.Sprite} | Draws textures (i.e. images) | + * | {@link PIXI.Text} | Draws text using the Canvas API internally | + * | {@link PIXI.BitmapText} | More scaleable solution for text rendering, reusing glyph textures | + * | {@link PIXI.TilingSprite} | Draws textures/images in a tiled fashion | + * | {@link PIXI.AnimatedSprite} | Draws an animation of multiple images | + * | {@link PIXI.Mesh} | Provides a lower-level API for drawing meshes with custom data | + * | {@link PIXI.NineSlicePlane} | Mesh-related | + * | {@link PIXI.SimpleMesh} | v4-compatible mesh | + * | {@link PIXI.SimplePlane} | Mesh-related | + * | {@link PIXI.SimpleRope} | Mesh-related | + * + * ## Transforms + * + * The [transform]{@link DisplayObject#transform} of a display object describes the projection from its + * local coordinate space to its parent's local coordinate space. The following properties are derived + * from the transform: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
PropertyDescription
[pivot]{@link PIXI.DisplayObject#pivot} + * Invariant under rotation, scaling, and skewing. The projection of into the parent's space of the pivot + * is equal to position, regardless of the other three transformations. In other words, It is the center of + * rotation, scaling, and skewing. + *
[position]{@link PIXI.DisplayObject#position} + * Translation. This is the position of the [pivot]{@link PIXI.DisplayObject#pivot} in the parent's local + * space. The default value of the pivot is the origin (0,0). If the top-left corner of your display object + * is (0,0) in its local space, then the position will be its top-left corner in the parent's local space. + *
[scale]{@link PIXI.DisplayObject#scale} + * Scaling. This will stretch (or compress) the display object's projection. The scale factors are along the + * local coordinate axes. In other words, the display object is scaled before rotated or skewed. The center + * of scaling is the [pivot]{@link PIXI.DisplayObject#pivot}. + *
[rotation]{@link PIXI.DisplayObject#rotation} + * Rotation. This will rotate the display object's projection by this angle (in radians). + *
[skew]{@link PIXI.DisplayObject#skew} + *

Skewing. This can be used to deform a rectangular display object into a parallelogram.

+ *

+ * In PixiJS, skew has a slightly different behaviour than the conventional meaning. It can be + * thought of the net rotation applied to the coordinate axes (separately). For example, if "skew.x" is + * ⍺ and "skew.y" is β, then the line x = 0 will be rotated by ⍺ (y = -x*cot⍺) and the line y = 0 will be + * rotated by β (y = x*tanβ). A line y = x*tanϴ (i.e. a line at angle ϴ to the x-axis in local-space) will + * be rotated by an angle between ⍺ and β. + *

+ *

+ * It can be observed that if skew is applied equally to both axes, then it will be equivalent to applying + * a rotation. Indeed, if "skew.x" = -ϴ and "skew.y" = ϴ, it will produce an equivalent of "rotation" = ϴ. + *

+ *

+ * Another quite interesting observation is that "skew.x", "skew.y", rotation are communtative operations. Indeed, + * because rotation is essentially a careful combination of the two. + *

+ *
angleRotation. This is an alias for [rotation]{@link PIXI.DisplayObject#rotation}, but in degrees.
xTranslation. This is an alias for position.x!
yTranslation. This is an alias for position.y!
width + * Implemented in [Container]{@link PIXI.Container}. Scaling. The width property calculates scale.x by dividing + * the "requested" width by the local bounding box width. It is indirectly an abstraction over scale.x, and there + * is no concept of user-defined width. + *
height + * Implemented in [Container]{@link PIXI.Container}. Scaling. The height property calculates scale.y by dividing + * the "requested" height by the local bounding box height. It is indirectly an abstraction over scale.y, and there + * is no concept of user-defined height. + *
+ * + * ## Bounds + * + * The bounds of a display object is defined by the minimum axis-aligned rectangle in world space that can fit + * around it. The abstract `calculateBounds` method is responsible for providing it (and it should use the + * `worldTransform` to calculate in world space). + * + * There are a few additional types of bounding boxes: + * + * | Bounds | Description | + * | --------------------- | ---------------------------------------------------------------------------------------- | + * | World Bounds | This is synonymous is the regular bounds described above. See `getBounds()`. | + * | Local Bounds | This the axis-aligned bounding box in the parent's local space. See `getLocalBounds()`. | + * | Render Bounds | The bounds, but including extra rendering effects like filter padding. | + * | Projected Bounds | The bounds of the projected display object onto the screen. Usually equals world bounds. | + * | Relative Bounds | The bounds of a display object when projected onto a ancestor's (or parent's) space. | + * | Natural Bounds | The bounds of an object in its own local space (not parent's space, like in local bounds)| + * | Content Bounds | The natural bounds when excluding all children of a `Container`. | + * + * ### calculateBounds + * + * [Container]{@link Container} already implements `calculateBounds` in a manner that includes children. + * + * But for a non-Container display object, the `calculateBounds` method must be overridden in order for `getBounds` and + * `getLocalBounds` to work. This method must write the bounds into `this._bounds`. + * + * Generally, the following technique works for most simple cases: take the list of points + * forming the "hull" of the object (i.e. outline of the object's shape), and then add them + * using {@link PIXI.Bounds#addPointMatrix}. + * + * ```js + * calculateBounds(): void + * { + * const points = [...]; + * + * for (let i = 0, j = points.length; i < j; i++) + * { + * this._bounds.addPointMatrix(this.worldTransform, points[i]); + * } + * } + * ``` + * + * You can optimize this for a large number of points by using {@link PIXI.Bounds#addVerticesMatrix} to pass them + * in one array together. + * + * ## Alpha + * + * This alpha sets a display object's **relative opacity** w.r.t its parent. For example, if the alpha of a display + * object is 0.5 and its parent's alpha is 0.5, then it will be rendered with 25% opacity (assuming alpha is not + * applied on any ancestor further up the chain). + * + * The alpha with which the display object will be rendered is called the [worldAlpha]{@link PIXI.DisplayObject#worldAlpha}. + * + * ## Renderable vs Visible + * + * The `renderable` and `visible` properties can be used to prevent a display object from being rendered to the + * screen. However, there is a subtle difference between the two. When using `renderable`, the transforms of the display + * object (and its children subtree) will continue to be calculated. When using `visible`, the transforms will not + * be calculated. + * + * It is recommended that applications use the `renderable` property for culling. See + * [@pixi-essentials/cull]{@link https://www.npmjs.com/package/@pixi-essentials/cull} or + * [pixi-cull]{@link https://www.npmjs.com/package/pixi-cull} for more details. + * + * Otherwise, to prevent an object from rendering in the general-purpose sense - `visible` is the property to use. This + * one is also better in terms of performance. + * @memberof PIXI + */ + var DisplayObject = /** @class */ (function (_super) { + __extends$j(DisplayObject, _super); + function DisplayObject() { + var _this = _super.call(this) || this; + _this.tempDisplayObjectParent = null; + // TODO: need to create Transform from factory + _this.transform = new Transform(); + _this.alpha = 1; + _this.visible = true; + _this.renderable = true; + _this.cullable = false; + _this.cullArea = null; + _this.parent = null; + _this.worldAlpha = 1; + _this._lastSortedIndex = 0; + _this._zIndex = 0; + _this.filterArea = null; + _this.filters = null; + _this._enabledFilters = null; + _this._bounds = new Bounds(); + _this._localBounds = null; + _this._boundsID = 0; + _this._boundsRect = null; + _this._localBoundsRect = null; + _this._mask = null; + _this._maskRefCount = 0; + _this._destroyed = false; + _this.isSprite = false; + _this.isMask = false; + return _this; + } + /** + * Mixes all enumerable properties and methods from a source object to DisplayObject. + * @param source - The source of properties and methods to mix in. + */ + DisplayObject.mixin = function (source) { + // in ES8/ES2017, this would be really easy: + // Object.defineProperties(DisplayObject.prototype, Object.getOwnPropertyDescriptors(source)); + // get all the enumerable property keys + var keys = Object.keys(source); + // loop through properties + for (var i = 0; i < keys.length; ++i) { + var propertyName = keys[i]; + // Set the property using the property descriptor - this works for accessors and normal value properties + Object.defineProperty(DisplayObject.prototype, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); + } + }; + Object.defineProperty(DisplayObject.prototype, "destroyed", { + /** + * Fired when this DisplayObject is added to a Container. + * @instance + * @event added + * @param {PIXI.Container} container - The container added to. + */ + /** + * Fired when this DisplayObject is removed from a Container. + * @instance + * @event removed + * @param {PIXI.Container} container - The container removed from. + */ + /** + * Fired when this DisplayObject is destroyed. This event is emitted once + * destroy is finished. + * @instance + * @event destroyed + */ + /** Readonly flag for destroyed display objects. */ + get: function () { + return this._destroyed; + }, + enumerable: false, + configurable: true + }); + /** Recursively updates transform of all objects from the root to this one internal function for toLocal() */ + DisplayObject.prototype._recursivePostUpdateTransform = function () { + if (this.parent) { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); + } + else { + this.transform.updateTransform(this._tempDisplayObjectParent.transform); + } + }; + /** Updates the object transform for rendering. TODO - Optimization pass! */ + DisplayObject.prototype.updateTransform = function () { + this._boundsID++; + this.transform.updateTransform(this.parent.transform); + // multiply the alphas.. + this.worldAlpha = this.alpha * this.parent.worldAlpha; + }; + /** + * Calculates and returns the (world) bounds of the display object as a [Rectangle]{@link PIXI.Rectangle}. + * + * This method is expensive on containers with a large subtree (like the stage). This is because the bounds + * of a container depend on its children's bounds, which recursively causes all bounds in the subtree to + * be recalculated. The upside, however, is that calling `getBounds` once on a container will indeed update + * the bounds of all children (the whole subtree, in fact). This side effect should be exploited by using + * `displayObject._bounds.getRectangle()` when traversing through all the bounds in a scene graph. Otherwise, + * calling `getBounds` on each object in a subtree will cause the total cost to increase quadratically as + * its height increases. + * + * The transforms of all objects in a container's **subtree** and of all **ancestors** are updated. + * The world bounds of all display objects in a container's **subtree** will also be recalculated. + * + * The `_bounds` object stores the last calculation of the bounds. You can use to entirely skip bounds + * calculation if needed. + * + * ```js + * const lastCalculatedBounds = displayObject._bounds.getRectangle(optionalRect); + * ``` + * + * Do know that usage of `getLocalBounds` can corrupt the `_bounds` of children (the whole subtree, actually). This + * is a known issue that has not been solved. See [getLocalBounds]{@link PIXI.DisplayObject#getLocalBounds} for more + * details. + * + * `getBounds` should be called with `skipUpdate` equal to `true` in a render() call. This is because the transforms + * are guaranteed to be update-to-date. In fact, recalculating inside a render() call may cause corruption in certain + * cases. + * @param skipUpdate - Setting to `true` will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost. + * @param rect - Optional rectangle to store the result of the bounds calculation. + * @returns - The minimum axis-aligned rectangle in world space that fits around this object. + */ + DisplayObject.prototype.getBounds = function (skipUpdate, rect) { + if (!skipUpdate) { + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } + else { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + if (this._bounds.updateID !== this._boundsID) { + this.calculateBounds(); + this._bounds.updateID = this._boundsID; + } + if (!rect) { + if (!this._boundsRect) { + this._boundsRect = new Rectangle(); + } + rect = this._boundsRect; + } + return this._bounds.getRectangle(rect); + }; + /** + * Retrieves the local bounds of the displayObject as a rectangle object. + * @param rect - Optional rectangle to store the result of the bounds calculation. + * @returns - The rectangular bounding area. + */ + DisplayObject.prototype.getLocalBounds = function (rect) { + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new Rectangle(); + } + rect = this._localBoundsRect; + } + if (!this._localBounds) { + this._localBounds = new Bounds(); + } + var transformRef = this.transform; + var parentRef = this.parent; + this.parent = null; + this.transform = this._tempDisplayObjectParent.transform; + var worldBounds = this._bounds; + var worldBoundsID = this._boundsID; + this._bounds = this._localBounds; + var bounds = this.getBounds(false, rect); + this.parent = parentRef; + this.transform = transformRef; + this._bounds = worldBounds; + this._bounds.updateID += this._boundsID - worldBoundsID; // reflect side-effects + return bounds; + }; + /** + * Calculates the global position of the display object. + * @param position - The world origin to calculate from. + * @param point - A Point object in which to store the value, optional + * (otherwise will create a new Point). + * @param skipUpdate - Should we skip the update transform. + * @returns - A point object representing the position of this object. + */ + DisplayObject.prototype.toGlobal = function (position, point, skipUpdate) { + if (skipUpdate === void 0) { skipUpdate = false; } + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } + else { + this.displayObjectUpdateTransform(); + } + } + // don't need to update the lot + return this.worldTransform.apply(position, point); + }; + /** + * Calculates the local position of the display object relative to another point. + * @param position - The world origin to calculate from. + * @param from - The DisplayObject to calculate the global position from. + * @param point - A Point object in which to store the value, optional + * (otherwise will create a new Point). + * @param skipUpdate - Should we skip the update transform + * @returns - A point object representing the position of this object + */ + DisplayObject.prototype.toLocal = function (position, from, point, skipUpdate) { + if (from) { + position = from.toGlobal(position, point, skipUpdate); + } + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } + else { + this.displayObjectUpdateTransform(); + } + } + // simply apply the matrix.. + return this.worldTransform.applyInverse(position, point); + }; + /** + * Set the parent Container of this DisplayObject. + * @param container - The Container to add this DisplayObject to. + * @returns - The Container that this DisplayObject was added to. + */ + DisplayObject.prototype.setParent = function (container) { + if (!container || !container.addChild) { + throw new Error('setParent: Argument must be a Container'); + } + container.addChild(this); + return container; + }; + /** + * Convenience function to set the position, scale, skew and pivot at once. + * @param x - The X position + * @param y - The Y position + * @param scaleX - The X scale value + * @param scaleY - The Y scale value + * @param rotation - The rotation + * @param skewX - The X skew value + * @param skewY - The Y skew value + * @param pivotX - The X pivot value + * @param pivotY - The Y pivot value + * @returns - The DisplayObject instance + */ + DisplayObject.prototype.setTransform = function (x, y, scaleX, scaleY, rotation, skewX, skewY, pivotX, pivotY) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (scaleX === void 0) { scaleX = 1; } + if (scaleY === void 0) { scaleY = 1; } + if (rotation === void 0) { rotation = 0; } + if (skewX === void 0) { skewX = 0; } + if (skewY === void 0) { skewY = 0; } + if (pivotX === void 0) { pivotX = 0; } + if (pivotY === void 0) { pivotY = 0; } + this.position.x = x; + this.position.y = y; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation; + this.skew.x = skewX; + this.skew.y = skewY; + this.pivot.x = pivotX; + this.pivot.y = pivotY; + return this; + }; + /** + * Base destroy method for generic display objects. This will automatically + * remove the display object from its parent Container as well as remove + * all current event listeners and internal references. Do not use a DisplayObject + * after calling `destroy()`. + * @param _options + */ + DisplayObject.prototype.destroy = function (_options) { + if (this.parent) { + this.parent.removeChild(this); + } + this._destroyed = true; + this.transform = null; + this.parent = null; + this._bounds = null; + this.mask = null; + this.cullArea = null; + this.filters = null; + this.filterArea = null; + this.hitArea = null; + this.interactive = false; + this.interactiveChildren = false; + this.emit('destroyed'); + this.removeAllListeners(); + }; + Object.defineProperty(DisplayObject.prototype, "_tempDisplayObjectParent", { + /** + * @protected + * @member {PIXI.Container} + */ + get: function () { + if (this.tempDisplayObjectParent === null) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + this.tempDisplayObjectParent = new TemporaryDisplayObject(); + } + return this.tempDisplayObjectParent; + }, + enumerable: false, + configurable: true + }); + /** + * Used in Renderer, cacheAsBitmap and other places where you call an `updateTransform` on root + * + * ``` + * const cacheParent = elem.enableTempParent(); + * elem.updateTransform(); + * elem.disableTempParent(cacheParent); + * ``` + * @returns - current parent + */ + DisplayObject.prototype.enableTempParent = function () { + var myParent = this.parent; + this.parent = this._tempDisplayObjectParent; + return myParent; + }; + /** + * Pair method for `enableTempParent` + * @param cacheParent - Actual parent of element + */ + DisplayObject.prototype.disableTempParent = function (cacheParent) { + this.parent = cacheParent; + }; + Object.defineProperty(DisplayObject.prototype, "x", { + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * An alias to position.x + */ + get: function () { + return this.position.x; + }, + set: function (value) { + this.transform.position.x = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "y", { + /** + * The position of the displayObject on the y axis relative to the local coordinates of the parent. + * An alias to position.y + */ + get: function () { + return this.position.y; + }, + set: function (value) { + this.transform.position.y = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "worldTransform", { + /** + * Current transform of the object based on world (parent) factors. + * @readonly + */ + get: function () { + return this.transform.worldTransform; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "localTransform", { + /** + * Current transform of the object based on local factors: position, scale, other stuff. + * @readonly + */ + get: function () { + return this.transform.localTransform; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "position", { + /** + * The coordinate of the object relative to the local coordinates of the parent. + * @since 4.0.0 + */ + get: function () { + return this.transform.position; + }, + set: function (value) { + this.transform.position.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "scale", { + /** + * The scale factors of this object along the local coordinate axes. + * + * The default scale is (1, 1). + * @since 4.0.0 + */ + get: function () { + return this.transform.scale; + }, + set: function (value) { + this.transform.scale.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "pivot", { + /** + * The center of rotation, scaling, and skewing for this display object in its local space. The `position` + * is the projection of `pivot` in the parent's local space. + * + * By default, the pivot is the origin (0, 0). + * @since 4.0.0 + */ + get: function () { + return this.transform.pivot; + }, + set: function (value) { + this.transform.pivot.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "skew", { + /** + * The skew factor for the object in radians. + * @since 4.0.0 + */ + get: function () { + return this.transform.skew; + }, + set: function (value) { + this.transform.skew.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "rotation", { + /** + * The rotation of the object in radians. + * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees. + */ + get: function () { + return this.transform.rotation; + }, + set: function (value) { + this.transform.rotation = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "angle", { + /** + * The angle of the object in degrees. + * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees. + */ + get: function () { + return this.transform.rotation * RAD_TO_DEG; + }, + set: function (value) { + this.transform.rotation = value * DEG_TO_RAD; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "zIndex", { + /** + * The zIndex of the displayObject. + * + * If a container has the sortableChildren property set to true, children will be automatically + * sorted by zIndex value; a higher value will mean it will be moved towards the end of the array, + * and thus rendered on top of other display objects within the same container. + * @see PIXI.Container#sortableChildren + */ + get: function () { + return this._zIndex; + }, + set: function (value) { + this._zIndex = value; + if (this.parent) { + this.parent.sortDirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "worldVisible", { + /** + * Indicates if the object is globally visible. + * @readonly + */ + get: function () { + var item = this; + do { + if (!item.visible) { + return false; + } + item = item.parent; + } while (item); + return true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "mask", { + /** + * Sets a mask for the displayObject. A mask is an object that limits the visibility of an + * object to the shape of the mask applied to it. In PixiJS a regular mask must be a + * {@link PIXI.Graphics} or a {@link PIXI.Sprite} object. This allows for much faster masking in canvas as it + * utilities shape clipping. Furthermore, a mask of an object must be in the subtree of its parent. + * Otherwise, `getLocalBounds` may calculate incorrect bounds, which makes the container's width and height wrong. + * To remove a mask, set this property to `null`. + * + * For sprite mask both alpha and red channel are used. Black mask is the same as transparent mask. + * @example + * const graphics = new PIXI.Graphics(); + * graphics.beginFill(0xFF3300); + * graphics.drawRect(50, 250, 100, 100); + * graphics.endFill(); + * + * const sprite = new PIXI.Sprite(texture); + * sprite.mask = graphics; + * @todo At the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. + */ + get: function () { + return this._mask; + }, + set: function (value) { + if (this._mask === value) { + return; + } + if (this._mask) { + var maskObject = (this._mask.isMaskData + ? this._mask.maskObject : this._mask); + if (maskObject) { + maskObject._maskRefCount--; + if (maskObject._maskRefCount === 0) { + maskObject.renderable = true; + maskObject.isMask = false; + } + } + } + this._mask = value; + if (this._mask) { + var maskObject = (this._mask.isMaskData + ? this._mask.maskObject : this._mask); + if (maskObject) { + if (maskObject._maskRefCount === 0) { + maskObject.renderable = false; + maskObject.isMask = true; + } + maskObject._maskRefCount++; + } + } + }, + enumerable: false, + configurable: true + }); + return DisplayObject; + }(eventemitter3)); + /** + * @private + */ + var TemporaryDisplayObject = /** @class */ (function (_super) { + __extends$j(TemporaryDisplayObject, _super); + function TemporaryDisplayObject() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.sortDirty = null; + return _this; + } + return TemporaryDisplayObject; + }(DisplayObject)); + /** + * DisplayObject default updateTransform, does not update children of container. + * Will crash if there's no parent element. + * @memberof PIXI.DisplayObject# + * @method displayObjectUpdateTransform + */ + DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; - offset += stride * 4; - } - }; + function sortChildren(a, b) { + if (a.zIndex === b.zIndex) { + return a._lastSortedIndex - b._lastSortedIndex; + } + return a.zIndex - b.zIndex; + } + /** + * Container is a general-purpose display object that holds children. It also adds built-in support for advanced + * rendering features like masking and filtering. + * + * It is the base class of all display objects that act as a container for other objects, including Graphics + * and Sprite. + * + * ```js + * import { BlurFilter } from '@pixi/filter-blur'; + * import { Container } from '@pixi/display'; + * import { Graphics } from '@pixi/graphics'; + * import { Sprite } from '@pixi/sprite'; + * + * let container = new Container(); + * let sprite = Sprite.from("https://s3-us-west-2.amazonaws.com/s.cdpn.io/693612/IaUrttj.png"); + * + * sprite.width = 512; + * sprite.height = 512; + * + * // Adds a sprite as a child to this container. As a result, the sprite will be rendered whenever the container + * // is rendered. + * container.addChild(sprite); + * + * // Blurs whatever is rendered by the container + * container.filters = [new BlurFilter()]; + * + * // Only the contents within a circle at the center should be rendered onto the screen. + * container.mask = new Graphics() + * .beginFill(0xffffff) + * .drawCircle(sprite.width / 2, sprite.height / 2, Math.min(sprite.width, sprite.height) / 2) + * .endFill(); + * ``` + * @memberof PIXI + */ + var Container = /** @class */ (function (_super) { + __extends$j(Container, _super); + function Container() { + var _this = _super.call(this) || this; + _this.children = []; + _this.sortableChildren = settings.SORTABLE_CHILDREN; + _this.sortDirty = false; + return _this; + /** + * Fired when a DisplayObject is added to this Container. + * @event PIXI.Container#childAdded + * @param {PIXI.DisplayObject} child - The child added to the Container. + * @param {PIXI.Container} container - The container that added the child. + * @param {number} index - The children's index of the added child. + */ + /** + * Fired when a DisplayObject is removed from this Container. + * @event PIXI.DisplayObject#childRemoved + * @param {PIXI.DisplayObject} child - The child removed from the Container. + * @param {PIXI.Container} container - The container that removed the child. + * @param {number} index - The former children's index of the removed child + */ + } + /** + * Overridable method that can be used by Container subclasses whenever the children array is modified. + * @param _length + */ + Container.prototype.onChildrenChange = function (_length) { + /* empty */ + }; + /** + * Adds one or more children to the container. + * + * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` + * @param {...PIXI.DisplayObject} children - The DisplayObject(s) to add to the container + * @returns {PIXI.DisplayObject} - The first child that was added. + */ + Container.prototype.addChild = function () { + var arguments$1 = arguments; - /** - * - * @param {PIXI.DisplayObject[]} children - the array of display objects to render - * @param {number} startIndex - the index to start from in the children array - * @param {number} amount - the amount of children that will have their positions uploaded - * @param {number[]} array - The vertices to upload. - * @param {number} stride - Stride to use for iteration. - * @param {number} offset - Offset to start at. - */ + var children = []; + for (var _i = 0; _i < arguments.length; _i++) { + children[_i] = arguments$1[_i]; + } + // if there is only one argument we can bypass looping through the them + if (children.length > 1) { + // loop through the array and add all children + for (var i = 0; i < children.length; i++) { + // eslint-disable-next-line prefer-rest-params + this.addChild(children[i]); + } + } + else { + var child = children[0]; + // if the child has a parent then lets remove it as PixiJS objects can only exist in one place + if (child.parent) { + child.parent.removeChild(child); + } + child.parent = this; + this.sortDirty = true; + // ensure child transform will be recalculated + child.transform._parentID = -1; + this.children.push(child); + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length - 1); + this.emit('childAdded', child, this, this.children.length - 1); + child.emit('added', this); + } + return children[0]; + }; + /** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * @param {PIXI.DisplayObject} child - The child to add + * @param {number} index - The index to place the child in + * @returns {PIXI.DisplayObject} The child that was added. + */ + Container.prototype.addChildAt = function (child, index) { + if (index < 0 || index > this.children.length) { + throw new Error(child + "addChildAt: The index " + index + " supplied is out of bounds " + this.children.length); + } + if (child.parent) { + child.parent.removeChild(child); + } + child.parent = this; + this.sortDirty = true; + // ensure child transform will be recalculated + child.transform._parentID = -1; + this.children.splice(index, 0, child); + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('added', this); + this.emit('childAdded', child, this, index); + return child; + }; + /** + * Swaps the position of 2 Display Objects within this container. + * @param child - First display object to swap + * @param child2 - Second display object to swap + */ + Container.prototype.swapChildren = function (child, child2) { + if (child === child2) { + return; + } + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); + }; + /** + * Returns the index position of a child DisplayObject instance + * @param child - The DisplayObject instance to identify + * @returns - The index position of the child display object to identify + */ + Container.prototype.getChildIndex = function (child) { + var index = this.children.indexOf(child); + if (index === -1) { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + return index; + }; + /** + * Changes the position of an existing child in the display object container + * @param child - The child DisplayObject instance for which you want to change the index number + * @param index - The resulting index number for the child display object + */ + Container.prototype.setChildIndex = function (child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error("The index " + index + " supplied is out of bounds " + this.children.length); + } + var currentIndex = this.getChildIndex(child); + removeItems(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); // add at new position + this.onChildrenChange(index); + }; + /** + * Returns the child at the specified index + * @param index - The index to get the child at + * @returns - The child at the given index, if any. + */ + Container.prototype.getChildAt = function (index) { + if (index < 0 || index >= this.children.length) { + throw new Error("getChildAt: Index (" + index + ") does not exist."); + } + return this.children[index]; + }; + /** + * Removes one or more children from the container. + * @param {...PIXI.DisplayObject} children - The DisplayObject(s) to remove + * @returns {PIXI.DisplayObject} The first child that was removed. + */ + Container.prototype.removeChild = function () { + var arguments$1 = arguments; + var children = []; + for (var _i = 0; _i < arguments.length; _i++) { + children[_i] = arguments$1[_i]; + } + // if there is only one argument we can bypass looping through the them + if (children.length > 1) { + // loop through the arguments property and remove all children + for (var i = 0; i < children.length; i++) { + this.removeChild(children[i]); + } + } + else { + var child = children[0]; + var index = this.children.indexOf(child); + if (index === -1) + { return null; } + child.parent = null; + // ensure child transform will be recalculated + child.transform._parentID = -1; + removeItems(this.children, index, 1); + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + this.emit('childRemoved', child, this, index); + } + return children[0]; + }; + /** + * Removes a child from the specified index position. + * @param index - The index to get the child from + * @returns The child that was removed. + */ + Container.prototype.removeChildAt = function (index) { + var child = this.getChildAt(index); + // ensure child transform will be recalculated.. + child.parent = null; + child.transform._parentID = -1; + removeItems(this.children, index, 1); + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + this.emit('childRemoved', child, this, index); + return child; + }; + /** + * Removes all children from this container that are within the begin and end indexes. + * @param beginIndex - The beginning position. + * @param endIndex - The ending position. Default value is size of the container. + * @returns - List of removed children + */ + Container.prototype.removeChildren = function (beginIndex, endIndex) { + if (beginIndex === void 0) { beginIndex = 0; } + if (endIndex === void 0) { endIndex = this.children.length; } + var begin = beginIndex; + var end = endIndex; + var range = end - begin; + var removed; + if (range > 0 && range <= end) { + removed = this.children.splice(begin, range); + for (var i = 0; i < removed.length; ++i) { + removed[i].parent = null; + if (removed[i].transform) { + removed[i].transform._parentID = -1; + } + } + this._boundsID++; + this.onChildrenChange(beginIndex); + for (var i = 0; i < removed.length; ++i) { + removed[i].emit('removed', this); + this.emit('childRemoved', removed[i], this, i); + } + return removed; + } + else if (range === 0 && this.children.length === 0) { + return []; + } + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); + }; + /** Sorts children by zIndex. Previous order is maintained for 2 children with the same zIndex. */ + Container.prototype.sortChildren = function () { + var sortRequired = false; + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + child._lastSortedIndex = i; + if (!sortRequired && child.zIndex !== 0) { + sortRequired = true; + } + } + if (sortRequired && this.children.length > 1) { + this.children.sort(sortChildren); + } + this.sortDirty = false; + }; + /** Updates the transform on all children of this container for rendering. */ + Container.prototype.updateTransform = function () { + if (this.sortableChildren && this.sortDirty) { + this.sortChildren(); + } + this._boundsID++; + this.transform.updateTransform(this.parent.transform); + // TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + if (child.visible) { + child.updateTransform(); + } + } + }; + /** + * Recalculates the bounds of the container. + * + * This implementation will automatically fit the children's bounds into the calculation. Each child's bounds + * is limited to its mask's bounds or filterArea, if any is applied. + */ + Container.prototype.calculateBounds = function () { + this._bounds.clear(); + this._calculateBounds(); + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + if (!child.visible || !child.renderable) { + continue; + } + child.calculateBounds(); + // TODO: filter+mask, need to mask both somehow + if (child._mask) { + var maskObject = (child._mask.isMaskData + ? child._mask.maskObject : child._mask); + if (maskObject) { + maskObject.calculateBounds(); + this._bounds.addBoundsMask(child._bounds, maskObject._bounds); + } + else { + this._bounds.addBounds(child._bounds); + } + } + else if (child.filterArea) { + this._bounds.addBoundsArea(child._bounds, child.filterArea); + } + else { + this._bounds.addBounds(child._bounds); + } + } + this._bounds.updateID = this._boundsID; + }; + /** + * Retrieves the local bounds of the displayObject as a rectangle object. + * + * Calling `getLocalBounds` may invalidate the `_bounds` of the whole subtree below. If using it inside a render() + * call, it is advised to call `getBounds()` immediately after to recalculate the world bounds of the subtree. + * @param rect - Optional rectangle to store the result of the bounds calculation. + * @param skipChildrenUpdate - Setting to `true` will stop re-calculation of children transforms, + * it was default behaviour of pixi 4.0-5.2 and caused many problems to users. + * @returns - The rectangular bounding area. + */ + Container.prototype.getLocalBounds = function (rect, skipChildrenUpdate) { + if (skipChildrenUpdate === void 0) { skipChildrenUpdate = false; } + var result = _super.prototype.getLocalBounds.call(this, rect); + if (!skipChildrenUpdate) { + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + if (child.visible) { + child.updateTransform(); + } + } + } + return result; + }; + /** + * Recalculates the content bounds of this object. This should be overriden to + * calculate the bounds of this specific object (not including children). + * @protected + */ + Container.prototype._calculateBounds = function () { + // FILL IN// + }; + /** + * Renders this object and its children with culling. + * @protected + * @param {PIXI.Renderer} renderer - The renderer + */ + Container.prototype._renderWithCulling = function (renderer) { + var sourceFrame = renderer.renderTexture.sourceFrame; + // If the source frame is empty, stop rendering. + if (!(sourceFrame.width > 0 && sourceFrame.height > 0)) { + return; + } + // Render the content of the container only if its bounds intersect with the source frame. + // All filters are on the stack at this point, and the filter source frame is bound: + // therefore, even if the bounds to non intersect the filter frame, the filter + // is still applied and any filter padding that is in the frame is rendered correctly. + var bounds; + var transform; + // If cullArea is set, we use this rectangle instead of the bounds of the object. The cullArea + // rectangle must completely contain the container and its children including filter padding. + if (this.cullArea) { + bounds = this.cullArea; + transform = this.worldTransform; + } + // If the container doesn't override _render, we can skip the bounds calculation and intersection test. + else if (this._render !== Container.prototype._render) { + bounds = this.getBounds(true); + } + // Render the container if the source frame intersects the bounds. + if (bounds && sourceFrame.intersects(bounds, transform)) { + this._render(renderer); + } + // If the bounds are defined by cullArea and do not intersect with the source frame, stop rendering. + else if (this.cullArea) { + return; + } + // Unless cullArea is set, we cannot skip the children if the bounds of the container do not intersect + // the source frame, because the children might have filters with nonzero padding, which may intersect + // with the source frame while the bounds do not: filter padding is not included in the bounds. + // If cullArea is not set, render the children with culling temporarily enabled so that they are not rendered + // if they are out of frame; otherwise, render the children normally. + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + var childCullable = child.cullable; + child.cullable = childCullable || !this.cullArea; + child.render(renderer); + child.cullable = childCullable; + } + }; + /** + * Renders the object using the WebGL renderer. + * + * The [_render]{@link PIXI.Container#_render} method is be overriden for rendering the contents of the + * container itself. This `render` method will invoke it, and also invoke the `render` methods of all + * children afterward. + * + * If `renderable` or `visible` is false or if `worldAlpha` is not positive or if `cullable` is true and + * the bounds of this object are out of frame, this implementation will entirely skip rendering. + * See {@link PIXI.DisplayObject} for choosing between `renderable` or `visible`. Generally, + * setting alpha to zero is not recommended for purely skipping rendering. + * + * When your scene becomes large (especially when it is larger than can be viewed in a single screen), it is + * advised to employ **culling** to automatically skip rendering objects outside of the current screen. + * See [cullable]{@link PIXI.DisplayObject#cullable} and [cullArea]{@link PIXI.DisplayObject#cullArea}. + * Other culling methods might be better suited for a large number static objects; see + * [@pixi-essentials/cull]{@link https://www.npmjs.com/package/@pixi-essentials/cull} and + * [pixi-cull]{@link https://www.npmjs.com/package/pixi-cull}. + * + * The [renderAdvanced]{@link PIXI.Container#renderAdvanced} method is internally used when when masking or + * filtering is applied on a container. This does, however, break batching and can affect performance when + * masking and filtering is applied extensively throughout the scene graph. + * @param renderer - The renderer + */ + Container.prototype.render = function (renderer) { + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + // do a quick check to see if this element has a mask or a filter. + if (this._mask || (this.filters && this.filters.length)) { + this.renderAdvanced(renderer); + } + else if (this.cullable) { + this._renderWithCulling(renderer); + } + else { + this._render(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].render(renderer); + } + } + }; + /** + * Render the object using the WebGL renderer and advanced features. + * @param renderer - The renderer + */ + Container.prototype.renderAdvanced = function (renderer) { + var filters = this.filters; + var mask = this._mask; + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } + this._enabledFilters.length = 0; + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); + } + } + } + var flush = (filters && this._enabledFilters && this._enabledFilters.length) + || (mask && (!mask.isMaskData + || (mask.enabled && (mask.autoDetect || mask.type !== exports.MASK_TYPES.NONE)))); + if (flush) { + renderer.batch.flush(); + } + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filter.push(this, this._enabledFilters); + } + if (mask) { + renderer.mask.push(this, this._mask); + } + if (this.cullable) { + this._renderWithCulling(renderer); + } + else { + this._render(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].render(renderer); + } + } + if (flush) { + renderer.batch.flush(); + } + if (mask) { + renderer.mask.pop(this); + } + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filter.pop(); + } + }; + /** + * To be overridden by the subclasses. + * @param _renderer - The renderer + */ + Container.prototype._render = function (_renderer) { + // this is where content itself gets rendered... + }; + /** + * Removes all internal references and listeners as well as removes children from the display list. + * Do not use a Container after calling `destroy`. + * @param options - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + Container.prototype.destroy = function (options) { + _super.prototype.destroy.call(this); + this.sortDirty = false; + var destroyChildren = typeof options === 'boolean' ? options : options && options.children; + var oldChildren = this.removeChildren(0, this.children.length); + if (destroyChildren) { + for (var i = 0; i < oldChildren.length; ++i) { + oldChildren[i].destroy(options); + } + } + }; + Object.defineProperty(Container.prototype, "width", { + /** The width of the Container, setting this will actually modify the scale to achieve the value set. */ + get: function () { + return this.scale.x * this.getLocalBounds().width; + }, + set: function (value) { + var width = this.getLocalBounds().width; + if (width !== 0) { + this.scale.x = value / width; + } + else { + this.scale.x = 1; + } + this._width = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Container.prototype, "height", { + /** The height of the Container, setting this will actually modify the scale to achieve the value set. */ + get: function () { + return this.scale.y * this.getLocalBounds().height; + }, + set: function (value) { + var height = this.getLocalBounds().height; + if (height !== 0) { + this.scale.y = value / height; + } + else { + this.scale.y = 1; + } + this._height = value; + }, + enumerable: false, + configurable: true + }); + return Container; + }(DisplayObject)); + /** + * Container default updateTransform, does update children of container. + * Will crash if there's no parent element. + * @memberof PIXI.Container# + * @method containerUpdateTransform + */ + Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; - ParticleRenderer.prototype.uploadPosition = function uploadPosition(children, startIndex, amount, array, stride, offset) { - for (var i = 0; i < amount; i++) { - var spritePosition = children[startIndex + i].position; + /*! + * @pixi/extensions - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/extensions is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + + var __assign$1 = function() { + __assign$1 = Object.assign || function __assign(t) { + var arguments$1 = arguments; + + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments$1[i]; + for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p)) { t[p] = s[p]; } } + } + return t; + }; + return __assign$1.apply(this, arguments); + }; - array[offset] = spritePosition.x; - array[offset + 1] = spritePosition.y; + /** + * Collection of valid extension types. + * @memberof PIXI + * @property {string} Application - Application plugins + * @property {string} RendererPlugin - Plugins for Renderer + * @property {string} CanvasRendererPlugin - Plugins for CanvasRenderer + * @property {string} Loader - Plugins to use with Loader + * @property {string} LoadParser - Parsers for Assets loader. + * @property {string} ResolveParser - Parsers for Assets resolvers. + * @property {string} CacheParser - Parsers for Assets cache. + */ + exports.ExtensionType = void 0; + (function (ExtensionType) { + ExtensionType["Application"] = "application"; + ExtensionType["RendererPlugin"] = "renderer-webgl-plugin"; + ExtensionType["CanvasRendererPlugin"] = "renderer-canvas-plugin"; + ExtensionType["Loader"] = "loader"; + ExtensionType["LoadParser"] = "load-parser"; + ExtensionType["ResolveParser"] = "resolve-parser"; + ExtensionType["CacheParser"] = "cache-parser"; + ExtensionType["DetectionParser"] = "detection-parser"; + })(exports.ExtensionType || (exports.ExtensionType = {})); + /** + * Convert input into extension format data. + * @ignore + */ + var normalizeExtension = function (ext) { + // Class/Object submission, use extension object + if (typeof ext === 'function' || (typeof ext === 'object' && ext.extension)) { + if (!ext.extension) { + throw new Error('Extension class must have an extension object'); + } + var metadata = (typeof ext.extension !== 'object') + ? { type: ext.extension } + : ext.extension; + ext = __assign$1(__assign$1({}, metadata), { ref: ext }); + } + if (typeof ext === 'object') { + ext = __assign$1({}, ext); + } + else { + throw new Error('Invalid extension type'); + } + if (typeof ext.type === 'string') { + ext.type = [ext.type]; + } + return ext; + }; + /** + * Global registration of all PixiJS extensions. One-stop-shop for extensibility. + * @memberof PIXI + * @namespace extensions + */ + var extensions = { + /** @ignore */ + _addHandlers: null, + /** @ignore */ + _removeHandlers: null, + /** @ignore */ + _queue: {}, + /** + * Remove extensions from PixiJS. + * @param extensions - Extensions to be removed. + * @returns {PIXI.extensions} For chaining. + */ + remove: function () { + var arguments$1 = arguments; - array[offset + stride] = spritePosition.x; - array[offset + stride + 1] = spritePosition.y; + var _this = this; + var extensions = []; + for (var _i = 0; _i < arguments.length; _i++) { + extensions[_i] = arguments$1[_i]; + } + extensions.map(normalizeExtension).forEach(function (ext) { + ext.type.forEach(function (type) { var _a, _b; return (_b = (_a = _this._removeHandlers)[type]) === null || _b === void 0 ? void 0 : _b.call(_a, ext); }); + }); + return this; + }, + /** + * Register new extensions with PixiJS. + * @param extensions - The spread of extensions to add to PixiJS. + * @returns {PIXI.extensions} For chaining. + */ + add: function () { + var arguments$1 = arguments; - array[offset + stride * 2] = spritePosition.x; - array[offset + stride * 2 + 1] = spritePosition.y; + var _this = this; + var extensions = []; + for (var _i = 0; _i < arguments.length; _i++) { + extensions[_i] = arguments$1[_i]; + } + // Handle any extensions either passed as class w/ data or as data + extensions.map(normalizeExtension).forEach(function (ext) { + ext.type.forEach(function (type) { + var handlers = _this._addHandlers; + var queue = _this._queue; + if (!handlers[type]) { + queue[type] = queue[type] || []; + queue[type].push(ext); + } + else { + handlers[type](ext); + } + }); + }); + return this; + }, + /** + * Internal method to handle extensions by name. + * @param type - The extension type. + * @param onAdd - Function for handling when extensions are added/registered passes {@link PIXI.ExtensionFormat}. + * @param onRemove - Function for handling when extensions are removed/unregistered passes {@link PIXI.ExtensionFormat}. + * @returns {PIXI.extensions} For chaining. + */ + handle: function (type, onAdd, onRemove) { + var addHandlers = this._addHandlers = this._addHandlers || {}; + var removeHandlers = this._removeHandlers = this._removeHandlers || {}; + if (addHandlers[type] || removeHandlers[type]) { + throw new Error("Extension type " + type + " already has a handler"); + } + addHandlers[type] = onAdd; + removeHandlers[type] = onRemove; + // Process the queue + var queue = this._queue; + // Process any plugins that have been registered before the handler + if (queue[type]) { + queue[type].forEach(function (ext) { return onAdd(ext); }); + delete queue[type]; + } + return this; + }, + /** + * Handle a type, but using a map by `name` property. + * @param type - Type of extension to handle. + * @param map - The object map of named extensions. + * @returns {PIXI.extensions} For chaining. + */ + handleByMap: function (type, map) { + return this.handle(type, function (extension) { + map[extension.name] = extension.ref; + }, function (extension) { + delete map[extension.name]; + }); + }, + /** + * Handle a type, but using a list of extensions. + * @param type - Type of extension to handle. + * @param list - The list of extensions. + * @returns {PIXI.extensions} For chaining. + */ + handleByList: function (type, list) { + return this.handle(type, function (extension) { + var _a, _b; + if (list.includes(extension.ref)) { + return; + } + list.push(extension.ref); + // TODO: remove me later, only added for @pixi/loaders + if (type === exports.ExtensionType.Loader) { + (_b = (_a = extension.ref).add) === null || _b === void 0 ? void 0 : _b.call(_a); + } + }, function (extension) { + var index = list.indexOf(extension.ref); + if (index !== -1) { + list.splice(index, 1); + } + }); + }, + }; - array[offset + stride * 3] = spritePosition.x; - array[offset + stride * 3 + 1] = spritePosition.y; + /*! + * @pixi/runner - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/runner is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * A Runner is a highly performant and simple alternative to signals. Best used in situations + * where events are dispatched to many objects at high frequency (say every frame!) + * + * + * like a signal.. + * ``` + * import { Runner } from '@pixi/runner'; + * + * const myObject = { + * loaded: new Runner('loaded') + * } + * + * const listener = { + * loaded: function(){ + * // thin + * } + * } + * + * myObject.loaded.add(listener); + * + * myObject.loaded.emit(); + * ``` + * + * Or for handling calling the same function on many items + * ``` + * import { Runner } from '@pixi/runner'; + * + * const myGame = { + * update: new Runner('update') + * } + * + * const gameObject = { + * update: function(time){ + * // update my gamey state + * } + * } + * + * myGame.update.add(gameObject); + * + * myGame.update.emit(time); + * ``` + * @memberof PIXI + */ + var Runner = /** @class */ (function () { + /** + * @param name - The function name that will be executed on the listeners added to this Runner. + */ + function Runner(name) { + this.items = []; + this._name = name; + this._aliasCount = 0; + } + /* eslint-disable jsdoc/require-param, jsdoc/check-param-names */ + /** + * Dispatch/Broadcast Runner to all listeners added to the queue. + * @param {...any} params - (optional) parameters to pass to each listener + */ + /* eslint-enable jsdoc/require-param, jsdoc/check-param-names */ + Runner.prototype.emit = function (a0, a1, a2, a3, a4, a5, a6, a7) { + if (arguments.length > 8) { + throw new Error('max arguments reached'); + } + var _a = this, name = _a.name, items = _a.items; + this._aliasCount++; + for (var i = 0, len = items.length; i < len; i++) { + items[i][name](a0, a1, a2, a3, a4, a5, a6, a7); + } + if (items === this.items) { + this._aliasCount--; + } + return this; + }; + Runner.prototype.ensureNonAliasedItems = function () { + if (this._aliasCount > 0 && this.items.length > 1) { + this._aliasCount = 0; + this.items = this.items.slice(0); + } + }; + /** + * Add a listener to the Runner + * + * Runners do not need to have scope or functions passed to them. + * All that is required is to pass the listening object and ensure that it has contains a function that has the same name + * as the name provided to the Runner when it was created. + * + * Eg A listener passed to this Runner will require a 'complete' function. + * + * ``` + * import { Runner } from '@pixi/runner'; + * + * const complete = new Runner('complete'); + * ``` + * + * The scope used will be the object itself. + * @param {any} item - The object that will be listening. + */ + Runner.prototype.add = function (item) { + if (item[this._name]) { + this.ensureNonAliasedItems(); + this.remove(item); + this.items.push(item); + } + return this; + }; + /** + * Remove a single listener from the dispatch queue. + * @param {any} item - The listener that you would like to remove. + */ + Runner.prototype.remove = function (item) { + var index = this.items.indexOf(item); + if (index !== -1) { + this.ensureNonAliasedItems(); + this.items.splice(index, 1); + } + return this; + }; + /** + * Check to see if the listener is already in the Runner + * @param {any} item - The listener that you would like to check. + */ + Runner.prototype.contains = function (item) { + return this.items.indexOf(item) !== -1; + }; + /** Remove all listeners from the Runner */ + Runner.prototype.removeAll = function () { + this.ensureNonAliasedItems(); + this.items.length = 0; + return this; + }; + /** Remove all references, don't use after this. */ + Runner.prototype.destroy = function () { + this.removeAll(); + this.items = null; + this._name = null; + }; + Object.defineProperty(Runner.prototype, "empty", { + /** + * `true` if there are no this Runner contains no listeners + * @readonly + */ + get: function () { + return this.items.length === 0; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Runner.prototype, "name", { + /** + * The name of the runner. + * @readonly + */ + get: function () { + return this._name; + }, + enumerable: false, + configurable: true + }); + return Runner; + }()); + Object.defineProperties(Runner.prototype, { + /** + * Alias for `emit` + * @memberof PIXI.Runner# + * @method dispatch + * @see PIXI.Runner#emit + */ + dispatch: { value: Runner.prototype.emit }, + /** + * Alias for `emit` + * @memberof PIXI.Runner# + * @method run + * @see PIXI.Runner#emit + */ + run: { value: Runner.prototype.emit }, + }); - offset += stride * 4; - } - }; + /*! + * @pixi/ticker - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/ticker is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ - /** - * - * @param {PIXI.DisplayObject[]} children - the array of display objects to render - * @param {number} startIndex - the index to start from in the children array - * @param {number} amount - the amount of children that will have their rotation uploaded - * @param {number[]} array - The vertices to upload. - * @param {number} stride - Stride to use for iteration. - * @param {number} offset - Offset to start at. - */ + /** + * Target frames per millisecond. + * @static + * @name TARGET_FPMS + * @memberof PIXI.settings + * @type {number} + * @default 0.06 + */ + settings.TARGET_FPMS = 0.06; + /** + * Represents the update priorities used by internal PIXI classes when registered with + * the {@link PIXI.Ticker} object. Higher priority items are updated first and lower + * priority items, such as render, should go later. + * @static + * @constant + * @name UPDATE_PRIORITY + * @memberof PIXI + * @enum {number} + * @property {number} [INTERACTION=50] Highest priority, used for {@link PIXI.InteractionManager} + * @property {number} [HIGH=25] High priority updating, {@link PIXI.VideoBaseTexture} and {@link PIXI.AnimatedSprite} + * @property {number} [NORMAL=0] Default priority for ticker events, see {@link PIXI.Ticker#add}. + * @property {number} [LOW=-25] Low priority used for {@link PIXI.Application} rendering. + * @property {number} [UTILITY=-50] Lowest priority used for {@link PIXI.BasePrepare} utility. + */ + exports.UPDATE_PRIORITY = void 0; + (function (UPDATE_PRIORITY) { + UPDATE_PRIORITY[UPDATE_PRIORITY["INTERACTION"] = 50] = "INTERACTION"; + UPDATE_PRIORITY[UPDATE_PRIORITY["HIGH"] = 25] = "HIGH"; + UPDATE_PRIORITY[UPDATE_PRIORITY["NORMAL"] = 0] = "NORMAL"; + UPDATE_PRIORITY[UPDATE_PRIORITY["LOW"] = -25] = "LOW"; + UPDATE_PRIORITY[UPDATE_PRIORITY["UTILITY"] = -50] = "UTILITY"; + })(exports.UPDATE_PRIORITY || (exports.UPDATE_PRIORITY = {})); - ParticleRenderer.prototype.uploadRotation = function uploadRotation(children, startIndex, amount, array, stride, offset) { - for (var i = 0; i < amount; i++) { - var spriteRotation = children[startIndex + i].rotation; + /** + * Internal class for handling the priority sorting of ticker handlers. + * @private + * @class + * @memberof PIXI + */ + var TickerListener = /** @class */ (function () { + /** + * Constructor + * @private + * @param fn - The listener function to be added for one update + * @param context - The listener context + * @param priority - The priority for emitting + * @param once - If the handler should fire once + */ + function TickerListener(fn, context, priority, once) { + if (context === void 0) { context = null; } + if (priority === void 0) { priority = 0; } + if (once === void 0) { once = false; } + /** The next item in chain. */ + this.next = null; + /** The previous item in chain. */ + this.previous = null; + /** `true` if this listener has been destroyed already. */ + this._destroyed = false; + this.fn = fn; + this.context = context; + this.priority = priority; + this.once = once; + } + /** + * Simple compare function to figure out if a function and context match. + * @private + * @param fn - The listener function to be added for one update + * @param context - The listener context + * @returns `true` if the listener match the arguments + */ + TickerListener.prototype.match = function (fn, context) { + if (context === void 0) { context = null; } + return this.fn === fn && this.context === context; + }; + /** + * Emit by calling the current function. + * @private + * @param deltaTime - time since the last emit. + * @returns Next ticker + */ + TickerListener.prototype.emit = function (deltaTime) { + if (this.fn) { + if (this.context) { + this.fn.call(this.context, deltaTime); + } + else { + this.fn(deltaTime); + } + } + var redirect = this.next; + if (this.once) { + this.destroy(true); + } + // Soft-destroying should remove + // the next reference + if (this._destroyed) { + this.next = null; + } + return redirect; + }; + /** + * Connect to the list. + * @private + * @param previous - Input node, previous listener + */ + TickerListener.prototype.connect = function (previous) { + this.previous = previous; + if (previous.next) { + previous.next.previous = this; + } + this.next = previous.next; + previous.next = this; + }; + /** + * Destroy and don't use after this. + * @private + * @param hard - `true` to remove the `next` reference, this + * is considered a hard destroy. Soft destroy maintains the next reference. + * @returns The listener to redirect while emitting or removing. + */ + TickerListener.prototype.destroy = function (hard) { + if (hard === void 0) { hard = false; } + this._destroyed = true; + this.fn = null; + this.context = null; + // Disconnect, hook up next and previous + if (this.previous) { + this.previous.next = this.next; + } + if (this.next) { + this.next.previous = this.previous; + } + // Redirect to the next item + var redirect = this.next; + // Remove references + this.next = hard ? null : redirect; + this.previous = null; + return redirect; + }; + return TickerListener; + }()); - array[offset] = spriteRotation; - array[offset + stride] = spriteRotation; - array[offset + stride * 2] = spriteRotation; - array[offset + stride * 3] = spriteRotation; + /** + * A Ticker class that runs an update loop that other objects listen to. + * + * This class is composed around listeners meant for execution on the next requested animation frame. + * Animation frames are requested only when necessary, e.g. When the ticker is started and the emitter has listeners. + * @class + * @memberof PIXI + */ + var Ticker = /** @class */ (function () { + function Ticker() { + var _this = this; + /** + * Whether or not this ticker should invoke the method + * {@link PIXI.Ticker#start} automatically + * when a listener is added. + */ + this.autoStart = false; + /** + * Scalar time value from last frame to this frame. + * This value is capped by setting {@link PIXI.Ticker#minFPS} + * and is scaled with {@link PIXI.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + */ + this.deltaTime = 1; + /** + * The last time {@link PIXI.Ticker#update} was invoked. + * This value is also reset internally outside of invoking + * update, but only when a new animation frame is requested. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + */ + this.lastTime = -1; + /** + * Factor of current {@link PIXI.Ticker#deltaTime}. + * @example + * // Scales ticker.deltaTime to what would be + * // the equivalent of approximately 120 FPS + * ticker.speed = 2; + */ + this.speed = 1; + /** + * Whether or not this ticker has been started. + * `true` if {@link PIXI.Ticker#start} has been called. + * `false` if {@link PIXI.Ticker#stop} has been called. + * While `false`, this value may change to `true` in the + * event of {@link PIXI.Ticker#autoStart} being `true` + * and a listener is added. + */ + this.started = false; + /** Internal current frame request ID */ + this._requestId = null; + /** + * Internal value managed by minFPS property setter and getter. + * This is the maximum allowed milliseconds between updates. + */ + this._maxElapsedMS = 100; + /** + * Internal value managed by minFPS property setter and getter. + * This is the minimum allowed milliseconds between updates. + */ + this._minElapsedMS = 0; + /** If enabled, deleting is disabled.*/ + this._protected = false; + /** The last time keyframe was executed. Maintains a relatively fixed interval with the previous value. */ + this._lastFrame = -1; + this._head = new TickerListener(null, null, Infinity); + this.deltaMS = 1 / settings.TARGET_FPMS; + this.elapsedMS = 1 / settings.TARGET_FPMS; + this._tick = function (time) { + _this._requestId = null; + if (_this.started) { + // Invoke listeners now + _this.update(time); + // Listener side effects may have modified ticker state. + if (_this.started && _this._requestId === null && _this._head.next) { + _this._requestId = requestAnimationFrame(_this._tick); + } + } + }; + } + /** + * Conditionally requests a new animation frame. + * If a frame has not already been requested, and if the internal + * emitter has listeners, a new frame is requested. + * @private + */ + Ticker.prototype._requestIfNeeded = function () { + if (this._requestId === null && this._head.next) { + // ensure callbacks get correct delta + this.lastTime = performance.now(); + this._lastFrame = this.lastTime; + this._requestId = requestAnimationFrame(this._tick); + } + }; + /** + * Conditionally cancels a pending animation frame. + * @private + */ + Ticker.prototype._cancelIfNeeded = function () { + if (this._requestId !== null) { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } + }; + /** + * Conditionally requests a new animation frame. + * If the ticker has been started it checks if a frame has not already + * been requested, and if the internal emitter has listeners. If these + * conditions are met, a new frame is requested. If the ticker has not + * been started, but autoStart is `true`, then the ticker starts now, + * and continues with the previous conditions to request a new frame. + * @private + */ + Ticker.prototype._startIfPossible = function () { + if (this.started) { + this._requestIfNeeded(); + } + else if (this.autoStart) { + this.start(); + } + }; + /** + * Register a handler for tick events. Calls continuously unless + * it is removed or the ticker is stopped. + * @param fn - The listener function to be added for updates + * @param context - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns This instance of a ticker + */ + Ticker.prototype.add = function (fn, context, priority) { + if (priority === void 0) { priority = exports.UPDATE_PRIORITY.NORMAL; } + return this._addListener(new TickerListener(fn, context, priority)); + }; + /** + * Add a handler for the tick event which is only execute once. + * @param fn - The listener function to be added for one update + * @param context - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns This instance of a ticker + */ + Ticker.prototype.addOnce = function (fn, context, priority) { + if (priority === void 0) { priority = exports.UPDATE_PRIORITY.NORMAL; } + return this._addListener(new TickerListener(fn, context, priority, true)); + }; + /** + * Internally adds the event handler so that it can be sorted by priority. + * Priority allows certain handler (user, AnimatedSprite, Interaction) to be run + * before the rendering. + * @private + * @param listener - Current listener being added. + * @returns This instance of a ticker + */ + Ticker.prototype._addListener = function (listener) { + // For attaching to head + var current = this._head.next; + var previous = this._head; + // Add the first item + if (!current) { + listener.connect(previous); + } + else { + // Go from highest to lowest priority + while (current) { + if (listener.priority > current.priority) { + listener.connect(previous); + break; + } + previous = current; + current = current.next; + } + // Not yet connected + if (!listener.previous) { + listener.connect(previous); + } + } + this._startIfPossible(); + return this; + }; + /** + * Removes any handlers matching the function and context parameters. + * If no handlers are left after removing, then it cancels the animation frame. + * @param fn - The listener function to be removed + * @param context - The listener context to be removed + * @returns This instance of a ticker + */ + Ticker.prototype.remove = function (fn, context) { + var listener = this._head.next; + while (listener) { + // We found a match, lets remove it + // no break to delete all possible matches + // incase a listener was added 2+ times + if (listener.match(fn, context)) { + listener = listener.destroy(); + } + else { + listener = listener.next; + } + } + if (!this._head.next) { + this._cancelIfNeeded(); + } + return this; + }; + Object.defineProperty(Ticker.prototype, "count", { + /** + * The number of listeners on this ticker, calculated by walking through linked list + * @readonly + * @member {number} + */ + get: function () { + if (!this._head) { + return 0; + } + var count = 0; + var current = this._head; + while ((current = current.next)) { + count++; + } + return count; + }, + enumerable: false, + configurable: true + }); + /** Starts the ticker. If the ticker has listeners a new animation frame is requested at this point. */ + Ticker.prototype.start = function () { + if (!this.started) { + this.started = true; + this._requestIfNeeded(); + } + }; + /** Stops the ticker. If the ticker has requested an animation frame it is canceled at this point. */ + Ticker.prototype.stop = function () { + if (this.started) { + this.started = false; + this._cancelIfNeeded(); + } + }; + /** Destroy the ticker and don't use after this. Calling this method removes all references to internal events. */ + Ticker.prototype.destroy = function () { + if (!this._protected) { + this.stop(); + var listener = this._head.next; + while (listener) { + listener = listener.destroy(true); + } + this._head.destroy(); + this._head = null; + } + }; + /** + * Triggers an update. An update entails setting the + * current {@link PIXI.Ticker#elapsedMS}, + * the current {@link PIXI.Ticker#deltaTime}, + * invoking all listeners with current deltaTime, + * and then finally setting {@link PIXI.Ticker#lastTime} + * with the value of currentTime that was provided. + * This method will be called automatically by animation + * frame callbacks if the ticker instance has been started + * and listeners are added. + * @param {number} [currentTime=performance.now()] - the current time of execution + */ + Ticker.prototype.update = function (currentTime) { + if (currentTime === void 0) { currentTime = performance.now(); } + var elapsedMS; + // If the difference in time is zero or negative, we ignore most of the work done here. + // If there is no valid difference, then should be no reason to let anyone know about it. + // A zero delta, is exactly that, nothing should update. + // + // The difference in time can be negative, and no this does not mean time traveling. + // This can be the result of a race condition between when an animation frame is requested + // on the current JavaScript engine event loop, and when the ticker's start method is invoked + // (which invokes the internal _requestIfNeeded method). If a frame is requested before + // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, + // can receive a time argument that can be less than the lastTime value that was set within + // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. + // + // This check covers this browser engine timing issue, as well as if consumers pass an invalid + // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. + if (currentTime > this.lastTime) { + // Save uncapped elapsedMS for measurement + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + // cap the milliseconds elapsed used for deltaTime + if (elapsedMS > this._maxElapsedMS) { + elapsedMS = this._maxElapsedMS; + } + elapsedMS *= this.speed; + // If not enough time has passed, exit the function. + // Get ready for next frame by setting _lastFrame, but based on _minElapsedMS + // adjustment to ensure a relatively stable interval. + if (this._minElapsedMS) { + var delta = currentTime - this._lastFrame | 0; + if (delta < this._minElapsedMS) { + return; + } + this._lastFrame = currentTime - (delta % this._minElapsedMS); + } + this.deltaMS = elapsedMS; + this.deltaTime = this.deltaMS * settings.TARGET_FPMS; + // Cache a local reference, in-case ticker is destroyed + // during the emit, we can still check for head.next + var head = this._head; + // Invoke listeners added to internal emitter + var listener = head.next; + while (listener) { + listener = listener.emit(this.deltaTime); + } + if (!head.next) { + this._cancelIfNeeded(); + } + } + else { + this.deltaTime = this.deltaMS = this.elapsedMS = 0; + } + this.lastTime = currentTime; + }; + Object.defineProperty(Ticker.prototype, "FPS", { + /** + * The frames per second at which this ticker is running. + * The default is approximately 60 in most modern browsers. + * **Note:** This does not factor in the value of + * {@link PIXI.Ticker#speed}, which is specific + * to scaling {@link PIXI.Ticker#deltaTime}. + * @member {number} + * @readonly + */ + get: function () { + return 1000 / this.elapsedMS; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Ticker.prototype, "minFPS", { + /** + * Manages the maximum amount of milliseconds allowed to + * elapse between invoking {@link PIXI.Ticker#update}. + * This value is used to cap {@link PIXI.Ticker#deltaTime}, + * but does not effect the measured value of {@link PIXI.Ticker#FPS}. + * When setting this property it is clamped to a value between + * `0` and `PIXI.settings.TARGET_FPMS * 1000`. + * @member {number} + * @default 10 + */ + get: function () { + return 1000 / this._maxElapsedMS; + }, + set: function (fps) { + // Minimum must be below the maxFPS + var minFPS = Math.min(this.maxFPS, fps); + // Must be at least 0, but below 1 / settings.TARGET_FPMS + var minFPMS = Math.min(Math.max(0, minFPS) / 1000, settings.TARGET_FPMS); + this._maxElapsedMS = 1 / minFPMS; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Ticker.prototype, "maxFPS", { + /** + * Manages the minimum amount of milliseconds required to + * elapse between invoking {@link PIXI.Ticker#update}. + * This will effect the measured value of {@link PIXI.Ticker#FPS}. + * If it is set to `0`, then there is no limit; PixiJS will render as many frames as it can. + * Otherwise it will be at least `minFPS` + * @member {number} + * @default 0 + */ + get: function () { + if (this._minElapsedMS) { + return Math.round(1000 / this._minElapsedMS); + } + return 0; + }, + set: function (fps) { + if (fps === 0) { + this._minElapsedMS = 0; + } + else { + // Max must be at least the minFPS + var maxFPS = Math.max(this.minFPS, fps); + this._minElapsedMS = 1 / (maxFPS / 1000); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Ticker, "shared", { + /** + * The shared ticker instance used by {@link PIXI.AnimatedSprite} and by + * {@link PIXI.VideoResource} to update animation frames / video textures. + * + * It may also be used by {@link PIXI.Application} if created with the `sharedTicker` option property set to true. + * + * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance. + * Please follow the examples for usage, including how to opt-out of auto-starting the shared ticker. + * @example + * let ticker = PIXI.Ticker.shared; + * // Set this to prevent starting this ticker when listeners are added. + * // By default this is true only for the PIXI.Ticker.shared instance. + * ticker.autoStart = false; + * // FYI, call this to ensure the ticker is stopped. It should be stopped + * // if you have not attempted to render anything yet. + * ticker.stop(); + * // Call this when you are ready for a running shared ticker. + * ticker.start(); + * @example + * // You may use the shared ticker to render... + * let renderer = PIXI.autoDetectRenderer(); + * let stage = new PIXI.Container(); + * document.body.appendChild(renderer.view); + * ticker.add(function (time) { + * renderer.render(stage); + * }); + * @example + * // Or you can just update it manually. + * ticker.autoStart = false; + * ticker.stop(); + * function animate(time) { + * ticker.update(time); + * renderer.render(stage); + * requestAnimationFrame(animate); + * } + * animate(performance.now()); + * @member {PIXI.Ticker} + * @static + */ + get: function () { + if (!Ticker._shared) { + var shared = Ticker._shared = new Ticker(); + shared.autoStart = true; + shared._protected = true; + } + return Ticker._shared; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Ticker, "system", { + /** + * The system ticker instance used by {@link PIXI.InteractionManager} and by + * {@link PIXI.BasePrepare} for core timing functionality that shouldn't usually need to be paused, + * unlike the `shared` ticker which drives visual animations and rendering which may want to be paused. + * + * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance. + * @member {PIXI.Ticker} + * @static + */ + get: function () { + if (!Ticker._system) { + var system = Ticker._system = new Ticker(); + system.autoStart = true; + system._protected = true; + } + return Ticker._system; + }, + enumerable: false, + configurable: true + }); + return Ticker; + }()); - offset += stride * 4; - } - }; + /** + * Middleware for for Application Ticker. + * @example + * import {TickerPlugin} from '@pixi/ticker'; + * import {Application} from '@pixi/app'; + * import {extensions} from '@pixi/extensions'; + * extensions.add(TickerPlugin); + * @class + * @memberof PIXI + */ + var TickerPlugin = /** @class */ (function () { + function TickerPlugin() { + } + /** + * Initialize the plugin with scope of application instance + * @static + * @private + * @param {object} [options] - See application options + */ + TickerPlugin.init = function (options) { + var _this = this; + // Set default + options = Object.assign({ + autoStart: true, + sharedTicker: false, + }, options); + // Create ticker setter + Object.defineProperty(this, 'ticker', { + set: function (ticker) { + if (this._ticker) { + this._ticker.remove(this.render, this); + } + this._ticker = ticker; + if (ticker) { + ticker.add(this.render, this, exports.UPDATE_PRIORITY.LOW); + } + }, + get: function () { + return this._ticker; + }, + }); + /** + * Convenience method for stopping the render. + * @method + * @memberof PIXI.Application + * @instance + */ + this.stop = function () { + _this._ticker.stop(); + }; + /** + * Convenience method for starting the render. + * @method + * @memberof PIXI.Application + * @instance + */ + this.start = function () { + _this._ticker.start(); + }; + /** + * Internal reference to the ticker. + * @type {PIXI.Ticker} + * @name _ticker + * @memberof PIXI.Application# + * @private + */ + this._ticker = null; + /** + * Ticker for doing render updates. + * @type {PIXI.Ticker} + * @name ticker + * @memberof PIXI.Application# + * @default PIXI.Ticker.shared + */ + this.ticker = options.sharedTicker ? Ticker.shared : new Ticker(); + // Start the rendering + if (options.autoStart) { + this.start(); + } + }; + /** + * Clean up the ticker, scoped to application. + * @static + * @private + */ + TickerPlugin.destroy = function () { + if (this._ticker) { + var oldTicker = this._ticker; + this.ticker = null; + oldTicker.destroy(); + } + }; + /** @ignore */ + TickerPlugin.extension = exports.ExtensionType.Application; + return TickerPlugin; + }()); + + /*! + * @pixi/core - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/core is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ - /** - * - * @param {PIXI.DisplayObject[]} children - the array of display objects to render - * @param {number} startIndex - the index to start from in the children array - * @param {number} amount - the amount of children that will have their rotation uploaded - * @param {number[]} array - The vertices to upload. - * @param {number} stride - Stride to use for iteration. - * @param {number} offset - Offset to start at. - */ + /** + * The maximum support for using WebGL. If a device does not + * support WebGL version, for instance WebGL 2, it will still + * attempt to fallback support to WebGL 1. If you want to + * explicitly remove feature support to target a more stable + * baseline, prefer a lower environment. + * + * Due to {@link https://bugs.chromium.org/p/chromium/issues/detail?id=934823|bug in chromium} + * we disable webgl2 by default for all non-apple mobile devices. + * @static + * @name PREFER_ENV + * @memberof PIXI.settings + * @type {number} + * @default PIXI.ENV.WEBGL2 + */ + settings.PREFER_ENV = isMobile.any ? exports.ENV.WEBGL : exports.ENV.WEBGL2; + /** + * If set to `true`, *only* Textures and BaseTexture objects stored + * in the caches ({@link PIXI.utils.TextureCache TextureCache} and + * {@link PIXI.utils.BaseTextureCache BaseTextureCache}) can be + * used when calling {@link PIXI.Texture.from Texture.from} or + * {@link PIXI.BaseTexture.from BaseTexture.from}. + * Otherwise, these `from` calls throw an exception. Using this property + * can be useful if you want to enforce preloading all assets with + * {@link PIXI.Loader Loader}. + * @static + * @name STRICT_TEXTURE_CACHE + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + settings.STRICT_TEXTURE_CACHE = false; + /** + * Collection of installed resource types, class must extend {@link PIXI.Resource}. + * @example + * class CustomResource extends PIXI.Resource { + * // MUST have source, options constructor signature + * // for auto-detected resources to be created. + * constructor(source, options) { + * super(); + * } + * upload(renderer, baseTexture, glTexture) { + * // upload with GL + * return true; + * } + * // used to auto-detect resource + * static test(source, extension) { + * return extension === 'xyz'|| source instanceof SomeClass; + * } + * } + * // Install the new resource type + * PIXI.INSTALLED.push(CustomResource); + * @memberof PIXI + * @type {Array} + * @static + * @readonly + */ + var INSTALLED = []; + /** + * Create a resource element from a single source element. This + * auto-detects which type of resource to create. All resources that + * are auto-detectable must have a static `test` method and a constructor + * with the arguments `(source, options?)`. Currently, the supported + * resources for auto-detection include: + * - {@link PIXI.ImageResource} + * - {@link PIXI.CanvasResource} + * - {@link PIXI.VideoResource} + * - {@link PIXI.SVGResource} + * - {@link PIXI.BufferResource} + * @static + * @memberof PIXI + * @function autoDetectResource + * @param {string|*} source - Resource source, this can be the URL to the resource, + * a typed-array (for BufferResource), HTMLVideoElement, SVG data-uri + * or any other resource that can be auto-detected. If not resource is + * detected, it's assumed to be an ImageResource. + * @param {object} [options] - Pass-through options to use for Resource + * @param {number} [options.width] - Width of BufferResource or SVG rasterization + * @param {number} [options.height] - Height of BufferResource or SVG rasterization + * @param {boolean} [options.autoLoad=true] - Image, SVG and Video flag to start loading + * @param {number} [options.scale=1] - SVG source scale. Overridden by width, height + * @param {boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - Image option to create Bitmap object + * @param {boolean} [options.crossorigin=true] - Image and Video option to set crossOrigin + * @param {boolean} [options.autoPlay=true] - Video option to start playing video immediately + * @param {number} [options.updateFPS=0] - Video option to update how many times a second the + * texture should be updated from the video. Leave at 0 to update at every render + * @returns {PIXI.Resource} The created resource. + */ + function autoDetectResource(source, options) { + if (!source) { + return null; + } + var extension = ''; + if (typeof source === 'string') { + // search for file extension: period, 3-4 chars, then ?, # or EOL + var result = (/\.(\w{3,4})(?:$|\?|#)/i).exec(source); + if (result) { + extension = result[1].toLowerCase(); + } + } + for (var i = INSTALLED.length - 1; i >= 0; --i) { + var ResourcePlugin = INSTALLED[i]; + if (ResourcePlugin.test && ResourcePlugin.test(source, extension)) { + return new ResourcePlugin(source, options); + } + } + throw new Error('Unrecognized source type to auto-detect Resource'); + } - ParticleRenderer.prototype.uploadUvs = function uploadUvs(children, startIndex, amount, array, stride, offset) { - for (var i = 0; i < amount; ++i) { - var textureUvs = children[startIndex + i]._texture._uvs; + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$i = function(d, b) { + extendStatics$i = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$i(d, b); + }; - if (textureUvs) { - array[offset] = textureUvs.x0; - array[offset + 1] = textureUvs.y0; + function __extends$i(d, b) { + extendStatics$i(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } - array[offset + stride] = textureUvs.x1; - array[offset + stride + 1] = textureUvs.y1; + var __assign = function() { + __assign = Object.assign || function __assign(t) { + var arguments$1 = arguments; - array[offset + stride * 2] = textureUvs.x2; - array[offset + stride * 2 + 1] = textureUvs.y2; + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments$1[i]; + for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p)) { t[p] = s[p]; } } + } + return t; + }; + return __assign.apply(this, arguments); + }; - array[offset + stride * 3] = textureUvs.x3; - array[offset + stride * 3 + 1] = textureUvs.y3; + function __rest(s, e) { + var t = {}; + for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + { t[p] = s[p]; } } + if (s != null && typeof Object.getOwnPropertySymbols === "function") + { for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + { t[p[i]] = s[p[i]]; } + } } + return t; + } - offset += stride * 4; - } else { - // TODO you know this can be easier! - array[offset] = 0; - array[offset + 1] = 0; + /** + * Base resource class for textures that manages validation and uploading, depending on its type. + * + * Uploading of a base texture to the GPU is required. + * @memberof PIXI + */ + var Resource = /** @class */ (function () { + /** + * @param width - Width of the resource + * @param height - Height of the resource + */ + function Resource(width, height) { + if (width === void 0) { width = 0; } + if (height === void 0) { height = 0; } + this._width = width; + this._height = height; + this.destroyed = false; + this.internal = false; + this.onResize = new Runner('setRealSize'); + this.onUpdate = new Runner('update'); + this.onError = new Runner('onError'); + } + /** + * Bind to a parent BaseTexture + * @param baseTexture - Parent texture + */ + Resource.prototype.bind = function (baseTexture) { + this.onResize.add(baseTexture); + this.onUpdate.add(baseTexture); + this.onError.add(baseTexture); + // Call a resize immediate if we already + // have the width and height of the resource + if (this._width || this._height) { + this.onResize.emit(this._width, this._height); + } + }; + /** + * Unbind to a parent BaseTexture + * @param baseTexture - Parent texture + */ + Resource.prototype.unbind = function (baseTexture) { + this.onResize.remove(baseTexture); + this.onUpdate.remove(baseTexture); + this.onError.remove(baseTexture); + }; + /** + * Trigger a resize event + * @param width - X dimension + * @param height - Y dimension + */ + Resource.prototype.resize = function (width, height) { + if (width !== this._width || height !== this._height) { + this._width = width; + this._height = height; + this.onResize.emit(width, height); + } + }; + Object.defineProperty(Resource.prototype, "valid", { + /** + * Has been validated + * @readonly + */ + get: function () { + return !!this._width && !!this._height; + }, + enumerable: false, + configurable: true + }); + /** Has been updated trigger event. */ + Resource.prototype.update = function () { + if (!this.destroyed) { + this.onUpdate.emit(); + } + }; + /** + * This can be overridden to start preloading a resource + * or do any other prepare step. + * @protected + * @returns Handle the validate event + */ + Resource.prototype.load = function () { + return Promise.resolve(this); + }; + Object.defineProperty(Resource.prototype, "width", { + /** + * The width of the resource. + * @readonly + */ + get: function () { + return this._width; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Resource.prototype, "height", { + /** + * The height of the resource. + * @readonly + */ + get: function () { + return this._height; + }, + enumerable: false, + configurable: true + }); + /** + * Set the style, optional to override + * @param _renderer - yeah, renderer! + * @param _baseTexture - the texture + * @param _glTexture - texture instance for this webgl context + * @returns - `true` is success + */ + Resource.prototype.style = function (_renderer, _baseTexture, _glTexture) { + return false; + }; + /** Clean up anything, this happens when destroying is ready. */ + Resource.prototype.dispose = function () { + // override + }; + /** + * Call when destroying resource, unbind any BaseTexture object + * before calling this method, as reference counts are maintained + * internally. + */ + Resource.prototype.destroy = function () { + if (!this.destroyed) { + this.destroyed = true; + this.dispose(); + this.onError.removeAll(); + this.onError = null; + this.onResize.removeAll(); + this.onResize = null; + this.onUpdate.removeAll(); + this.onUpdate = null; + } + }; + /** + * Abstract, used to auto-detect resource type. + * @param {*} _source - The source object + * @param {string} _extension - The extension of source, if set + */ + Resource.test = function (_source, _extension) { + return false; + }; + return Resource; + }()); - array[offset + stride] = 0; - array[offset + stride + 1] = 0; + /** + * @interface SharedArrayBuffer + */ + /** + * Buffer resource with data of typed array. + * @memberof PIXI + */ + var BufferResource = /** @class */ (function (_super) { + __extends$i(BufferResource, _super); + /** + * @param source - Source buffer + * @param options - Options + * @param {number} options.width - Width of the texture + * @param {number} options.height - Height of the texture + */ + function BufferResource(source, options) { + var _this = this; + var _a = options || {}, width = _a.width, height = _a.height; + if (!width || !height) { + throw new Error('BufferResource width or height invalid'); + } + _this = _super.call(this, width, height) || this; + _this.data = source; + return _this; + } + /** + * Upload the texture to the GPU. + * @param renderer - Upload to the renderer + * @param baseTexture - Reference to parent texture + * @param glTexture - glTexture + * @returns - true is success + */ + BufferResource.prototype.upload = function (renderer, baseTexture, glTexture) { + var gl = renderer.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === exports.ALPHA_MODES.UNPACK); + var width = baseTexture.realWidth; + var height = baseTexture.realHeight; + if (glTexture.width === width && glTexture.height === height) { + gl.texSubImage2D(baseTexture.target, 0, 0, 0, width, height, baseTexture.format, glTexture.type, this.data); + } + else { + glTexture.width = width; + glTexture.height = height; + gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, width, height, 0, baseTexture.format, glTexture.type, this.data); + } + return true; + }; + /** Destroy and don't use after this. */ + BufferResource.prototype.dispose = function () { + this.data = null; + }; + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @returns {boolean} `true` if + */ + BufferResource.test = function (source) { + return source instanceof Float32Array + || source instanceof Uint8Array + || source instanceof Uint32Array; + }; + return BufferResource; + }(Resource)); + + var defaultBufferOptions = { + scaleMode: exports.SCALE_MODES.NEAREST, + format: exports.FORMATS.RGBA, + alphaMode: exports.ALPHA_MODES.NPM, + }; + /** + * A Texture stores the information that represents an image. + * All textures have a base texture, which contains information about the source. + * Therefore you can have many textures all using a single BaseTexture + * @memberof PIXI + * @typeParam R - The BaseTexture's Resource type. + * @typeParam RO - The options for constructing resource. + */ + var BaseTexture = /** @class */ (function (_super) { + __extends$i(BaseTexture, _super); + /** + * @param {PIXI.Resource|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} [resource=null] - + * The current resource to use, for things that aren't Resource objects, will be converted + * into a Resource. + * @param options - Collection of options + * @param {PIXI.MIPMAP_MODES} [options.mipmap=PIXI.settings.MIPMAP_TEXTURES] - If mipmapping is enabled for texture + * @param {number} [options.anisotropicLevel=PIXI.settings.ANISOTROPIC_LEVEL] - Anisotropic filtering level of texture + * @param {PIXI.WRAP_MODES} [options.wrapMode=PIXI.settings.WRAP_MODE] - Wrap mode for textures + * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.settings.SCALE_MODE] - Default scale mode, linear, nearest + * @param {PIXI.FORMATS} [options.format=PIXI.FORMATS.RGBA] - GL format type + * @param {PIXI.TYPES} [options.type=PIXI.TYPES.UNSIGNED_BYTE] - GL data type + * @param {PIXI.TARGETS} [options.target=PIXI.TARGETS.TEXTURE_2D] - GL texture target + * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Pre multiply the image alpha + * @param {number} [options.width=0] - Width of the texture + * @param {number} [options.height=0] - Height of the texture + * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - Resolution of the base texture + * @param {object} [options.resourceOptions] - Optional resource options, + * see {@link PIXI.autoDetectResource autoDetectResource} + */ + function BaseTexture(resource, options) { + if (resource === void 0) { resource = null; } + if (options === void 0) { options = null; } + var _this = _super.call(this) || this; + options = options || {}; + var alphaMode = options.alphaMode, mipmap = options.mipmap, anisotropicLevel = options.anisotropicLevel, scaleMode = options.scaleMode, width = options.width, height = options.height, wrapMode = options.wrapMode, format = options.format, type = options.type, target = options.target, resolution = options.resolution, resourceOptions = options.resourceOptions; + // Convert the resource to a Resource object + if (resource && !(resource instanceof Resource)) { + resource = autoDetectResource(resource, resourceOptions); + resource.internal = true; + } + _this.resolution = resolution || settings.RESOLUTION; + _this.width = Math.round((width || 0) * _this.resolution) / _this.resolution; + _this.height = Math.round((height || 0) * _this.resolution) / _this.resolution; + _this._mipmap = mipmap !== undefined ? mipmap : settings.MIPMAP_TEXTURES; + _this.anisotropicLevel = anisotropicLevel !== undefined ? anisotropicLevel : settings.ANISOTROPIC_LEVEL; + _this._wrapMode = wrapMode || settings.WRAP_MODE; + _this._scaleMode = scaleMode !== undefined ? scaleMode : settings.SCALE_MODE; + _this.format = format || exports.FORMATS.RGBA; + _this.type = type || exports.TYPES.UNSIGNED_BYTE; + _this.target = target || exports.TARGETS.TEXTURE_2D; + _this.alphaMode = alphaMode !== undefined ? alphaMode : exports.ALPHA_MODES.UNPACK; + _this.uid = uid(); + _this.touched = 0; + _this.isPowerOfTwo = false; + _this._refreshPOT(); + _this._glTextures = {}; + _this.dirtyId = 0; + _this.dirtyStyleId = 0; + _this.cacheId = null; + _this.valid = width > 0 && height > 0; + _this.textureCacheIds = []; + _this.destroyed = false; + _this.resource = null; + _this._batchEnabled = 0; + _this._batchLocation = 0; + _this.parentTextureArray = null; + /** + * Fired when a not-immediately-available source finishes loading. + * @protected + * @event PIXI.BaseTexture#loaded + * @param {PIXI.BaseTexture} baseTexture - Resource loaded. + */ + /** + * Fired when a not-immediately-available source fails to load. + * @protected + * @event PIXI.BaseTexture#error + * @param {PIXI.BaseTexture} baseTexture - Resource errored. + * @param {ErrorEvent} event - Load error event. + */ + /** + * Fired when BaseTexture is updated. + * @protected + * @event PIXI.BaseTexture#loaded + * @param {PIXI.BaseTexture} baseTexture - Resource loaded. + */ + /** + * Fired when BaseTexture is updated. + * @protected + * @event PIXI.BaseTexture#update + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated. + */ + /** + * Fired when BaseTexture is destroyed. + * @protected + * @event PIXI.BaseTexture#dispose + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed. + */ + // Set the resource + _this.setResource(resource); + return _this; + } + Object.defineProperty(BaseTexture.prototype, "realWidth", { + /** + * Pixel width of the source of this texture + * @readonly + */ + get: function () { + return Math.round(this.width * this.resolution); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "realHeight", { + /** + * Pixel height of the source of this texture + * @readonly + */ + get: function () { + return Math.round(this.height * this.resolution); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "mipmap", { + /** + * Mipmap mode of the texture, affects downscaled images + * @default PIXI.settings.MIPMAP_TEXTURES + */ + get: function () { + return this._mipmap; + }, + set: function (value) { + if (this._mipmap !== value) { + this._mipmap = value; + this.dirtyStyleId++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "scaleMode", { + /** + * The scale mode to apply when scaling this texture + * @default PIXI.settings.SCALE_MODE + */ + get: function () { + return this._scaleMode; + }, + set: function (value) { + if (this._scaleMode !== value) { + this._scaleMode = value; + this.dirtyStyleId++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "wrapMode", { + /** + * How the texture wraps + * @default PIXI.settings.WRAP_MODE + */ + get: function () { + return this._wrapMode; + }, + set: function (value) { + if (this._wrapMode !== value) { + this._wrapMode = value; + this.dirtyStyleId++; + } + }, + enumerable: false, + configurable: true + }); + /** + * Changes style options of BaseTexture + * @param scaleMode - Pixi scalemode + * @param mipmap - enable mipmaps + * @returns - this + */ + BaseTexture.prototype.setStyle = function (scaleMode, mipmap) { + var dirty; + if (scaleMode !== undefined && scaleMode !== this.scaleMode) { + this.scaleMode = scaleMode; + dirty = true; + } + if (mipmap !== undefined && mipmap !== this.mipmap) { + this.mipmap = mipmap; + dirty = true; + } + if (dirty) { + this.dirtyStyleId++; + } + return this; + }; + /** + * Changes w/h/resolution. Texture becomes valid if width and height are greater than zero. + * @param desiredWidth - Desired visual width + * @param desiredHeight - Desired visual height + * @param resolution - Optionally set resolution + * @returns - this + */ + BaseTexture.prototype.setSize = function (desiredWidth, desiredHeight, resolution) { + resolution = resolution || this.resolution; + return this.setRealSize(desiredWidth * resolution, desiredHeight * resolution, resolution); + }; + /** + * Sets real size of baseTexture, preserves current resolution. + * @param realWidth - Full rendered width + * @param realHeight - Full rendered height + * @param resolution - Optionally set resolution + * @returns - this + */ + BaseTexture.prototype.setRealSize = function (realWidth, realHeight, resolution) { + this.resolution = resolution || this.resolution; + this.width = Math.round(realWidth) / this.resolution; + this.height = Math.round(realHeight) / this.resolution; + this._refreshPOT(); + this.update(); + return this; + }; + /** + * Refresh check for isPowerOfTwo texture based on size + * @private + */ + BaseTexture.prototype._refreshPOT = function () { + this.isPowerOfTwo = isPow2(this.realWidth) && isPow2(this.realHeight); + }; + /** + * Changes resolution + * @param resolution - res + * @returns - this + */ + BaseTexture.prototype.setResolution = function (resolution) { + var oldResolution = this.resolution; + if (oldResolution === resolution) { + return this; + } + this.resolution = resolution; + if (this.valid) { + this.width = Math.round(this.width * oldResolution) / resolution; + this.height = Math.round(this.height * oldResolution) / resolution; + this.emit('update', this); + } + this._refreshPOT(); + return this; + }; + /** + * Sets the resource if it wasn't set. Throws error if resource already present + * @param resource - that is managing this BaseTexture + * @returns - this + */ + BaseTexture.prototype.setResource = function (resource) { + if (this.resource === resource) { + return this; + } + if (this.resource) { + throw new Error('Resource can be set only once'); + } + resource.bind(this); + this.resource = resource; + return this; + }; + /** Invalidates the object. Texture becomes valid if width and height are greater than zero. */ + BaseTexture.prototype.update = function () { + if (!this.valid) { + if (this.width > 0 && this.height > 0) { + this.valid = true; + this.emit('loaded', this); + this.emit('update', this); + } + } + else { + this.dirtyId++; + this.dirtyStyleId++; + this.emit('update', this); + } + }; + /** + * Handle errors with resources. + * @private + * @param event - Error event emitted. + */ + BaseTexture.prototype.onError = function (event) { + this.emit('error', this, event); + }; + /** + * Destroys this base texture. + * The method stops if resource doesn't want this texture to be destroyed. + * Removes texture from all caches. + */ + BaseTexture.prototype.destroy = function () { + // remove and destroy the resource + if (this.resource) { + this.resource.unbind(this); + // only destroy resourced created internally + if (this.resource.internal) { + this.resource.destroy(); + } + this.resource = null; + } + if (this.cacheId) { + delete BaseTextureCache[this.cacheId]; + delete TextureCache[this.cacheId]; + this.cacheId = null; + } + // finally let the WebGL renderer know.. + this.dispose(); + BaseTexture.removeFromCache(this); + this.textureCacheIds = null; + this.destroyed = true; + }; + /** + * Frees the texture from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * @fires PIXI.BaseTexture#dispose + */ + BaseTexture.prototype.dispose = function () { + this.emit('dispose', this); + }; + /** Utility function for BaseTexture|Texture cast. */ + BaseTexture.prototype.castToBaseTexture = function () { + return this; + }; + /** + * Helper function that creates a base texture based on the source you provide. + * The source can be - image url, image element, canvas element. If the + * source is an image url or an image element and not in the base texture + * cache, it will be created and loaded. + * @static + * @param {string|string[]|HTMLImageElement|HTMLCanvasElement|SVGElement|HTMLVideoElement} source - The + * source to create base texture from. + * @param options - See {@link PIXI.BaseTexture}'s constructor for options. + * @param {string} [options.pixiIdPrefix=pixiid] - If a source has no id, this is the prefix of the generated id + * @param {boolean} [strict] - Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}. + * @returns {PIXI.BaseTexture} The new base texture. + */ + BaseTexture.from = function (source, options, strict) { + if (strict === void 0) { strict = settings.STRICT_TEXTURE_CACHE; } + var isFrame = typeof source === 'string'; + var cacheId = null; + if (isFrame) { + cacheId = source; + } + else { + if (!source._pixiId) { + var prefix = (options && options.pixiIdPrefix) || 'pixiid'; + source._pixiId = prefix + "_" + uid(); + } + cacheId = source._pixiId; + } + var baseTexture = BaseTextureCache[cacheId]; + // Strict-mode rejects invalid cacheIds + if (isFrame && strict && !baseTexture) { + throw new Error("The cacheId \"" + cacheId + "\" does not exist in BaseTextureCache."); + } + if (!baseTexture) { + baseTexture = new BaseTexture(source, options); + baseTexture.cacheId = cacheId; + BaseTexture.addToCache(baseTexture, cacheId); + } + return baseTexture; + }; + /** + * Create a new BaseTexture with a BufferResource from a Float32Array. + * RGBA values are floats from 0 to 1. + * @param {Float32Array|Uint8Array} buffer - The optional array to use, if no data + * is provided, a new Float32Array is created. + * @param width - Width of the resource + * @param height - Height of the resource + * @param options - See {@link PIXI.BaseTexture}'s constructor for options. + * Default properties are different from the constructor's defaults. + * @param {PIXI.FORMATS} [options.format=PIXI.FORMATS.RGBA] - GL format type + * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.NPM] - Image alpha, not premultiplied by default + * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.SCALE_MODES.NEAREST] - Scale mode, pixelating by default + * @returns - The resulting new BaseTexture + */ + BaseTexture.fromBuffer = function (buffer, width, height, options) { + buffer = buffer || new Float32Array(width * height * 4); + var resource = new BufferResource(buffer, { width: width, height: height }); + var type = buffer instanceof Float32Array ? exports.TYPES.FLOAT : exports.TYPES.UNSIGNED_BYTE; + return new BaseTexture(resource, Object.assign({}, defaultBufferOptions, options || { width: width, height: height, type: type })); + }; + /** + * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache. + * @param {string} id - The id that the BaseTexture will be stored against. + */ + BaseTexture.addToCache = function (baseTexture, id) { + if (id) { + if (baseTexture.textureCacheIds.indexOf(id) === -1) { + baseTexture.textureCacheIds.push(id); + } + if (BaseTextureCache[id]) { + // eslint-disable-next-line no-console + console.warn("BaseTexture added to the cache with an id [" + id + "] that already had an entry"); + } + BaseTextureCache[id] = baseTexture; + } + }; + /** + * Remove a BaseTexture from the global BaseTextureCache. + * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself. + * @returns {PIXI.BaseTexture|null} The BaseTexture that was removed. + */ + BaseTexture.removeFromCache = function (baseTexture) { + if (typeof baseTexture === 'string') { + var baseTextureFromCache = BaseTextureCache[baseTexture]; + if (baseTextureFromCache) { + var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture); + if (index > -1) { + baseTextureFromCache.textureCacheIds.splice(index, 1); + } + delete BaseTextureCache[baseTexture]; + return baseTextureFromCache; + } + } + else if (baseTexture && baseTexture.textureCacheIds) { + for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) { + delete BaseTextureCache[baseTexture.textureCacheIds[i]]; + } + baseTexture.textureCacheIds.length = 0; + return baseTexture; + } + return null; + }; + /** Global number of the texture batch, used by multi-texture renderers. */ + BaseTexture._globalBatch = 0; + return BaseTexture; + }(eventemitter3)); - array[offset + stride * 2] = 0; - array[offset + stride * 2 + 1] = 0; + /** + * Resource that can manage several resource (items) inside. + * All resources need to have the same pixel size. + * Parent class for CubeResource and ArrayResource + * @memberof PIXI + */ + var AbstractMultiResource = /** @class */ (function (_super) { + __extends$i(AbstractMultiResource, _super); + /** + * @param length + * @param options - Options to for Resource constructor + * @param {number} [options.width] - Width of the resource + * @param {number} [options.height] - Height of the resource + */ + function AbstractMultiResource(length, options) { + var _this = this; + var _a = options || {}, width = _a.width, height = _a.height; + _this = _super.call(this, width, height) || this; + _this.items = []; + _this.itemDirtyIds = []; + for (var i = 0; i < length; i++) { + var partTexture = new BaseTexture(); + _this.items.push(partTexture); + // -2 - first run of texture array upload + // -1 - texture item was allocated + // >=0 - texture item uploaded , in sync with items[i].dirtyId + _this.itemDirtyIds.push(-2); + } + _this.length = length; + _this._load = null; + _this.baseTexture = null; + return _this; + } + /** + * Used from ArrayResource and CubeResource constructors. + * @param resources - Can be resources, image elements, canvas, etc. , + * length should be same as constructor length + * @param options - Detect options for resources + */ + AbstractMultiResource.prototype.initFromArray = function (resources, options) { + for (var i = 0; i < this.length; i++) { + if (!resources[i]) { + continue; + } + if (resources[i].castToBaseTexture) { + this.addBaseTextureAt(resources[i].castToBaseTexture(), i); + } + else if (resources[i] instanceof Resource) { + this.addResourceAt(resources[i], i); + } + else { + this.addResourceAt(autoDetectResource(resources[i], options), i); + } + } + }; + /** Destroy this BaseImageResource. */ + AbstractMultiResource.prototype.dispose = function () { + for (var i = 0, len = this.length; i < len; i++) { + this.items[i].destroy(); + } + this.items = null; + this.itemDirtyIds = null; + this._load = null; + }; + /** + * Set a resource by ID + * @param resource + * @param index - Zero-based index of resource to set + * @returns - Instance for chaining + */ + AbstractMultiResource.prototype.addResourceAt = function (resource, index) { + if (!this.items[index]) { + throw new Error("Index " + index + " is out of bounds"); + } + // Inherit the first resource dimensions + if (resource.valid && !this.valid) { + this.resize(resource.width, resource.height); + } + this.items[index].setResource(resource); + return this; + }; + /** + * Set the parent base texture. + * @param baseTexture + */ + AbstractMultiResource.prototype.bind = function (baseTexture) { + if (this.baseTexture !== null) { + throw new Error('Only one base texture per TextureArray is allowed'); + } + _super.prototype.bind.call(this, baseTexture); + for (var i = 0; i < this.length; i++) { + this.items[i].parentTextureArray = baseTexture; + this.items[i].on('update', baseTexture.update, baseTexture); + } + }; + /** + * Unset the parent base texture. + * @param baseTexture + */ + AbstractMultiResource.prototype.unbind = function (baseTexture) { + _super.prototype.unbind.call(this, baseTexture); + for (var i = 0; i < this.length; i++) { + this.items[i].parentTextureArray = null; + this.items[i].off('update', baseTexture.update, baseTexture); + } + }; + /** + * Load all the resources simultaneously + * @returns - When load is resolved + */ + AbstractMultiResource.prototype.load = function () { + var _this = this; + if (this._load) { + return this._load; + } + var resources = this.items.map(function (item) { return item.resource; }).filter(function (item) { return item; }); + // TODO: also implement load part-by-part strategy + var promises = resources.map(function (item) { return item.load(); }); + this._load = Promise.all(promises) + .then(function () { + var _a = _this.items[0], realWidth = _a.realWidth, realHeight = _a.realHeight; + _this.resize(realWidth, realHeight); + return Promise.resolve(_this); + }); + return this._load; + }; + return AbstractMultiResource; + }(Resource)); - array[offset + stride * 3] = 0; - array[offset + stride * 3 + 1] = 0; + /** + * A resource that contains a number of sources. + * @memberof PIXI + */ + var ArrayResource = /** @class */ (function (_super) { + __extends$i(ArrayResource, _super); + /** + * @param source - Number of items in array or the collection + * of image URLs to use. Can also be resources, image elements, canvas, etc. + * @param options - Options to apply to {@link PIXI.autoDetectResource} + * @param {number} [options.width] - Width of the resource + * @param {number} [options.height] - Height of the resource + */ + function ArrayResource(source, options) { + var _this = this; + var _a = options || {}, width = _a.width, height = _a.height; + var urls; + var length; + if (Array.isArray(source)) { + urls = source; + length = source.length; + } + else { + length = source; + } + _this = _super.call(this, length, { width: width, height: height }) || this; + if (urls) { + _this.initFromArray(urls, options); + } + return _this; + } + /** + * Set a baseTexture by ID, + * ArrayResource just takes resource from it, nothing more + * @param baseTexture + * @param index - Zero-based index of resource to set + * @returns - Instance for chaining + */ + ArrayResource.prototype.addBaseTextureAt = function (baseTexture, index) { + if (baseTexture.resource) { + this.addResourceAt(baseTexture.resource, index); + } + else { + throw new Error('ArrayResource does not support RenderTexture'); + } + return this; + }; + /** + * Add binding + * @param baseTexture + */ + ArrayResource.prototype.bind = function (baseTexture) { + _super.prototype.bind.call(this, baseTexture); + baseTexture.target = exports.TARGETS.TEXTURE_2D_ARRAY; + }; + /** + * Upload the resources to the GPU. + * @param renderer + * @param texture + * @param glTexture + * @returns - whether texture was uploaded + */ + ArrayResource.prototype.upload = function (renderer, texture, glTexture) { + var _a = this, length = _a.length, itemDirtyIds = _a.itemDirtyIds, items = _a.items; + var gl = renderer.gl; + if (glTexture.dirtyId < 0) { + gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, glTexture.internalFormat, this._width, this._height, length, 0, texture.format, glTexture.type, null); + } + for (var i = 0; i < length; i++) { + var item = items[i]; + if (itemDirtyIds[i] < item.dirtyId) { + itemDirtyIds[i] = item.dirtyId; + if (item.valid) { + gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, 0, // xoffset + 0, // yoffset + i, // zoffset + item.resource.width, item.resource.height, 1, texture.format, glTexture.type, item.resource.source); + } + } + } + return true; + }; + return ArrayResource; + }(AbstractMultiResource)); - offset += stride * 4; - } - } - }; + /** + * Base for all the image/canvas resources. + * @memberof PIXI + */ + var BaseImageResource = /** @class */ (function (_super) { + __extends$i(BaseImageResource, _super); + /** + * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} source + */ + function BaseImageResource(source) { + var _this = this; + var sourceAny = source; + var width = sourceAny.naturalWidth || sourceAny.videoWidth || sourceAny.width; + var height = sourceAny.naturalHeight || sourceAny.videoHeight || sourceAny.height; + _this = _super.call(this, width, height) || this; + _this.source = source; + _this.noSubImage = false; + return _this; + } + /** + * Set cross origin based detecting the url and the crossorigin + * @param element - Element to apply crossOrigin + * @param url - URL to check + * @param crossorigin - Cross origin value to use + */ + BaseImageResource.crossOrigin = function (element, url, crossorigin) { + if (crossorigin === undefined && url.indexOf('data:') !== 0) { + element.crossOrigin = determineCrossOrigin(url); + } + else if (crossorigin !== false) { + element.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; + } + }; + /** + * Upload the texture to the GPU. + * @param renderer - Upload to the renderer + * @param baseTexture - Reference to parent texture + * @param glTexture + * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} [source] - (optional) + * @returns - true is success + */ + BaseImageResource.prototype.upload = function (renderer, baseTexture, glTexture, source) { + var gl = renderer.gl; + var width = baseTexture.realWidth; + var height = baseTexture.realHeight; + source = source || this.source; + if (source instanceof HTMLImageElement) { + if (!source.complete || source.naturalWidth === 0) { + return false; + } + } + else if (source instanceof HTMLVideoElement) { + if (source.readyState <= 1) { + return false; + } + } + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === exports.ALPHA_MODES.UNPACK); + if (!this.noSubImage + && baseTexture.target === gl.TEXTURE_2D + && glTexture.width === width + && glTexture.height === height) { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, baseTexture.format, glTexture.type, source); + } + else { + glTexture.width = width; + glTexture.height = height; + gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, baseTexture.format, glTexture.type, source); + } + return true; + }; + /** + * Checks if source width/height was changed, resize can cause extra baseTexture update. + * Triggers one update in any case. + */ + BaseImageResource.prototype.update = function () { + if (this.destroyed) { + return; + } + var source = this.source; + var width = source.naturalWidth || source.videoWidth || source.width; + var height = source.naturalHeight || source.videoHeight || source.height; + this.resize(width, height); + _super.prototype.update.call(this); + }; + /** Destroy this {@link BaseImageResource} */ + BaseImageResource.prototype.dispose = function () { + this.source = null; + }; + return BaseImageResource; + }(Resource)); - /** - * - * @param {PIXI.DisplayObject[]} children - the array of display objects to render - * @param {number} startIndex - the index to start from in the children array - * @param {number} amount - the amount of children that will have their rotation uploaded - * @param {number[]} array - The vertices to upload. - * @param {number} stride - Stride to use for iteration. - * @param {number} offset - Offset to start at. - */ + /** + * @interface OffscreenCanvas + */ + /** + * Resource type for HTMLCanvasElement. + * @memberof PIXI + */ + var CanvasResource = /** @class */ (function (_super) { + __extends$i(CanvasResource, _super); + /** + * @param source - Canvas element to use + */ + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + function CanvasResource(source) { + return _super.call(this, source) || this; + } + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @returns {boolean} `true` if source is HTMLCanvasElement or OffscreenCanvas + */ + CanvasResource.test = function (source) { + var OffscreenCanvas = globalThis.OffscreenCanvas; + // Check for browsers that don't yet support OffscreenCanvas + if (OffscreenCanvas && source instanceof OffscreenCanvas) { + return true; + } + return globalThis.HTMLCanvasElement && source instanceof HTMLCanvasElement; + }; + return CanvasResource; + }(BaseImageResource)); + /** + * Resource for a CubeTexture which contains six resources. + * @memberof PIXI + */ + var CubeResource = /** @class */ (function (_super) { + __extends$i(CubeResource, _super); + /** + * @param {Array} [source] - Collection of URLs or resources + * to use as the sides of the cube. + * @param options - ImageResource options + * @param {number} [options.width] - Width of resource + * @param {number} [options.height] - Height of resource + * @param {number} [options.autoLoad=true] - Whether to auto-load resources + * @param {number} [options.linkBaseTexture=true] - In case BaseTextures are supplied, + * whether to copy them or use + */ + function CubeResource(source, options) { + var _this = this; + var _a = options || {}, width = _a.width, height = _a.height, autoLoad = _a.autoLoad, linkBaseTexture = _a.linkBaseTexture; + if (source && source.length !== CubeResource.SIDES) { + throw new Error("Invalid length. Got " + source.length + ", expected 6"); + } + _this = _super.call(this, 6, { width: width, height: height }) || this; + for (var i = 0; i < CubeResource.SIDES; i++) { + _this.items[i].target = exports.TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + i; + } + _this.linkBaseTexture = linkBaseTexture !== false; + if (source) { + _this.initFromArray(source, options); + } + if (autoLoad !== false) { + _this.load(); + } + return _this; + } + /** + * Add binding. + * @param baseTexture - parent base texture + */ + CubeResource.prototype.bind = function (baseTexture) { + _super.prototype.bind.call(this, baseTexture); + baseTexture.target = exports.TARGETS.TEXTURE_CUBE_MAP; + }; + CubeResource.prototype.addBaseTextureAt = function (baseTexture, index, linkBaseTexture) { + if (!this.items[index]) { + throw new Error("Index " + index + " is out of bounds"); + } + if (!this.linkBaseTexture + || baseTexture.parentTextureArray + || Object.keys(baseTexture._glTextures).length > 0) { + // copy mode + if (baseTexture.resource) { + this.addResourceAt(baseTexture.resource, index); + } + else { + throw new Error("CubeResource does not support copying of renderTexture."); + } + } + else { + // link mode, the difficult one! + baseTexture.target = exports.TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + index; + baseTexture.parentTextureArray = this.baseTexture; + this.items[index] = baseTexture; + } + if (baseTexture.valid && !this.valid) { + this.resize(baseTexture.realWidth, baseTexture.realHeight); + } + this.items[index] = baseTexture; + return this; + }; + /** + * Upload the resource + * @param renderer + * @param _baseTexture + * @param glTexture + * @returns {boolean} true is success + */ + CubeResource.prototype.upload = function (renderer, _baseTexture, glTexture) { + var dirty = this.itemDirtyIds; + for (var i = 0; i < CubeResource.SIDES; i++) { + var side = this.items[i]; + if (dirty[i] < side.dirtyId || glTexture.dirtyId < _baseTexture.dirtyId) { + if (side.valid && side.resource) { + side.resource.upload(renderer, side, glTexture); + dirty[i] = side.dirtyId; + } + else if (dirty[i] < -1) { + // either item is not valid yet, either its a renderTexture + // allocate the memory + renderer.gl.texImage2D(side.target, 0, glTexture.internalFormat, _baseTexture.realWidth, _baseTexture.realHeight, 0, _baseTexture.format, glTexture.type, null); + dirty[i] = -1; + } + } + } + return true; + }; + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @returns {boolean} `true` if source is an array of 6 elements + */ + CubeResource.test = function (source) { + return Array.isArray(source) && source.length === CubeResource.SIDES; + }; + /** Number of texture sides to store for CubeResources. */ + CubeResource.SIDES = 6; + return CubeResource; + }(AbstractMultiResource)); - ParticleRenderer.prototype.uploadAlpha = function uploadAlpha(children, startIndex, amount, array, stride, offset) { - for (var i = 0; i < amount; i++) { - var spriteAlpha = children[startIndex + i].alpha; + /** + * Resource type for HTMLImageElement. + * @memberof PIXI + */ + var ImageResource = /** @class */ (function (_super) { + __extends$i(ImageResource, _super); + /** + * @param source - image source or URL + * @param options + * @param {boolean} [options.autoLoad=true] - start loading process + * @param {boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - whether its required to create + * a bitmap before upload + * @param {boolean} [options.crossorigin=true] - Load image using cross origin + * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Premultiply image alpha in bitmap + */ + function ImageResource(source, options) { + var _this = this; + options = options || {}; + if (!(source instanceof HTMLImageElement)) { + var imageElement = new Image(); + BaseImageResource.crossOrigin(imageElement, source, options.crossorigin); + imageElement.src = source; + source = imageElement; + } + _this = _super.call(this, source) || this; + // FireFox 68, and possibly other versions, seems like setting the HTMLImageElement#width and #height + // to non-zero values before its loading completes if images are in a cache. + // Because of this, need to set the `_width` and the `_height` to zero to avoid uploading incomplete images. + // Please refer to the issue #5968 (https://github.com/pixijs/pixi.js/issues/5968). + if (!source.complete && !!_this._width && !!_this._height) { + _this._width = 0; + _this._height = 0; + } + _this.url = source.src; + _this._process = null; + _this.preserveBitmap = false; + _this.createBitmap = (options.createBitmap !== undefined + ? options.createBitmap : settings.CREATE_IMAGE_BITMAP) && !!globalThis.createImageBitmap; + _this.alphaMode = typeof options.alphaMode === 'number' ? options.alphaMode : null; + _this.bitmap = null; + _this._load = null; + if (options.autoLoad !== false) { + _this.load(); + } + return _this; + } + /** + * Returns a promise when image will be loaded and processed. + * @param createBitmap - whether process image into bitmap + */ + ImageResource.prototype.load = function (createBitmap) { + var _this = this; + if (this._load) { + return this._load; + } + if (createBitmap !== undefined) { + this.createBitmap = createBitmap; + } + this._load = new Promise(function (resolve, reject) { + var source = _this.source; + _this.url = source.src; + var completed = function () { + if (_this.destroyed) { + return; + } + source.onload = null; + source.onerror = null; + _this.resize(source.width, source.height); + _this._load = null; + if (_this.createBitmap) { + resolve(_this.process()); + } + else { + resolve(_this); + } + }; + if (source.complete && source.src) { + completed(); + } + else { + source.onload = completed; + source.onerror = function (event) { + // Avoids Promise freezing when resource broken + reject(event); + _this.onError.emit(event); + }; + } + }); + return this._load; + }; + /** + * Called when we need to convert image into BitmapImage. + * Can be called multiple times, real promise is cached inside. + * @returns - Cached promise to fill that bitmap + */ + ImageResource.prototype.process = function () { + var _this = this; + var source = this.source; + if (this._process !== null) { + return this._process; + } + if (this.bitmap !== null || !globalThis.createImageBitmap) { + return Promise.resolve(this); + } + var createImageBitmap = globalThis.createImageBitmap; + var cors = !source.crossOrigin || source.crossOrigin === 'anonymous'; + this._process = fetch(source.src, { + mode: cors ? 'cors' : 'no-cors' + }) + .then(function (r) { return r.blob(); }) + .then(function (blob) { return createImageBitmap(blob, 0, 0, source.width, source.height, { + premultiplyAlpha: _this.alphaMode === null || _this.alphaMode === exports.ALPHA_MODES.UNPACK + ? 'premultiply' : 'none', + }); }) + .then(function (bitmap) { + if (_this.destroyed) { + return Promise.reject(); + } + _this.bitmap = bitmap; + _this.update(); + _this._process = null; + return Promise.resolve(_this); + }); + return this._process; + }; + /** + * Upload the image resource to GPU. + * @param renderer - Renderer to upload to + * @param baseTexture - BaseTexture for this resource + * @param glTexture - GLTexture to use + * @returns {boolean} true is success + */ + ImageResource.prototype.upload = function (renderer, baseTexture, glTexture) { + if (typeof this.alphaMode === 'number') { + // bitmap stores unpack premultiply flag, we dont have to notify texImage2D about it + baseTexture.alphaMode = this.alphaMode; + } + if (!this.createBitmap) { + return _super.prototype.upload.call(this, renderer, baseTexture, glTexture); + } + if (!this.bitmap) { + // yeah, ignore the output + this.process(); + if (!this.bitmap) { + return false; + } + } + _super.prototype.upload.call(this, renderer, baseTexture, glTexture, this.bitmap); + if (!this.preserveBitmap) { + // checks if there are other renderers that possibly need this bitmap + var flag = true; + var glTextures = baseTexture._glTextures; + for (var key in glTextures) { + var otherTex = glTextures[key]; + if (otherTex !== glTexture && otherTex.dirtyId !== baseTexture.dirtyId) { + flag = false; + break; + } + } + if (flag) { + if (this.bitmap.close) { + this.bitmap.close(); + } + this.bitmap = null; + } + } + return true; + }; + /** Destroys this resource. */ + ImageResource.prototype.dispose = function () { + this.source.onload = null; + this.source.onerror = null; + _super.prototype.dispose.call(this); + if (this.bitmap) { + this.bitmap.close(); + this.bitmap = null; + } + this._process = null; + this._load = null; + }; + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @returns {boolean} `true` if source is string or HTMLImageElement + */ + ImageResource.test = function (source) { + return typeof source === 'string' || source instanceof HTMLImageElement; + }; + return ImageResource; + }(BaseImageResource)); - array[offset] = spriteAlpha; - array[offset + stride] = spriteAlpha; - array[offset + stride * 2] = spriteAlpha; - array[offset + stride * 3] = spriteAlpha; + /** + * Resource type for SVG elements and graphics. + * @memberof PIXI + */ + var SVGResource = /** @class */ (function (_super) { + __extends$i(SVGResource, _super); + /** + * @param sourceBase64 - Base64 encoded SVG element or URL for SVG file. + * @param {object} [options] - Options to use + * @param {number} [options.scale=1] - Scale to apply to SVG. Overridden by... + * @param {number} [options.width] - Rasterize SVG this wide. Aspect ratio preserved if height not specified. + * @param {number} [options.height] - Rasterize SVG this high. Aspect ratio preserved if width not specified. + * @param {boolean} [options.autoLoad=true] - Start loading right away. + */ + function SVGResource(sourceBase64, options) { + var _this = this; + options = options || {}; + _this = _super.call(this, settings.ADAPTER.createCanvas()) || this; + _this._width = 0; + _this._height = 0; + _this.svg = sourceBase64; + _this.scale = options.scale || 1; + _this._overrideWidth = options.width; + _this._overrideHeight = options.height; + _this._resolve = null; + _this._crossorigin = options.crossorigin; + _this._load = null; + if (options.autoLoad !== false) { + _this.load(); + } + return _this; + } + SVGResource.prototype.load = function () { + var _this = this; + if (this._load) { + return this._load; + } + this._load = new Promise(function (resolve) { + // Save this until after load is finished + _this._resolve = function () { + _this.resize(_this.source.width, _this.source.height); + resolve(_this); + }; + // Convert SVG inline string to data-uri + if (SVGResource.SVG_XML.test(_this.svg.trim())) { + if (!btoa) { + throw new Error('Your browser doesn\'t support base64 conversions.'); + } + _this.svg = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(_this.svg))); + } + _this._loadSvg(); + }); + return this._load; + }; + /** Loads an SVG image from `imageUrl` or `data URL`. */ + SVGResource.prototype._loadSvg = function () { + var _this = this; + var tempImage = new Image(); + BaseImageResource.crossOrigin(tempImage, this.svg, this._crossorigin); + tempImage.src = this.svg; + tempImage.onerror = function (event) { + if (!_this._resolve) { + return; + } + tempImage.onerror = null; + _this.onError.emit(event); + }; + tempImage.onload = function () { + if (!_this._resolve) { + return; + } + var svgWidth = tempImage.width; + var svgHeight = tempImage.height; + if (!svgWidth || !svgHeight) { + throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.'); + } + // Set render size + var width = svgWidth * _this.scale; + var height = svgHeight * _this.scale; + if (_this._overrideWidth || _this._overrideHeight) { + width = _this._overrideWidth || _this._overrideHeight / svgHeight * svgWidth; + height = _this._overrideHeight || _this._overrideWidth / svgWidth * svgHeight; + } + width = Math.round(width); + height = Math.round(height); + // Create a canvas element + var canvas = _this.source; + canvas.width = width; + canvas.height = height; + canvas._pixiId = "canvas_" + uid(); + // Draw the Svg to the canvas + canvas + .getContext('2d') + .drawImage(tempImage, 0, 0, svgWidth, svgHeight, 0, 0, width, height); + _this._resolve(); + _this._resolve = null; + }; + }; + /** + * Get size from an svg string using a regular expression. + * @param svgString - a serialized svg element + * @returns - image extension + */ + SVGResource.getSize = function (svgString) { + var sizeMatch = SVGResource.SVG_SIZE.exec(svgString); + var size = {}; + if (sizeMatch) { + size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3])); + size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7])); + } + return size; + }; + /** Destroys this texture. */ + SVGResource.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this._resolve = null; + this._crossorigin = null; + }; + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @param {string} extension - The extension of source, if set + * @returns {boolean} - If the source is a SVG source or data file + */ + SVGResource.test = function (source, extension) { + // url file extension is SVG + return extension === 'svg' + // source is SVG data-uri + || (typeof source === 'string' && source.startsWith('data:image/svg+xml')) + // source is SVG inline + || (typeof source === 'string' && SVGResource.SVG_XML.test(source)); + }; + /** + * Regular expression for SVG XML document. + * @example <?xml version="1.0" encoding="utf-8" ?><!-- image/svg --><svg + * @readonly + */ + SVGResource.SVG_XML = /^(<\?xml[^?]+\?>)?\s*()]*-->)?\s*\]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len + return SVGResource; + }(BaseImageResource)); - offset += stride * 4; - } - }; + /** + * Resource type for {@code HTMLVideoElement}. + * @memberof PIXI + */ + var VideoResource = /** @class */ (function (_super) { + __extends$i(VideoResource, _super); + /** + * @param {HTMLVideoElement|object|string|Array} source - Video element to use. + * @param {object} [options] - Options to use + * @param {boolean} [options.autoLoad=true] - Start loading the video immediately + * @param {boolean} [options.autoPlay=true] - Start playing video immediately + * @param {number} [options.updateFPS=0] - How many times a second to update the texture from the video. + * Leave at 0 to update at every render. + * @param {boolean} [options.crossorigin=true] - Load image using cross origin + */ + function VideoResource(source, options) { + var _this = this; + options = options || {}; + if (!(source instanceof HTMLVideoElement)) { + var videoElement = document.createElement('video'); + // workaround for https://github.com/pixijs/pixi.js/issues/5996 + videoElement.setAttribute('preload', 'auto'); + videoElement.setAttribute('webkit-playsinline', ''); + videoElement.setAttribute('playsinline', ''); + if (typeof source === 'string') { + source = [source]; + } + var firstSrc = source[0].src || source[0]; + BaseImageResource.crossOrigin(videoElement, firstSrc, options.crossorigin); + // array of objects or strings + for (var i = 0; i < source.length; ++i) { + var sourceElement = document.createElement('source'); + var _a = source[i], src = _a.src, mime = _a.mime; + src = src || source[i]; + var baseSrc = src.split('?').shift().toLowerCase(); + var ext = baseSrc.slice(baseSrc.lastIndexOf('.') + 1); + mime = mime || VideoResource.MIME_TYPES[ext] || "video/" + ext; + sourceElement.src = src; + sourceElement.type = mime; + videoElement.appendChild(sourceElement); + } + // Override the source + source = videoElement; + } + _this = _super.call(this, source) || this; + _this.noSubImage = true; + _this._autoUpdate = true; + _this._isConnectedToTicker = false; + _this._updateFPS = options.updateFPS || 0; + _this._msToNextUpdate = 0; + _this.autoPlay = options.autoPlay !== false; + _this._load = null; + _this._resolve = null; + // Bind for listeners + _this._onCanPlay = _this._onCanPlay.bind(_this); + _this._onError = _this._onError.bind(_this); + if (options.autoLoad !== false) { + _this.load(); + } + return _this; + } + /** + * Trigger updating of the texture. + * @param _deltaTime - time delta since last tick + */ + VideoResource.prototype.update = function (_deltaTime) { + if (!this.destroyed) { + // account for if video has had its playbackRate changed + var elapsedMS = Ticker.shared.elapsedMS * this.source.playbackRate; + this._msToNextUpdate = Math.floor(this._msToNextUpdate - elapsedMS); + if (!this._updateFPS || this._msToNextUpdate <= 0) { + _super.prototype.update.call(this); + this._msToNextUpdate = this._updateFPS ? Math.floor(1000 / this._updateFPS) : 0; + } + } + }; + /** + * Start preloading the video resource. + * @returns {Promise} Handle the validate event + */ + VideoResource.prototype.load = function () { + var _this = this; + if (this._load) { + return this._load; + } + var source = this.source; + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) + && source.width && source.height) { + source.complete = true; + } + source.addEventListener('play', this._onPlayStart.bind(this)); + source.addEventListener('pause', this._onPlayStop.bind(this)); + if (!this._isSourceReady()) { + source.addEventListener('canplay', this._onCanPlay); + source.addEventListener('canplaythrough', this._onCanPlay); + source.addEventListener('error', this._onError, true); + } + else { + this._onCanPlay(); + } + this._load = new Promise(function (resolve) { + if (_this.valid) { + resolve(_this); + } + else { + _this._resolve = resolve; + source.load(); + } + }); + return this._load; + }; + /** + * Handle video error events. + * @param event + */ + VideoResource.prototype._onError = function (event) { + this.source.removeEventListener('error', this._onError, true); + this.onError.emit(event); + }; + /** + * Returns true if the underlying source is playing. + * @returns - True if playing. + */ + VideoResource.prototype._isSourcePlaying = function () { + var source = this.source; + return (!source.paused && !source.ended && this._isSourceReady()); + }; + /** + * Returns true if the underlying source is ready for playing. + * @returns - True if ready. + */ + VideoResource.prototype._isSourceReady = function () { + var source = this.source; + return source.readyState > 2; + }; + /** Runs the update loop when the video is ready to play. */ + VideoResource.prototype._onPlayStart = function () { + // Just in case the video has not received its can play even yet.. + if (!this.valid) { + this._onCanPlay(); + } + if (this.autoUpdate && !this._isConnectedToTicker) { + Ticker.shared.add(this.update, this); + this._isConnectedToTicker = true; + } + }; + /** Fired when a pause event is triggered, stops the update loop. */ + VideoResource.prototype._onPlayStop = function () { + if (this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + }; + /** Fired when the video is loaded and ready to play. */ + VideoResource.prototype._onCanPlay = function () { + var source = this.source; + source.removeEventListener('canplay', this._onCanPlay); + source.removeEventListener('canplaythrough', this._onCanPlay); + var valid = this.valid; + this.resize(source.videoWidth, source.videoHeight); + // prevent multiple loaded dispatches.. + if (!valid && this._resolve) { + this._resolve(this); + this._resolve = null; + } + if (this._isSourcePlaying()) { + this._onPlayStart(); + } + else if (this.autoPlay) { + source.play(); + } + }; + /** Destroys this texture. */ + VideoResource.prototype.dispose = function () { + if (this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + var source = this.source; + if (source) { + source.removeEventListener('error', this._onError, true); + source.pause(); + source.src = ''; + source.load(); + } + _super.prototype.dispose.call(this); + }; + Object.defineProperty(VideoResource.prototype, "autoUpdate", { + /** Should the base texture automatically update itself, set to true by default. */ + get: function () { + return this._autoUpdate; + }, + set: function (value) { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + if (!this._autoUpdate && this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + else if (this._autoUpdate && !this._isConnectedToTicker && this._isSourcePlaying()) { + Ticker.shared.add(this.update, this); + this._isConnectedToTicker = true; + } + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(VideoResource.prototype, "updateFPS", { + /** + * How many times a second to update the texture from the video. Leave at 0 to update at every render. + * A lower fps can help performance, as updating the texture at 60fps on a 30ps video may not be efficient. + */ + get: function () { + return this._updateFPS; + }, + set: function (value) { + if (value !== this._updateFPS) { + this._updateFPS = value; + } + }, + enumerable: false, + configurable: true + }); + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @param {string} extension - The extension of source, if set + * @returns {boolean} `true` if video source + */ + VideoResource.test = function (source, extension) { + return (globalThis.HTMLVideoElement && source instanceof HTMLVideoElement) + || VideoResource.TYPES.indexOf(extension) > -1; + }; + /** + * List of common video file extensions supported by VideoResource. + * @readonly + */ + VideoResource.TYPES = ['mp4', 'm4v', 'webm', 'ogg', 'ogv', 'h264', 'avi', 'mov']; + /** + * Map of video MIME types that can't be directly derived from file extensions. + * @readonly + */ + VideoResource.MIME_TYPES = { + ogv: 'video/ogg', + mov: 'video/quicktime', + m4v: 'video/mp4', + }; + return VideoResource; + }(BaseImageResource)); - /** - * Destroys the ParticleRenderer. - * - */ + /** + * Resource type for ImageBitmap. + * @memberof PIXI + */ + var ImageBitmapResource = /** @class */ (function (_super) { + __extends$i(ImageBitmapResource, _super); + /** + * @param source - Image element to use + */ + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + function ImageBitmapResource(source) { + return _super.call(this, source) || this; + } + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @returns {boolean} `true` if source is an ImageBitmap + */ + ImageBitmapResource.test = function (source) { + return !!globalThis.createImageBitmap && typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap; + }; + return ImageBitmapResource; + }(BaseImageResource)); + + INSTALLED.push(ImageResource, ImageBitmapResource, CanvasResource, VideoResource, SVGResource, BufferResource, CubeResource, ArrayResource); + + var _resources = { + __proto__: null, + Resource: Resource, + BaseImageResource: BaseImageResource, + INSTALLED: INSTALLED, + autoDetectResource: autoDetectResource, + AbstractMultiResource: AbstractMultiResource, + ArrayResource: ArrayResource, + BufferResource: BufferResource, + CanvasResource: CanvasResource, + CubeResource: CubeResource, + ImageResource: ImageResource, + SVGResource: SVGResource, + VideoResource: VideoResource, + ImageBitmapResource: ImageBitmapResource + }; + /** + * Resource type for DepthTexture. + * @memberof PIXI + */ + var DepthResource = /** @class */ (function (_super) { + __extends$i(DepthResource, _super); + function DepthResource() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** + * Upload the texture to the GPU. + * @param renderer - Upload to the renderer + * @param baseTexture - Reference to parent texture + * @param glTexture - glTexture + * @returns - true is success + */ + DepthResource.prototype.upload = function (renderer, baseTexture, glTexture) { + var gl = renderer.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === exports.ALPHA_MODES.UNPACK); + var width = baseTexture.realWidth; + var height = baseTexture.realHeight; + if (glTexture.width === width && glTexture.height === height) { + gl.texSubImage2D(baseTexture.target, 0, 0, 0, width, height, baseTexture.format, glTexture.type, this.data); + } + else { + glTexture.width = width; + glTexture.height = height; + gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, width, height, 0, baseTexture.format, glTexture.type, this.data); + } + return true; + }; + return DepthResource; + }(BufferResource)); - ParticleRenderer.prototype.destroy = function destroy() { - if (this.renderer.gl) { - this.renderer.gl.deleteBuffer(this.indexBuffer); - } + /** + * A framebuffer can be used to render contents off of the screen. {@link PIXI.BaseRenderTexture} uses + * one internally to render into itself. You can attach a depth or stencil buffer to a framebuffer. + * + * On WebGL 2 machines, shaders can output to multiple textures simultaneously with GLSL 300 ES. + * @memberof PIXI + */ + var Framebuffer = /** @class */ (function () { + /** + * @param width - Width of the frame buffer + * @param height - Height of the frame buffer + */ + function Framebuffer(width, height) { + this.width = Math.round(width || 100); + this.height = Math.round(height || 100); + this.stencil = false; + this.depth = false; + this.dirtyId = 0; + this.dirtyFormat = 0; + this.dirtySize = 0; + this.depthTexture = null; + this.colorTextures = []; + this.glFramebuffers = {}; + this.disposeRunner = new Runner('disposeFramebuffer'); + this.multisample = exports.MSAA_QUALITY.NONE; + } + Object.defineProperty(Framebuffer.prototype, "colorTexture", { + /** + * Reference to the colorTexture. + * @readonly + */ + get: function () { + return this.colorTextures[0]; + }, + enumerable: false, + configurable: true + }); + /** + * Add texture to the colorTexture array. + * @param index - Index of the array to add the texture to + * @param texture - Texture to add to the array + */ + Framebuffer.prototype.addColorTexture = function (index, texture) { + if (index === void 0) { index = 0; } + // TODO add some validation to the texture - same width / height etc? + this.colorTextures[index] = texture || new BaseTexture(null, { + scaleMode: exports.SCALE_MODES.NEAREST, + resolution: 1, + mipmap: exports.MIPMAP_MODES.OFF, + width: this.width, + height: this.height, + }); + this.dirtyId++; + this.dirtyFormat++; + return this; + }; + /** + * Add a depth texture to the frame buffer. + * @param texture - Texture to add. + */ + Framebuffer.prototype.addDepthTexture = function (texture) { + /* eslint-disable max-len */ + this.depthTexture = texture || new BaseTexture(new DepthResource(null, { width: this.width, height: this.height }), { + scaleMode: exports.SCALE_MODES.NEAREST, + resolution: 1, + width: this.width, + height: this.height, + mipmap: exports.MIPMAP_MODES.OFF, + format: exports.FORMATS.DEPTH_COMPONENT, + type: exports.TYPES.UNSIGNED_SHORT, + }); + this.dirtyId++; + this.dirtyFormat++; + return this; + }; + /** Enable depth on the frame buffer. */ + Framebuffer.prototype.enableDepth = function () { + this.depth = true; + this.dirtyId++; + this.dirtyFormat++; + return this; + }; + /** Enable stencil on the frame buffer. */ + Framebuffer.prototype.enableStencil = function () { + this.stencil = true; + this.dirtyId++; + this.dirtyFormat++; + return this; + }; + /** + * Resize the frame buffer + * @param width - Width of the frame buffer to resize to + * @param height - Height of the frame buffer to resize to + */ + Framebuffer.prototype.resize = function (width, height) { + width = Math.round(width); + height = Math.round(height); + if (width === this.width && height === this.height) + { return; } + this.width = width; + this.height = height; + this.dirtyId++; + this.dirtySize++; + for (var i = 0; i < this.colorTextures.length; i++) { + var texture = this.colorTextures[i]; + var resolution = texture.resolution; + // take into account the fact the texture may have a different resolution.. + texture.setSize(width / resolution, height / resolution); + } + if (this.depthTexture) { + var resolution = this.depthTexture.resolution; + this.depthTexture.setSize(width / resolution, height / resolution); + } + }; + /** Disposes WebGL resources that are connected to this geometry. */ + Framebuffer.prototype.dispose = function () { + this.disposeRunner.emit(this, false); + }; + /** Destroys and removes the depth texture added to this framebuffer. */ + Framebuffer.prototype.destroyDepthTexture = function () { + if (this.depthTexture) { + this.depthTexture.destroy(); + this.depthTexture = null; + ++this.dirtyId; + ++this.dirtyFormat; + } + }; + return Framebuffer; + }()); - _core$ObjectRenderer.prototype.destroy.call(this); + /** + * A BaseRenderTexture is a special texture that allows any PixiJS display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(); + * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 800, height: 600 }); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * let sprite = PIXI.Sprite.from("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, {renderTexture}); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 100, height: 100 }); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * + * renderer.render(sprite, {renderTexture}); // Renders to center of RenderTexture + * ``` + * @memberof PIXI + */ + var BaseRenderTexture = /** @class */ (function (_super) { + __extends$i(BaseRenderTexture, _super); + /** + * @param options + * @param {number} [options.width=100] - The width of the base render texture. + * @param {number} [options.height=100] - The height of the base render texture. + * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} + * for possible values. + * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio + * of the texture being generated. + * @param {PIXI.MSAA_QUALITY} [options.multisample=PIXI.MSAA_QUALITY.NONE] - The number of samples of the frame buffer. + */ + function BaseRenderTexture(options) { + if (options === void 0) { options = {}; } + var _this = this; + if (typeof options === 'number') { + /* eslint-disable prefer-rest-params */ + // Backward compatibility of signature + var width = arguments[0]; + var height = arguments[1]; + var scaleMode = arguments[2]; + var resolution = arguments[3]; + options = { width: width, height: height, scaleMode: scaleMode, resolution: resolution }; + /* eslint-enable prefer-rest-params */ + } + options.width = options.width || 100; + options.height = options.height || 100; + options.multisample = options.multisample !== undefined ? options.multisample : exports.MSAA_QUALITY.NONE; + _this = _super.call(this, null, options) || this; + // Set defaults + _this.mipmap = exports.MIPMAP_MODES.OFF; + _this.valid = true; + _this.clearColor = [0, 0, 0, 0]; + _this.framebuffer = new Framebuffer(_this.realWidth, _this.realHeight) + .addColorTexture(0, _this); + _this.framebuffer.multisample = options.multisample; + // TODO - could this be added the systems? + _this.maskStack = []; + _this.filterStack = [{}]; + return _this; + } + /** + * Resizes the BaseRenderTexture. + * @param desiredWidth - The desired width to resize to. + * @param desiredHeight - The desired height to resize to. + */ + BaseRenderTexture.prototype.resize = function (desiredWidth, desiredHeight) { + this.framebuffer.resize(desiredWidth * this.resolution, desiredHeight * this.resolution); + this.setRealSize(this.framebuffer.width, this.framebuffer.height); + }; + /** + * Frees the texture and framebuffer from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * @fires PIXI.BaseTexture#dispose + */ + BaseRenderTexture.prototype.dispose = function () { + this.framebuffer.dispose(); + _super.prototype.dispose.call(this); + }; + /** Destroys this texture. */ + BaseRenderTexture.prototype.destroy = function () { + _super.prototype.destroy.call(this); + this.framebuffer.destroyDepthTexture(); + this.framebuffer = null; + }; + return BaseRenderTexture; + }(BaseTexture)); - this.shader.destroy(); + /** + * Stores a texture's frame in UV coordinates, in + * which everything lies in the rectangle `[(0,0), (1,0), + * (1,1), (0,1)]`. + * + * | Corner | Coordinates | + * |--------------|-------------| + * | Top-Left | `(x0,y0)` | + * | Top-Right | `(x1,y1)` | + * | Bottom-Right | `(x2,y2)` | + * | Bottom-Left | `(x3,y3)` | + * @protected + * @memberof PIXI + */ + var TextureUvs = /** @class */ (function () { + function TextureUvs() { + this.x0 = 0; + this.y0 = 0; + this.x1 = 1; + this.y1 = 0; + this.x2 = 1; + this.y2 = 1; + this.x3 = 0; + this.y3 = 1; + this.uvsFloat32 = new Float32Array(8); + } + /** + * Sets the texture Uvs based on the given frame information. + * @protected + * @param frame - The frame of the texture + * @param baseFrame - The base frame of the texture + * @param rotate - Rotation of frame, see {@link PIXI.groupD8} + */ + TextureUvs.prototype.set = function (frame, baseFrame, rotate) { + var tw = baseFrame.width; + var th = baseFrame.height; + if (rotate) { + // width and height div 2 div baseFrame size + var w2 = frame.width / 2 / tw; + var h2 = frame.height / 2 / th; + // coordinates of center + var cX = (frame.x / tw) + w2; + var cY = (frame.y / th) + h2; + rotate = groupD8.add(rotate, groupD8.NW); // NW is top-left corner + this.x0 = cX + (w2 * groupD8.uX(rotate)); + this.y0 = cY + (h2 * groupD8.uY(rotate)); + rotate = groupD8.add(rotate, 2); // rotate 90 degrees clockwise + this.x1 = cX + (w2 * groupD8.uX(rotate)); + this.y1 = cY + (h2 * groupD8.uY(rotate)); + rotate = groupD8.add(rotate, 2); + this.x2 = cX + (w2 * groupD8.uX(rotate)); + this.y2 = cY + (h2 * groupD8.uY(rotate)); + rotate = groupD8.add(rotate, 2); + this.x3 = cX + (w2 * groupD8.uX(rotate)); + this.y3 = cY + (h2 * groupD8.uY(rotate)); + } + else { + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + this.uvsFloat32[0] = this.x0; + this.uvsFloat32[1] = this.y0; + this.uvsFloat32[2] = this.x1; + this.uvsFloat32[3] = this.y1; + this.uvsFloat32[4] = this.x2; + this.uvsFloat32[5] = this.y2; + this.uvsFloat32[6] = this.x3; + this.uvsFloat32[7] = this.y3; + }; + TextureUvs.prototype.toString = function () { + return "[@pixi/core:TextureUvs " + + ("x0=" + this.x0 + " y0=" + this.y0 + " ") + + ("x1=" + this.x1 + " y1=" + this.y1 + " x2=" + this.x2 + " ") + + ("y2=" + this.y2 + " x3=" + this.x3 + " y3=" + this.y3) + + "]"; + }; + return TextureUvs; + }()); + + var DEFAULT_UVS = new TextureUvs(); + /** + * Used to remove listeners from WHITE and EMPTY Textures + * @ignore + */ + function removeAllHandlers(tex) { + tex.destroy = function _emptyDestroy() { }; + tex.on = function _emptyOn() { }; + tex.once = function _emptyOnce() { }; + tex.emit = function _emptyEmit() { }; + } + /** + * A texture stores the information that represents an image or part of an image. + * + * It cannot be added to the display list directly; instead use it as the texture for a Sprite. + * If no frame is provided for a texture, then the whole image is used. + * + * You can directly create a texture from an image and then reuse it multiple times like this : + * + * ```js + * let texture = PIXI.Texture.from('assets/image.png'); + * let sprite1 = new PIXI.Sprite(texture); + * let sprite2 = new PIXI.Sprite(texture); + * ``` + * + * If you didnt pass the texture frame to constructor, it enables `noFrame` mode: + * it subscribes on baseTexture events, it automatically resizes at the same time as baseTexture. + * + * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. + * You can check for this by checking the sprite's _textureID property. + * ```js + * var texture = PIXI.Texture.from('assets/image.svg'); + * var sprite1 = new PIXI.Sprite(texture); + * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file + * ``` + * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. + * @memberof PIXI + * @typeParam R - The BaseTexture's Resource type. + */ + var Texture = /** @class */ (function (_super) { + __extends$i(Texture, _super); + /** + * @param baseTexture - The base texture source to create the texture from + * @param frame - The rectangle frame of the texture to show + * @param orig - The area of original texture + * @param trim - Trimmed rectangle of original texture + * @param rotate - indicates how the texture was rotated by texture packer. See {@link PIXI.groupD8} + * @param anchor - Default anchor point used for sprite placement / rotation + */ + function Texture(baseTexture, frame, orig, trim, rotate, anchor) { + var _this = _super.call(this) || this; + _this.noFrame = false; + if (!frame) { + _this.noFrame = true; + frame = new Rectangle(0, 0, 1, 1); + } + if (baseTexture instanceof Texture) { + baseTexture = baseTexture.baseTexture; + } + _this.baseTexture = baseTexture; + _this._frame = frame; + _this.trim = trim; + _this.valid = false; + _this._uvs = DEFAULT_UVS; + _this.uvMatrix = null; + _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); + _this._rotate = Number(rotate || 0); + if (rotate === true) { + // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures + _this._rotate = 2; + } + else if (_this._rotate % 2 !== 0) { + throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); + } + _this.defaultAnchor = anchor ? new Point(anchor.x, anchor.y) : new Point(0, 0); + _this._updateID = 0; + _this.textureCacheIds = []; + if (!baseTexture.valid) { + baseTexture.once('loaded', _this.onBaseTextureUpdated, _this); + } + else if (_this.noFrame) { + // if there is no frame we should monitor for any base texture changes.. + if (baseTexture.valid) { + _this.onBaseTextureUpdated(baseTexture); + } + } + else { + _this.frame = frame; + } + if (_this.noFrame) { + baseTexture.on('update', _this.onBaseTextureUpdated, _this); + } + return _this; + } + /** + * Updates this texture on the gpu. + * + * Calls the TextureResource update. + * + * If you adjusted `frame` manually, please call `updateUvs()` instead. + */ + Texture.prototype.update = function () { + if (this.baseTexture.resource) { + this.baseTexture.resource.update(); + } + }; + /** + * Called when the base texture is updated + * @protected + * @param baseTexture - The base texture. + */ + Texture.prototype.onBaseTextureUpdated = function (baseTexture) { + if (this.noFrame) { + if (!this.baseTexture.valid) { + return; + } + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + this.valid = true; + this.updateUvs(); + } + else { + // TODO this code looks confusing.. boo to abusing getters and setters! + // if user gave us frame that has bigger size than resized texture it can be a problem + this.frame = this._frame; + } + this.emit('update', this); + }; + /** + * Destroys this texture + * @param [destroyBase=false] - Whether to destroy the base texture as well + */ + Texture.prototype.destroy = function (destroyBase) { + if (this.baseTexture) { + if (destroyBase) { + var resource = this.baseTexture.resource; + // delete the texture if it exists in the texture cache.. + // this only needs to be removed if the base texture is actually destroyed too.. + if (resource && resource.url && TextureCache[resource.url]) { + Texture.removeFromCache(resource.url); + } + this.baseTexture.destroy(); + } + this.baseTexture.off('loaded', this.onBaseTextureUpdated, this); + this.baseTexture.off('update', this.onBaseTextureUpdated, this); + this.baseTexture = null; + } + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + this.valid = false; + Texture.removeFromCache(this); + this.textureCacheIds = null; + }; + /** + * Creates a new texture object that acts the same as this one. + * @returns - The new texture + */ + Texture.prototype.clone = function () { + var clonedFrame = this._frame.clone(); + var clonedOrig = this._frame === this.orig ? clonedFrame : this.orig.clone(); + var clonedTexture = new Texture(this.baseTexture, !this.noFrame && clonedFrame, clonedOrig, this.trim && this.trim.clone(), this.rotate, this.defaultAnchor); + if (this.noFrame) { + clonedTexture._frame = clonedFrame; + } + return clonedTexture; + }; + /** + * Updates the internal WebGL UV cache. Use it after you change `frame` or `trim` of the texture. + * Call it after changing the frame + */ + Texture.prototype.updateUvs = function () { + if (this._uvs === DEFAULT_UVS) { + this._uvs = new TextureUvs(); + } + this._uvs.set(this._frame, this.baseTexture, this.rotate); + this._updateID++; + }; + /** + * Helper function that creates a new Texture based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * @param {string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} source - + * Source or array of sources to create texture from + * @param options - See {@link PIXI.BaseTexture}'s constructor for options. + * @param {string} [options.pixiIdPrefix=pixiid] - If a source has no id, this is the prefix of the generated id + * @param {boolean} [strict] - Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}. + * @returns {PIXI.Texture} The newly created texture + */ + Texture.from = function (source, options, strict) { + if (options === void 0) { options = {}; } + if (strict === void 0) { strict = settings.STRICT_TEXTURE_CACHE; } + var isFrame = typeof source === 'string'; + var cacheId = null; + if (isFrame) { + cacheId = source; + } + else if (source instanceof BaseTexture) { + if (!source.cacheId) { + var prefix = (options && options.pixiIdPrefix) || 'pixiid'; + source.cacheId = prefix + "-" + uid(); + BaseTexture.addToCache(source, source.cacheId); + } + cacheId = source.cacheId; + } + else { + if (!source._pixiId) { + var prefix = (options && options.pixiIdPrefix) || 'pixiid'; + source._pixiId = prefix + "_" + uid(); + } + cacheId = source._pixiId; + } + var texture = TextureCache[cacheId]; + // Strict-mode rejects invalid cacheIds + if (isFrame && strict && !texture) { + throw new Error("The cacheId \"" + cacheId + "\" does not exist in TextureCache."); + } + if (!texture && !(source instanceof BaseTexture)) { + if (!options.resolution) { + options.resolution = getResolutionOfUrl(source); + } + texture = new Texture(new BaseTexture(source, options)); + texture.baseTexture.cacheId = cacheId; + BaseTexture.addToCache(texture.baseTexture, cacheId); + Texture.addToCache(texture, cacheId); + } + else if (!texture && (source instanceof BaseTexture)) { + texture = new Texture(source); + Texture.addToCache(texture, cacheId); + } + // lets assume its a base texture! + return texture; + }; + /** + * Useful for loading textures via URLs. Use instead of `Texture.from` because + * it does a better job of handling failed URLs more effectively. This also ignores + * `PIXI.settings.STRICT_TEXTURE_CACHE`. Works for Videos, SVGs, Images. + * @param url - The remote URL or array of URLs to load. + * @param options - Optional options to include + * @returns - A Promise that resolves to a Texture. + */ + Texture.fromURL = function (url, options) { + var resourceOptions = Object.assign({ autoLoad: false }, options === null || options === void 0 ? void 0 : options.resourceOptions); + var texture = Texture.from(url, Object.assign({ resourceOptions: resourceOptions }, options), false); + var resource = texture.baseTexture.resource; + // The texture was already loaded + if (texture.baseTexture.valid) { + return Promise.resolve(texture); + } + // Manually load the texture, this should allow users to handle load errors + return resource.load().then(function () { return Promise.resolve(texture); }); + }; + /** + * Create a new Texture with a BufferResource from a Float32Array. + * RGBA values are floats from 0 to 1. + * @param {Float32Array|Uint8Array} buffer - The optional array to use, if no data + * is provided, a new Float32Array is created. + * @param width - Width of the resource + * @param height - Height of the resource + * @param options - See {@link PIXI.BaseTexture}'s constructor for options. + * @returns - The resulting new BaseTexture + */ + Texture.fromBuffer = function (buffer, width, height, options) { + return new Texture(BaseTexture.fromBuffer(buffer, width, height, options)); + }; + /** + * Create a texture from a source and add to the cache. + * @param {HTMLImageElement|HTMLCanvasElement|string} source - The input source. + * @param imageUrl - File name of texture, for cache and resolving resolution. + * @param name - Human readable name for the texture cache. If no name is + * specified, only `imageUrl` will be used as the cache ID. + * @param options + * @returns - Output texture + */ + Texture.fromLoader = function (source, imageUrl, name, options) { + var baseTexture = new BaseTexture(source, Object.assign({ + scaleMode: settings.SCALE_MODE, + resolution: getResolutionOfUrl(imageUrl), + }, options)); + var resource = baseTexture.resource; + if (resource instanceof ImageResource) { + resource.url = imageUrl; + } + var texture = new Texture(baseTexture); + // No name, use imageUrl instead + if (!name) { + name = imageUrl; + } + // lets also add the frame to pixi's global cache for 'fromLoader' function + BaseTexture.addToCache(texture.baseTexture, name); + Texture.addToCache(texture, name); + // also add references by url if they are different. + if (name !== imageUrl) { + BaseTexture.addToCache(texture.baseTexture, imageUrl); + Texture.addToCache(texture, imageUrl); + } + // Generally images are valid right away + if (texture.baseTexture.valid) { + return Promise.resolve(texture); + } + // SVG assets need to be parsed async, let's wait + return new Promise(function (resolve) { + texture.baseTexture.once('loaded', function () { return resolve(texture); }); + }); + }; + /** + * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object. + * @param texture - The Texture to add to the cache. + * @param id - The id that the Texture will be stored against. + */ + Texture.addToCache = function (texture, id) { + if (id) { + if (texture.textureCacheIds.indexOf(id) === -1) { + texture.textureCacheIds.push(id); + } + if (TextureCache[id]) { + // eslint-disable-next-line no-console + console.warn("Texture added to the cache with an id [" + id + "] that already had an entry"); + } + TextureCache[id] = texture; + } + }; + /** + * Remove a Texture from the global TextureCache. + * @param texture - id of a Texture to be removed, or a Texture instance itself + * @returns - The Texture that was removed + */ + Texture.removeFromCache = function (texture) { + if (typeof texture === 'string') { + var textureFromCache = TextureCache[texture]; + if (textureFromCache) { + var index = textureFromCache.textureCacheIds.indexOf(texture); + if (index > -1) { + textureFromCache.textureCacheIds.splice(index, 1); + } + delete TextureCache[texture]; + return textureFromCache; + } + } + else if (texture && texture.textureCacheIds) { + for (var i = 0; i < texture.textureCacheIds.length; ++i) { + // Check that texture matches the one being passed in before deleting it from the cache. + if (TextureCache[texture.textureCacheIds[i]] === texture) { + delete TextureCache[texture.textureCacheIds[i]]; + } + } + texture.textureCacheIds.length = 0; + return texture; + } + return null; + }; + Object.defineProperty(Texture.prototype, "resolution", { + /** + * Returns resolution of baseTexture + * @readonly + */ + get: function () { + return this.baseTexture.resolution; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Texture.prototype, "frame", { + /** + * The frame specifies the region of the base texture that this texture uses. + * Please call `updateUvs()` after you change coordinates of `frame` manually. + */ + get: function () { + return this._frame; + }, + set: function (frame) { + this._frame = frame; + this.noFrame = false; + var x = frame.x, y = frame.y, width = frame.width, height = frame.height; + var xNotFit = x + width > this.baseTexture.width; + var yNotFit = y + height > this.baseTexture.height; + if (xNotFit || yNotFit) { + var relationship = xNotFit && yNotFit ? 'and' : 'or'; + var errorX = "X: " + x + " + " + width + " = " + (x + width) + " > " + this.baseTexture.width; + var errorY = "Y: " + y + " + " + height + " = " + (y + height) + " > " + this.baseTexture.height; + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' + + (errorX + " " + relationship + " " + errorY)); + } + this.valid = width && height && this.baseTexture.valid; + if (!this.trim && !this.rotate) { + this.orig = frame; + } + if (this.valid) { + this.updateUvs(); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Texture.prototype, "rotate", { + /** + * Indicates whether the texture is rotated inside the atlas + * set to 2 to compensate for texture packer rotation + * set to 6 to compensate for spine packer rotation + * can be used to rotate or mirror sprites + * See {@link PIXI.groupD8} for explanation + */ + get: function () { + return this._rotate; + }, + set: function (rotate) { + this._rotate = rotate; + if (this.valid) { + this.updateUvs(); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Texture.prototype, "width", { + /** The width of the Texture in pixels. */ + get: function () { + return this.orig.width; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Texture.prototype, "height", { + /** The height of the Texture in pixels. */ + get: function () { + return this.orig.height; + }, + enumerable: false, + configurable: true + }); + /** Utility function for BaseTexture|Texture cast. */ + Texture.prototype.castToBaseTexture = function () { + return this.baseTexture; + }; + Object.defineProperty(Texture, "EMPTY", { + /** An empty texture, used often to not have to create multiple empty textures. Can not be destroyed. */ + get: function () { + if (!Texture._EMPTY) { + Texture._EMPTY = new Texture(new BaseTexture()); + removeAllHandlers(Texture._EMPTY); + removeAllHandlers(Texture._EMPTY.baseTexture); + } + return Texture._EMPTY; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Texture, "WHITE", { + /** A white texture of 16x16 size, used for graphics and other things Can not be destroyed. */ + get: function () { + if (!Texture._WHITE) { + var canvas = settings.ADAPTER.createCanvas(16, 16); + var context = canvas.getContext('2d'); + canvas.width = 16; + canvas.height = 16; + context.fillStyle = 'white'; + context.fillRect(0, 0, 16, 16); + Texture._WHITE = new Texture(BaseTexture.from(canvas)); + removeAllHandlers(Texture._WHITE); + removeAllHandlers(Texture._WHITE.baseTexture); + } + return Texture._WHITE; + }, + enumerable: false, + configurable: true + }); + return Texture; + }(eventemitter3)); - this.indices = null; - this.tempMatrix = null; - }; + /** + * A RenderTexture is a special texture that allows any PixiJS display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * __Hint-2__: The actual memory allocation will happen on first render. + * You shouldn't create renderTextures each frame just to delete them after, try to reuse them. + * + * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(); + * let renderTexture = PIXI.RenderTexture.create({ width: 800, height: 600 }); + * let sprite = PIXI.Sprite.from("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, {renderTexture}); + * ``` + * Note that you should not create a new renderer, but reuse the same one as the rest of the application. + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let renderTexture = new PIXI.RenderTexture.create({ width: 100, height: 100 }); + * + * renderer.render(sprite, {renderTexture}); // Renders to center of RenderTexture + * ``` + * @memberof PIXI + */ + var RenderTexture = /** @class */ (function (_super) { + __extends$i(RenderTexture, _super); + /** + * @param baseRenderTexture - The base texture object that this texture uses. + * @param frame - The rectangle frame of the texture to show. + */ + function RenderTexture(baseRenderTexture, frame) { + var _this = _super.call(this, baseRenderTexture, frame) || this; + _this.valid = true; + _this.filterFrame = null; + _this.filterPoolKey = null; + _this.updateUvs(); + return _this; + } + Object.defineProperty(RenderTexture.prototype, "framebuffer", { + /** + * Shortcut to `this.baseTexture.framebuffer`, saves baseTexture cast. + * @readonly + */ + get: function () { + return this.baseTexture.framebuffer; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(RenderTexture.prototype, "multisample", { + /** + * Shortcut to `this.framebuffer.multisample`. + * @default PIXI.MSAA_QUALITY.NONE + */ + get: function () { + return this.framebuffer.multisample; + }, + set: function (value) { + this.framebuffer.multisample = value; + }, + enumerable: false, + configurable: true + }); + /** + * Resizes the RenderTexture. + * @param desiredWidth - The desired width to resize to. + * @param desiredHeight - The desired height to resize to. + * @param resizeBaseTexture - Should the baseTexture.width and height values be resized as well? + */ + RenderTexture.prototype.resize = function (desiredWidth, desiredHeight, resizeBaseTexture) { + if (resizeBaseTexture === void 0) { resizeBaseTexture = true; } + var resolution = this.baseTexture.resolution; + var width = Math.round(desiredWidth * resolution) / resolution; + var height = Math.round(desiredHeight * resolution) / resolution; + // TODO - could be not required.. + this.valid = (width > 0 && height > 0); + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + if (resizeBaseTexture) { + this.baseTexture.resize(width, height); + } + this.updateUvs(); + }; + /** + * Changes the resolution of baseTexture, but does not change framebuffer size. + * @param resolution - The new resolution to apply to RenderTexture + */ + RenderTexture.prototype.setResolution = function (resolution) { + var baseTexture = this.baseTexture; + if (baseTexture.resolution === resolution) { + return; + } + baseTexture.setResolution(resolution); + this.resize(baseTexture.width, baseTexture.height, false); + }; + RenderTexture.create = function (options) { + var arguments$1 = arguments; + + var rest = []; + for (var _i = 1; _i < arguments.length; _i++) { + rest[_i - 1] = arguments$1[_i]; + } + // @deprecated fallback, old-style: create(width, height, scaleMode, resolution) + if (typeof options === 'number') { + deprecation('6.0.0', 'Arguments (width, height, scaleMode, resolution) have been deprecated.'); + /* eslint-disable prefer-rest-params */ + options = { + width: options, + height: rest[0], + scaleMode: rest[1], + resolution: rest[2], + }; + /* eslint-enable prefer-rest-params */ + } + return new RenderTexture(new BaseRenderTexture(options)); + }; + return RenderTexture; + }(Texture)); - return ParticleRenderer; -}(core.ObjectRenderer); + /** + * Texture pool, used by FilterSystem and plugins. + * + * Stores collection of temporary pow2 or screen-sized renderTextures + * + * If you use custom RenderTexturePool for your filters, you can use methods + * `getFilterTexture` and `returnFilterTexture` same as in + * @memberof PIXI + */ + var RenderTexturePool = /** @class */ (function () { + /** + * @param textureOptions - options that will be passed to BaseRenderTexture constructor + * @param {PIXI.SCALE_MODES} [textureOptions.scaleMode] - See {@link PIXI.SCALE_MODES} for possible values. + */ + function RenderTexturePool(textureOptions) { + this.texturePool = {}; + this.textureOptions = textureOptions || {}; + this.enableFullScreen = false; + this._pixelsWidth = 0; + this._pixelsHeight = 0; + } + /** + * Creates texture with params that were specified in pool constructor. + * @param realWidth - Width of texture in pixels. + * @param realHeight - Height of texture in pixels. + * @param multisample - Number of samples of the framebuffer. + */ + RenderTexturePool.prototype.createTexture = function (realWidth, realHeight, multisample) { + if (multisample === void 0) { multisample = exports.MSAA_QUALITY.NONE; } + var baseRenderTexture = new BaseRenderTexture(Object.assign({ + width: realWidth, + height: realHeight, + resolution: 1, + multisample: multisample, + }, this.textureOptions)); + return new RenderTexture(baseRenderTexture); + }; + /** + * Gets a Power-of-Two render texture or fullScreen texture + * @param minWidth - The minimum width of the render texture. + * @param minHeight - The minimum height of the render texture. + * @param resolution - The resolution of the render texture. + * @param multisample - Number of samples of the render texture. + * @returns The new render texture. + */ + RenderTexturePool.prototype.getOptimalTexture = function (minWidth, minHeight, resolution, multisample) { + if (resolution === void 0) { resolution = 1; } + if (multisample === void 0) { multisample = exports.MSAA_QUALITY.NONE; } + var key; + minWidth = Math.ceil((minWidth * resolution) - 1e-6); + minHeight = Math.ceil((minHeight * resolution) - 1e-6); + if (!this.enableFullScreen || minWidth !== this._pixelsWidth || minHeight !== this._pixelsHeight) { + minWidth = nextPow2(minWidth); + minHeight = nextPow2(minHeight); + key = (((minWidth & 0xFFFF) << 16) | (minHeight & 0xFFFF)) >>> 0; + if (multisample > 1) { + key += multisample * 0x100000000; + } + } + else { + key = multisample > 1 ? -multisample : -1; + } + if (!this.texturePool[key]) { + this.texturePool[key] = []; + } + var renderTexture = this.texturePool[key].pop(); + if (!renderTexture) { + renderTexture = this.createTexture(minWidth, minHeight, multisample); + } + renderTexture.filterPoolKey = key; + renderTexture.setResolution(resolution); + return renderTexture; + }; + /** + * Gets extra texture of the same size as input renderTexture + * + * `getFilterTexture(input, 0.5)` or `getFilterTexture(0.5, input)` + * @param input - renderTexture from which size and resolution will be copied + * @param resolution - override resolution of the renderTexture + * It overrides, it does not multiply + * @param multisample - number of samples of the renderTexture + */ + RenderTexturePool.prototype.getFilterTexture = function (input, resolution, multisample) { + var filterTexture = this.getOptimalTexture(input.width, input.height, resolution || input.resolution, multisample || exports.MSAA_QUALITY.NONE); + filterTexture.filterFrame = input.filterFrame; + return filterTexture; + }; + /** + * Place a render texture back into the pool. + * @param renderTexture - The renderTexture to free + */ + RenderTexturePool.prototype.returnTexture = function (renderTexture) { + var key = renderTexture.filterPoolKey; + renderTexture.filterFrame = null; + this.texturePool[key].push(renderTexture); + }; + /** + * Alias for returnTexture, to be compliant with FilterSystem interface. + * @param renderTexture - The renderTexture to free + */ + RenderTexturePool.prototype.returnFilterTexture = function (renderTexture) { + this.returnTexture(renderTexture); + }; + /** + * Clears the pool. + * @param destroyTextures - Destroy all stored textures. + */ + RenderTexturePool.prototype.clear = function (destroyTextures) { + destroyTextures = destroyTextures !== false; + if (destroyTextures) { + for (var i in this.texturePool) { + var textures = this.texturePool[i]; + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + } + } + this.texturePool = {}; + }; + /** + * If screen size was changed, drops all screen-sized textures, + * sets new screen size, sets `enableFullScreen` to true + * + * Size is measured in pixels, `renderer.view` can be passed here, not `renderer.screen` + * @param size - Initial size of screen. + */ + RenderTexturePool.prototype.setScreenSize = function (size) { + if (size.width === this._pixelsWidth + && size.height === this._pixelsHeight) { + return; + } + this.enableFullScreen = size.width > 0 && size.height > 0; + for (var i in this.texturePool) { + if (!(Number(i) < 0)) { + continue; + } + var textures = this.texturePool[i]; + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + this.texturePool[i] = []; + } + this._pixelsWidth = size.width; + this._pixelsHeight = size.height; + }; + /** + * Key that is used to store fullscreen renderTextures in a pool + * @constant + */ + RenderTexturePool.SCREEN_KEY = -1; + return RenderTexturePool; + }()); -exports.default = ParticleRenderer; + /* eslint-disable max-len */ + /** + * Holds the information for a single attribute structure required to render geometry. + * + * This does not contain the actual data, but instead has a buffer id that maps to a {@link PIXI.Buffer} + * This can include anything from positions, uvs, normals, colors etc. + * @memberof PIXI + */ + var Attribute = /** @class */ (function () { + /** + * @param buffer - the id of the buffer that this attribute will look for + * @param size - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2. + * @param normalized - should the data be normalized. + * @param {PIXI.TYPES} [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available + * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data) + * @param [start=0] - How far into the array to start reading values (used for interleaving data) + * @param [instance=false] - Whether the geometry is instanced. + */ + function Attribute(buffer, size, normalized, type, stride, start, instance) { + if (size === void 0) { size = 0; } + if (normalized === void 0) { normalized = false; } + if (type === void 0) { type = exports.TYPES.FLOAT; } + this.buffer = buffer; + this.size = size; + this.normalized = normalized; + this.type = type; + this.stride = stride; + this.start = start; + this.instance = instance; + } + /** Destroys the Attribute. */ + Attribute.prototype.destroy = function () { + this.buffer = null; + }; + /** + * Helper function that creates an Attribute based on the information provided + * @param buffer - the id of the buffer that this attribute will look for + * @param [size=0] - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2 + * @param [normalized=false] - should the data be normalized. + * @param [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available + * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data) + * @returns - A new {@link PIXI.Attribute} based on the information provided + */ + Attribute.from = function (buffer, size, normalized, type, stride) { + return new Attribute(buffer, size, normalized, type, stride); + }; + return Attribute; + }()); + var UID$4 = 0; + /** + * A wrapper for data so that it can be used and uploaded by WebGL + * @memberof PIXI + */ + var Buffer = /** @class */ (function () { + /** + * @param {PIXI.IArrayBuffer} data - the data to store in the buffer. + * @param _static - `true` for static buffer + * @param index - `true` for index buffer + */ + function Buffer(data, _static, index) { + if (_static === void 0) { _static = true; } + if (index === void 0) { index = false; } + this.data = (data || new Float32Array(1)); + this._glBuffers = {}; + this._updateID = 0; + this.index = index; + this.static = _static; + this.id = UID$4++; + this.disposeRunner = new Runner('disposeBuffer'); + } + // TODO could explore flagging only a partial upload? + /** + * Flags this buffer as requiring an upload to the GPU. + * @param {PIXI.IArrayBuffer|number[]} [data] - the data to update in the buffer. + */ + Buffer.prototype.update = function (data) { + if (data instanceof Array) { + data = new Float32Array(data); + } + this.data = data || this.data; + this._updateID++; + }; + /** Disposes WebGL resources that are connected to this geometry. */ + Buffer.prototype.dispose = function () { + this.disposeRunner.emit(this, false); + }; + /** Destroys the buffer. */ + Buffer.prototype.destroy = function () { + this.dispose(); + this.data = null; + }; + Object.defineProperty(Buffer.prototype, "index", { + get: function () { + return this.type === exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; + }, + /** + * Flags whether this is an index buffer. + * + * Index buffers are of type `ELEMENT_ARRAY_BUFFER`. Note that setting this property to false will make + * the buffer of type `ARRAY_BUFFER`. + * + * For backwards compatibility. + */ + set: function (value) { + this.type = value ? exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER : exports.BUFFER_TYPE.ARRAY_BUFFER; + }, + enumerable: false, + configurable: true + }); + /** + * Helper function that creates a buffer based on an array or TypedArray + * @param {ArrayBufferView | number[]} data - the TypedArray that the buffer will store. If this is a regular Array it will be converted to a Float32Array. + * @returns - A new Buffer based on the data provided. + */ + Buffer.from = function (data) { + if (data instanceof Array) { + data = new Float32Array(data); + } + return new Buffer(data); + }; + return Buffer; + }()); + + /* eslint-disable object-shorthand */ + var map$1 = { + Float32Array: Float32Array, + Uint32Array: Uint32Array, + Int32Array: Int32Array, + Uint8Array: Uint8Array, + }; + function interleaveTypedArrays(arrays, sizes) { + var outSize = 0; + var stride = 0; + var views = {}; + for (var i = 0; i < arrays.length; i++) { + stride += sizes[i]; + outSize += arrays[i].length; + } + var buffer = new ArrayBuffer(outSize * 4); + var out = null; + var littleOffset = 0; + for (var i = 0; i < arrays.length; i++) { + var size = sizes[i]; + var array = arrays[i]; + var type = getBufferType(array); + if (!views[type]) { + views[type] = new map$1[type](buffer); + } + out = views[type]; + for (var j = 0; j < array.length; j++) { + var indexStart = ((j / size | 0) * stride) + littleOffset; + var index = j % size; + out[indexStart + index] = array[j]; + } + littleOffset += size; + } + return new Float32Array(buffer); + } -core.WebGLRenderer.registerPlugin('particle', ParticleRenderer); + var byteSizeMap$1 = { 5126: 4, 5123: 2, 5121: 1 }; + var UID$3 = 0; + /* eslint-disable object-shorthand */ + var map = { + Float32Array: Float32Array, + Uint32Array: Uint32Array, + Int32Array: Int32Array, + Uint8Array: Uint8Array, + Uint16Array: Uint16Array, + }; + /* eslint-disable max-len */ + /** + * The Geometry represents a model. It consists of two components: + * - GeometryStyle - The structure of the model such as the attributes layout + * - GeometryData - the data of the model - this consists of buffers. + * This can include anything from positions, uvs, normals, colors etc. + * + * Geometry can be defined without passing in a style or data if required (thats how I prefer!) + * + * ```js + * let geometry = new PIXI.Geometry(); + * + * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2); + * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1],2) + * geometry.addIndex([0,1,2,1,3,2]) + * ``` + * @memberof PIXI + */ + var Geometry = /** @class */ (function () { + /** + * @param buffers - An array of buffers. optional. + * @param attributes - Of the geometry, optional structure of the attributes layout + */ + function Geometry(buffers, attributes) { + if (buffers === void 0) { buffers = []; } + if (attributes === void 0) { attributes = {}; } + this.buffers = buffers; + this.indexBuffer = null; + this.attributes = attributes; + this.glVertexArrayObjects = {}; + this.id = UID$3++; + this.instanced = false; + this.instanceCount = 1; + this.disposeRunner = new Runner('disposeGeometry'); + this.refCount = 0; + } + /** + * + * Adds an attribute to the geometry + * Note: `stride` and `start` should be `undefined` if you dont know them, not 0! + * @param id - the name of the attribute (matching up to a shader) + * @param {PIXI.Buffer|number[]} buffer - the buffer that holds the data of the attribute . You can also provide an Array and a buffer will be created from it. + * @param size - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2 + * @param normalized - should the data be normalized. + * @param [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {PIXI.TYPES} to see the ones available + * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data) + * @param [start=0] - How far into the array to start reading values (used for interleaving data) + * @param instance - Instancing flag + * @returns - Returns self, useful for chaining. + */ + Geometry.prototype.addAttribute = function (id, buffer, size, normalized, type, stride, start, instance) { + if (size === void 0) { size = 0; } + if (normalized === void 0) { normalized = false; } + if (instance === void 0) { instance = false; } + if (!buffer) { + throw new Error('You must pass a buffer when creating an attribute'); + } + // check if this is a buffer! + if (!(buffer instanceof Buffer)) { + // its an array! + if (buffer instanceof Array) { + buffer = new Float32Array(buffer); + } + buffer = new Buffer(buffer); + } + var ids = id.split('|'); + if (ids.length > 1) { + for (var i = 0; i < ids.length; i++) { + this.addAttribute(ids[i], buffer, size, normalized, type); + } + return this; + } + var bufferIndex = this.buffers.indexOf(buffer); + if (bufferIndex === -1) { + this.buffers.push(buffer); + bufferIndex = this.buffers.length - 1; + } + this.attributes[id] = new Attribute(bufferIndex, size, normalized, type, stride, start, instance); + // assuming that if there is instanced data then this will be drawn with instancing! + this.instanced = this.instanced || instance; + return this; + }; + /** + * Returns the requested attribute. + * @param id - The name of the attribute required + * @returns - The attribute requested. + */ + Geometry.prototype.getAttribute = function (id) { + return this.attributes[id]; + }; + /** + * Returns the requested buffer. + * @param id - The name of the buffer required. + * @returns - The buffer requested. + */ + Geometry.prototype.getBuffer = function (id) { + return this.buffers[this.getAttribute(id).buffer]; + }; + /** + * + * Adds an index buffer to the geometry + * The index buffer contains integers, three for each triangle in the geometry, which reference the various attribute buffers (position, colour, UV coordinates, other UV coordinates, normal, …). There is only ONE index buffer. + * @param {PIXI.Buffer|number[]} [buffer] - The buffer that holds the data of the index buffer. You can also provide an Array and a buffer will be created from it. + * @returns - Returns self, useful for chaining. + */ + Geometry.prototype.addIndex = function (buffer) { + if (!(buffer instanceof Buffer)) { + // its an array! + if (buffer instanceof Array) { + buffer = new Uint16Array(buffer); + } + buffer = new Buffer(buffer); + } + buffer.type = exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; + this.indexBuffer = buffer; + if (this.buffers.indexOf(buffer) === -1) { + this.buffers.push(buffer); + } + return this; + }; + /** + * Returns the index buffer + * @returns - The index buffer. + */ + Geometry.prototype.getIndex = function () { + return this.indexBuffer; + }; + /** + * This function modifies the structure so that all current attributes become interleaved into a single buffer + * This can be useful if your model remains static as it offers a little performance boost + * @returns - Returns self, useful for chaining. + */ + Geometry.prototype.interleave = function () { + // a simple check to see if buffers are already interleaved.. + if (this.buffers.length === 1 || (this.buffers.length === 2 && this.indexBuffer)) + { return this; } + // assume already that no buffers are interleaved + var arrays = []; + var sizes = []; + var interleavedBuffer = new Buffer(); + var i; + for (i in this.attributes) { + var attribute = this.attributes[i]; + var buffer = this.buffers[attribute.buffer]; + arrays.push(buffer.data); + sizes.push((attribute.size * byteSizeMap$1[attribute.type]) / 4); + attribute.buffer = 0; + } + interleavedBuffer.data = interleaveTypedArrays(arrays, sizes); + for (i = 0; i < this.buffers.length; i++) { + if (this.buffers[i] !== this.indexBuffer) { + this.buffers[i].destroy(); + } + } + this.buffers = [interleavedBuffer]; + if (this.indexBuffer) { + this.buffers.push(this.indexBuffer); + } + return this; + }; + /** Get the size of the geometries, in vertices. */ + Geometry.prototype.getSize = function () { + for (var i in this.attributes) { + var attribute = this.attributes[i]; + var buffer = this.buffers[attribute.buffer]; + return buffer.data.length / ((attribute.stride / 4) || attribute.size); + } + return 0; + }; + /** Disposes WebGL resources that are connected to this geometry. */ + Geometry.prototype.dispose = function () { + this.disposeRunner.emit(this, false); + }; + /** Destroys the geometry. */ + Geometry.prototype.destroy = function () { + this.dispose(); + this.buffers = null; + this.indexBuffer = null; + this.attributes = null; + }; + /** + * Returns a clone of the geometry. + * @returns - A new clone of this geometry. + */ + Geometry.prototype.clone = function () { + var geometry = new Geometry(); + for (var i = 0; i < this.buffers.length; i++) { + geometry.buffers[i] = new Buffer(this.buffers[i].data.slice(0)); + } + for (var i in this.attributes) { + var attrib = this.attributes[i]; + geometry.attributes[i] = new Attribute(attrib.buffer, attrib.size, attrib.normalized, attrib.type, attrib.stride, attrib.start, attrib.instance); + } + if (this.indexBuffer) { + geometry.indexBuffer = geometry.buffers[this.buffers.indexOf(this.indexBuffer)]; + geometry.indexBuffer.type = exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; + } + return geometry; + }; + /** + * Merges an array of geometries into a new single one. + * + * Geometry attribute styles must match for this operation to work. + * @param geometries - array of geometries to merge + * @returns - Shiny new geometry! + */ + Geometry.merge = function (geometries) { + // todo add a geometry check! + // also a size check.. cant be too big!] + var geometryOut = new Geometry(); + var arrays = []; + var sizes = []; + var offsets = []; + var geometry; + // pass one.. get sizes.. + for (var i = 0; i < geometries.length; i++) { + geometry = geometries[i]; + for (var j = 0; j < geometry.buffers.length; j++) { + sizes[j] = sizes[j] || 0; + sizes[j] += geometry.buffers[j].data.length; + offsets[j] = 0; + } + } + // build the correct size arrays.. + for (var i = 0; i < geometry.buffers.length; i++) { + // TODO types! + arrays[i] = new map[getBufferType(geometry.buffers[i].data)](sizes[i]); + geometryOut.buffers[i] = new Buffer(arrays[i]); + } + // pass to set data.. + for (var i = 0; i < geometries.length; i++) { + geometry = geometries[i]; + for (var j = 0; j < geometry.buffers.length; j++) { + arrays[j].set(geometry.buffers[j].data, offsets[j]); + offsets[j] += geometry.buffers[j].data.length; + } + } + geometryOut.attributes = geometry.attributes; + if (geometry.indexBuffer) { + geometryOut.indexBuffer = geometryOut.buffers[geometry.buffers.indexOf(geometry.indexBuffer)]; + geometryOut.indexBuffer.type = exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; + var offset = 0; + var stride = 0; + var offset2 = 0; + var bufferIndexToCount = 0; + // get a buffer + for (var i = 0; i < geometry.buffers.length; i++) { + if (geometry.buffers[i] !== geometry.indexBuffer) { + bufferIndexToCount = i; + break; + } + } + // figure out the stride of one buffer.. + for (var i in geometry.attributes) { + var attribute = geometry.attributes[i]; + if ((attribute.buffer | 0) === bufferIndexToCount) { + stride += ((attribute.size * byteSizeMap$1[attribute.type]) / 4); + } + } + // time to off set all indexes.. + for (var i = 0; i < geometries.length; i++) { + var indexBufferData = geometries[i].indexBuffer.data; + for (var j = 0; j < indexBufferData.length; j++) { + geometryOut.indexBuffer.data[j + offset2] += offset; + } + offset += geometries[i].buffers[bufferIndexToCount].data.length / (stride); + offset2 += indexBufferData.length; + } + } + return geometryOut; + }; + return Geometry; + }()); -},{"../../core":65,"./ParticleBuffer":175,"./ParticleShader":177}],177:[function(require,module,exports){ -'use strict'; + /** + * Helper class to create a quad + * @memberof PIXI + */ + var Quad = /** @class */ (function (_super) { + __extends$i(Quad, _super); + function Quad() { + var _this = _super.call(this) || this; + _this.addAttribute('aVertexPosition', new Float32Array([ + 0, 0, + 1, 0, + 1, 1, + 0, 1 ])) + .addIndex([0, 1, 3, 2]); + return _this; + } + return Quad; + }(Geometry)); -exports.__esModule = true; + /** + * Helper class to create a quad with uvs like in v4 + * @memberof PIXI + */ + var QuadUv = /** @class */ (function (_super) { + __extends$i(QuadUv, _super); + function QuadUv() { + var _this = _super.call(this) || this; + _this.vertices = new Float32Array([ + -1, -1, + 1, -1, + 1, 1, + -1, 1 ]); + _this.uvs = new Float32Array([ + 0, 0, + 1, 0, + 1, 1, + 0, 1 ]); + _this.vertexBuffer = new Buffer(_this.vertices); + _this.uvBuffer = new Buffer(_this.uvs); + _this.addAttribute('aVertexPosition', _this.vertexBuffer) + .addAttribute('aTextureCoord', _this.uvBuffer) + .addIndex([0, 1, 2, 0, 2, 3]); + return _this; + } + /** + * Maps two Rectangle to the quad. + * @param targetTextureFrame - The first rectangle + * @param destinationFrame - The second rectangle + * @returns - Returns itself. + */ + QuadUv.prototype.map = function (targetTextureFrame, destinationFrame) { + var x = 0; // destinationFrame.x / targetTextureFrame.width; + var y = 0; // destinationFrame.y / targetTextureFrame.height; + this.uvs[0] = x; + this.uvs[1] = y; + this.uvs[2] = x + (destinationFrame.width / targetTextureFrame.width); + this.uvs[3] = y; + this.uvs[4] = x + (destinationFrame.width / targetTextureFrame.width); + this.uvs[5] = y + (destinationFrame.height / targetTextureFrame.height); + this.uvs[6] = x; + this.uvs[7] = y + (destinationFrame.height / targetTextureFrame.height); + x = destinationFrame.x; + y = destinationFrame.y; + this.vertices[0] = x; + this.vertices[1] = y; + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + this.invalidate(); + return this; + }; + /** + * Legacy upload method, just marks buffers dirty. + * @returns - Returns itself. + */ + QuadUv.prototype.invalidate = function () { + this.vertexBuffer._updateID++; + this.uvBuffer._updateID++; + return this; + }; + return QuadUv; + }(Geometry)); + + var UID$2 = 0; + /** + * Uniform group holds uniform map and some ID's for work + * + * `UniformGroup` has two modes: + * + * 1: Normal mode + * Normal mode will upload the uniforms with individual function calls as required + * + * 2: Uniform buffer mode + * This mode will treat the uniforms as a uniform buffer. You can pass in either a buffer that you manually handle, or + * or a generic object that PixiJS will automatically map to a buffer for you. + * For maximum benefits, make Ubo UniformGroups static, and only update them each frame. + * + * Rules of UBOs: + * - UBOs only work with WebGL2, so make sure you have a fallback! + * - Only floats are supported (including vec[2,3,4], mat[2,3,4]) + * - Samplers cannot be used in ubo's (a GPU limitation) + * - You must ensure that the object you pass in exactly matches in the shader ubo structure. + * Otherwise, weirdness will ensue! + * - The name of the ubo object added to the group must match exactly the name of the ubo in the shader. + * + * ``` + * // ubo in shader: + * uniform myCoolData { // declaring a ubo.. + * mat4 uCoolMatrix; + * float uFloatyMcFloatFace + * + * + * // a new uniform buffer object.. + * const myCoolData = new UniformBufferGroup({ + * uCoolMatrix: new Matrix(), + * uFloatyMcFloatFace: 23, + * }} + * + * // build a shader... + * const shader = Shader.from(srcVert, srcFrag, { + * myCoolData // name matches the ubo name in the shader. will be processed accordingly. + * }) + * + * ``` + * @memberof PIXI + */ + var UniformGroup = /** @class */ (function () { + /** + * @param {object | Buffer} [uniforms] - Custom uniforms to use to augment the built-in ones. Or a pixi buffer. + * @param isStatic - Uniforms wont be changed after creation. + * @param isUbo - If true, will treat this uniform group as a uniform buffer object. + */ + function UniformGroup(uniforms, isStatic, isUbo) { + this.group = true; + // lets generate this when the shader ? + this.syncUniforms = {}; + this.dirtyId = 0; + this.id = UID$2++; + this.static = !!isStatic; + this.ubo = !!isUbo; + if (uniforms instanceof Buffer) { + this.buffer = uniforms; + this.buffer.type = exports.BUFFER_TYPE.UNIFORM_BUFFER; + this.autoManage = false; + this.ubo = true; + } + else { + this.uniforms = uniforms; + if (this.ubo) { + this.buffer = new Buffer(new Float32Array(1)); + this.buffer.type = exports.BUFFER_TYPE.UNIFORM_BUFFER; + this.autoManage = true; + } + } + } + UniformGroup.prototype.update = function () { + this.dirtyId++; + if (!this.autoManage && this.buffer) { + this.buffer.update(); + } + }; + UniformGroup.prototype.add = function (name, uniforms, _static) { + if (!this.ubo) { + this.uniforms[name] = new UniformGroup(uniforms, _static); + } + else { + // eslint-disable-next-line max-len + throw new Error('[UniformGroup] uniform groups in ubo mode cannot be modified, or have uniform groups nested in them'); + } + }; + UniformGroup.from = function (uniforms, _static, _ubo) { + return new UniformGroup(uniforms, _static, _ubo); + }; + /** + * A short hand function for creating a static UBO UniformGroup. + * @param uniforms - the ubo item + * @param _static - should this be updated each time it is used? defaults to true here! + */ + UniformGroup.uboFrom = function (uniforms, _static) { + return new UniformGroup(uniforms, _static !== null && _static !== void 0 ? _static : true, true); + }; + return UniformGroup; + }()); -var _Shader2 = require('../../core/Shader'); + /** + * System plugin to the renderer to manage filter states. + * @ignore + */ + var FilterState = /** @class */ (function () { + function FilterState() { + this.renderTexture = null; + this.target = null; + this.legacy = false; + this.resolution = 1; + this.multisample = exports.MSAA_QUALITY.NONE; + // next three fields are created only for root + // re-assigned for everything else + this.sourceFrame = new Rectangle(); + this.destinationFrame = new Rectangle(); + this.bindingSourceFrame = new Rectangle(); + this.bindingDestinationFrame = new Rectangle(); + this.filters = []; + this.transform = null; + } + /** Clears the state */ + FilterState.prototype.clear = function () { + this.target = null; + this.filters = null; + this.renderTexture = null; + }; + return FilterState; + }()); + + var tempPoints = [new Point(), new Point(), new Point(), new Point()]; + var tempMatrix$2 = new Matrix(); + /** + * System plugin to the renderer to manage filters. + * + * ## Pipeline + * + * The FilterSystem executes the filtering pipeline by rendering the display-object into a texture, applying its + * [filters]{@link PIXI.Filter} in series, and the last filter outputs into the final render-target. + * + * The filter-frame is the rectangle in world space being filtered, and those contents are mapped into + * `(0, 0, filterFrame.width, filterFrame.height)` into the filter render-texture. The filter-frame is also called + * the source-frame, as it is used to bind the filter render-textures. The last filter outputs to the `filterFrame` + * in the final render-target. + * + * ## Usage + * + * {@link PIXI.Container#renderAdvanced} is an example of how to use the filter system. It is a 3 step process: + * + * **push**: Use {@link PIXI.FilterSystem#push} to push the set of filters to be applied on a filter-target. + * **render**: Render the contents to be filtered using the renderer. The filter-system will only capture the contents + * inside the bounds of the filter-target. NOTE: Using {@link PIXI.Renderer#render} is + * illegal during an existing render cycle, and it may reset the filter system. + * **pop**: Use {@link PIXI.FilterSystem#pop} to pop & execute the filters you initially pushed. It will apply them + * serially and output to the bounds of the filter-target. + * @memberof PIXI + */ + var FilterSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this System works for. + */ + function FilterSystem(renderer) { + this.renderer = renderer; + this.defaultFilterStack = [{}]; + this.texturePool = new RenderTexturePool(); + this.texturePool.setScreenSize(renderer.view); + this.statePool = []; + this.quad = new Quad(); + this.quadUv = new QuadUv(); + this.tempRect = new Rectangle(); + this.activeState = {}; + this.globalUniforms = new UniformGroup({ + outputFrame: new Rectangle(), + inputSize: new Float32Array(4), + inputPixel: new Float32Array(4), + inputClamp: new Float32Array(4), + resolution: 1, + // legacy variables + filterArea: new Float32Array(4), + filterClamp: new Float32Array(4), + }, true); + this.forceClear = false; + this.useMaxPadding = false; + } + /** + * Pushes a set of filters to be applied later to the system. This will redirect further rendering into an + * input render-texture for the rest of the filtering pipeline. + * @param {PIXI.DisplayObject} target - The target of the filter to render. + * @param filters - The filters to apply. + */ + FilterSystem.prototype.push = function (target, filters) { + var _a, _b; + var renderer = this.renderer; + var filterStack = this.defaultFilterStack; + var state = this.statePool.pop() || new FilterState(); + var renderTextureSystem = this.renderer.renderTexture; + var resolution = filters[0].resolution; + var multisample = filters[0].multisample; + var padding = filters[0].padding; + var autoFit = filters[0].autoFit; + // We don't know whether it's a legacy filter until it was bound for the first time, + // therefore we have to assume that it is if legacy is undefined. + var legacy = (_a = filters[0].legacy) !== null && _a !== void 0 ? _a : true; + for (var i = 1; i < filters.length; i++) { + var filter = filters[i]; + // let's use the lowest resolution + resolution = Math.min(resolution, filter.resolution); + // let's use the lowest number of samples + multisample = Math.min(multisample, filter.multisample); + // figure out the padding required for filters + padding = this.useMaxPadding + // old behavior: use largest amount of padding! + ? Math.max(padding, filter.padding) + // new behavior: sum the padding + : padding + filter.padding; + // only auto fit if all filters are autofit + autoFit = autoFit && filter.autoFit; + legacy = legacy || ((_b = filter.legacy) !== null && _b !== void 0 ? _b : true); + } + if (filterStack.length === 1) { + this.defaultFilterStack[0].renderTexture = renderTextureSystem.current; + } + filterStack.push(state); + state.resolution = resolution; + state.multisample = multisample; + state.legacy = legacy; + state.target = target; + state.sourceFrame.copyFrom(target.filterArea || target.getBounds(true)); + state.sourceFrame.pad(padding); + var sourceFrameProjected = this.tempRect.copyFrom(renderTextureSystem.sourceFrame); + // Project source frame into world space (if projection is applied) + if (renderer.projection.transform) { + this.transformAABB(tempMatrix$2.copyFrom(renderer.projection.transform).invert(), sourceFrameProjected); + } + if (autoFit) { + state.sourceFrame.fit(sourceFrameProjected); + if (state.sourceFrame.width <= 0 || state.sourceFrame.height <= 0) { + state.sourceFrame.width = 0; + state.sourceFrame.height = 0; + } + } + else if (!state.sourceFrame.intersects(sourceFrameProjected)) { + state.sourceFrame.width = 0; + state.sourceFrame.height = 0; + } + // Round sourceFrame in screen space based on render-texture. + this.roundFrame(state.sourceFrame, renderTextureSystem.current ? renderTextureSystem.current.resolution : renderer.resolution, renderTextureSystem.sourceFrame, renderTextureSystem.destinationFrame, renderer.projection.transform); + state.renderTexture = this.getOptimalFilterTexture(state.sourceFrame.width, state.sourceFrame.height, resolution, multisample); + state.filters = filters; + state.destinationFrame.width = state.renderTexture.width; + state.destinationFrame.height = state.renderTexture.height; + var destinationFrame = this.tempRect; + destinationFrame.x = 0; + destinationFrame.y = 0; + destinationFrame.width = state.sourceFrame.width; + destinationFrame.height = state.sourceFrame.height; + state.renderTexture.filterFrame = state.sourceFrame; + state.bindingSourceFrame.copyFrom(renderTextureSystem.sourceFrame); + state.bindingDestinationFrame.copyFrom(renderTextureSystem.destinationFrame); + state.transform = renderer.projection.transform; + renderer.projection.transform = null; + renderTextureSystem.bind(state.renderTexture, state.sourceFrame, destinationFrame); + renderer.framebuffer.clear(0, 0, 0, 0); + }; + /** Pops off the filter and applies it. */ + FilterSystem.prototype.pop = function () { + var filterStack = this.defaultFilterStack; + var state = filterStack.pop(); + var filters = state.filters; + this.activeState = state; + var globalUniforms = this.globalUniforms.uniforms; + globalUniforms.outputFrame = state.sourceFrame; + globalUniforms.resolution = state.resolution; + var inputSize = globalUniforms.inputSize; + var inputPixel = globalUniforms.inputPixel; + var inputClamp = globalUniforms.inputClamp; + inputSize[0] = state.destinationFrame.width; + inputSize[1] = state.destinationFrame.height; + inputSize[2] = 1.0 / inputSize[0]; + inputSize[3] = 1.0 / inputSize[1]; + inputPixel[0] = Math.round(inputSize[0] * state.resolution); + inputPixel[1] = Math.round(inputSize[1] * state.resolution); + inputPixel[2] = 1.0 / inputPixel[0]; + inputPixel[3] = 1.0 / inputPixel[1]; + inputClamp[0] = 0.5 * inputPixel[2]; + inputClamp[1] = 0.5 * inputPixel[3]; + inputClamp[2] = (state.sourceFrame.width * inputSize[2]) - (0.5 * inputPixel[2]); + inputClamp[3] = (state.sourceFrame.height * inputSize[3]) - (0.5 * inputPixel[3]); + // only update the rect if its legacy.. + if (state.legacy) { + var filterArea = globalUniforms.filterArea; + filterArea[0] = state.destinationFrame.width; + filterArea[1] = state.destinationFrame.height; + filterArea[2] = state.sourceFrame.x; + filterArea[3] = state.sourceFrame.y; + globalUniforms.filterClamp = globalUniforms.inputClamp; + } + this.globalUniforms.update(); + var lastState = filterStack[filterStack.length - 1]; + this.renderer.framebuffer.blit(); + if (filters.length === 1) { + filters[0].apply(this, state.renderTexture, lastState.renderTexture, exports.CLEAR_MODES.BLEND, state); + this.returnFilterTexture(state.renderTexture); + } + else { + var flip = state.renderTexture; + var flop = this.getOptimalFilterTexture(flip.width, flip.height, state.resolution); + flop.filterFrame = flip.filterFrame; + var i = 0; + for (i = 0; i < filters.length - 1; ++i) { + if (i === 1 && state.multisample > 1) { + flop = this.getOptimalFilterTexture(flip.width, flip.height, state.resolution); + flop.filterFrame = flip.filterFrame; + } + filters[i].apply(this, flip, flop, exports.CLEAR_MODES.CLEAR, state); + var t = flip; + flip = flop; + flop = t; + } + filters[i].apply(this, flip, lastState.renderTexture, exports.CLEAR_MODES.BLEND, state); + if (i > 1 && state.multisample > 1) { + this.returnFilterTexture(state.renderTexture); + } + this.returnFilterTexture(flip); + this.returnFilterTexture(flop); + } + // lastState.renderTexture is blitted when lastState is popped + state.clear(); + this.statePool.push(state); + }; + /** + * Binds a renderTexture with corresponding `filterFrame`, clears it if mode corresponds. + * @param filterTexture - renderTexture to bind, should belong to filter pool or filter stack + * @param clearMode - clearMode, by default its CLEAR/YES. See {@link PIXI.CLEAR_MODES} + */ + FilterSystem.prototype.bindAndClear = function (filterTexture, clearMode) { + if (clearMode === void 0) { clearMode = exports.CLEAR_MODES.CLEAR; } + var _a = this.renderer, renderTextureSystem = _a.renderTexture, stateSystem = _a.state; + if (filterTexture === this.defaultFilterStack[this.defaultFilterStack.length - 1].renderTexture) { + // Restore projection transform if rendering into the output render-target. + this.renderer.projection.transform = this.activeState.transform; + } + else { + // Prevent projection within filtering pipeline. + this.renderer.projection.transform = null; + } + if (filterTexture && filterTexture.filterFrame) { + var destinationFrame = this.tempRect; + destinationFrame.x = 0; + destinationFrame.y = 0; + destinationFrame.width = filterTexture.filterFrame.width; + destinationFrame.height = filterTexture.filterFrame.height; + renderTextureSystem.bind(filterTexture, filterTexture.filterFrame, destinationFrame); + } + else if (filterTexture !== this.defaultFilterStack[this.defaultFilterStack.length - 1].renderTexture) { + renderTextureSystem.bind(filterTexture); + } + else { + // Restore binding for output render-target. + this.renderer.renderTexture.bind(filterTexture, this.activeState.bindingSourceFrame, this.activeState.bindingDestinationFrame); + } + // Clear the texture in BLIT mode if blending is disabled or the forceClear flag is set. The blending + // is stored in the 0th bit of the state. + var autoClear = (stateSystem.stateId & 1) || this.forceClear; + if (clearMode === exports.CLEAR_MODES.CLEAR + || (clearMode === exports.CLEAR_MODES.BLIT && autoClear)) { + // Use framebuffer.clear because we want to clear the whole filter texture, not just the filtering + // area over which the shaders are run. This is because filters may sampling outside of it (e.g. blur) + // instead of clamping their arithmetic. + this.renderer.framebuffer.clear(0, 0, 0, 0); + } + }; + /** + * Draws a filter using the default rendering process. + * + * This should be called only by {@link Filter#apply}. + * @param filter - The filter to draw. + * @param input - The input render target. + * @param output - The target to output to. + * @param clearMode - Should the output be cleared before rendering to it + */ + FilterSystem.prototype.applyFilter = function (filter, input, output, clearMode) { + var renderer = this.renderer; + // Set state before binding, so bindAndClear gets the blend mode. + renderer.state.set(filter.state); + this.bindAndClear(output, clearMode); + // set the uniforms.. + filter.uniforms.uSampler = input; + filter.uniforms.filterGlobals = this.globalUniforms; + // TODO make it so that the order of this does not matter.. + // because it does at the moment cos of global uniforms. + // they need to get resynced + renderer.shader.bind(filter); + // check to see if the filter is a legacy one.. + filter.legacy = !!filter.program.attributeData.aTextureCoord; + if (filter.legacy) { + this.quadUv.map(input._frame, input.filterFrame); + renderer.geometry.bind(this.quadUv); + renderer.geometry.draw(exports.DRAW_MODES.TRIANGLES); + } + else { + renderer.geometry.bind(this.quad); + renderer.geometry.draw(exports.DRAW_MODES.TRIANGLE_STRIP); + } + }; + /** + * Multiply _input normalized coordinates_ to this matrix to get _sprite texture normalized coordinates_. + * + * Use `outputMatrix * vTextureCoord` in the shader. + * @param outputMatrix - The matrix to output to. + * @param {PIXI.Sprite} sprite - The sprite to map to. + * @returns The mapped matrix. + */ + FilterSystem.prototype.calculateSpriteMatrix = function (outputMatrix, sprite) { + var _a = this.activeState, sourceFrame = _a.sourceFrame, destinationFrame = _a.destinationFrame; + var orig = sprite._texture.orig; + var mappedMatrix = outputMatrix.set(destinationFrame.width, 0, 0, destinationFrame.height, sourceFrame.x, sourceFrame.y); + var worldTransform = sprite.worldTransform.copyTo(Matrix.TEMP_MATRIX); + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + mappedMatrix.scale(1.0 / orig.width, 1.0 / orig.height); + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + return mappedMatrix; + }; + /** Destroys this Filter System. */ + FilterSystem.prototype.destroy = function () { + this.renderer = null; + // Those textures has to be destroyed by RenderTextureSystem or FramebufferSystem + this.texturePool.clear(false); + }; + /** + * Gets a Power-of-Two render texture or fullScreen texture + * @param minWidth - The minimum width of the render texture in real pixels. + * @param minHeight - The minimum height of the render texture in real pixels. + * @param resolution - The resolution of the render texture. + * @param multisample - Number of samples of the render texture. + * @returns - The new render texture. + */ + FilterSystem.prototype.getOptimalFilterTexture = function (minWidth, minHeight, resolution, multisample) { + if (resolution === void 0) { resolution = 1; } + if (multisample === void 0) { multisample = exports.MSAA_QUALITY.NONE; } + return this.texturePool.getOptimalTexture(minWidth, minHeight, resolution, multisample); + }; + /** + * Gets extra render texture to use inside current filter + * To be compliant with older filters, you can use params in any order + * @param input - renderTexture from which size and resolution will be copied + * @param resolution - override resolution of the renderTexture + * @param multisample - number of samples of the renderTexture + */ + FilterSystem.prototype.getFilterTexture = function (input, resolution, multisample) { + if (typeof input === 'number') { + var swap = input; + input = resolution; + resolution = swap; + } + input = input || this.activeState.renderTexture; + var filterTexture = this.texturePool.getOptimalTexture(input.width, input.height, resolution || input.resolution, multisample || exports.MSAA_QUALITY.NONE); + filterTexture.filterFrame = input.filterFrame; + return filterTexture; + }; + /** + * Frees a render texture back into the pool. + * @param renderTexture - The renderTarget to free + */ + FilterSystem.prototype.returnFilterTexture = function (renderTexture) { + this.texturePool.returnTexture(renderTexture); + }; + /** Empties the texture pool. */ + FilterSystem.prototype.emptyPool = function () { + this.texturePool.clear(true); + }; + /** Calls `texturePool.resize()`, affects fullScreen renderTextures. */ + FilterSystem.prototype.resize = function () { + this.texturePool.setScreenSize(this.renderer.view); + }; + /** + * @param matrix - first param + * @param rect - second param + */ + FilterSystem.prototype.transformAABB = function (matrix, rect) { + var lt = tempPoints[0]; + var lb = tempPoints[1]; + var rt = tempPoints[2]; + var rb = tempPoints[3]; + lt.set(rect.left, rect.top); + lb.set(rect.left, rect.bottom); + rt.set(rect.right, rect.top); + rb.set(rect.right, rect.bottom); + matrix.apply(lt, lt); + matrix.apply(lb, lb); + matrix.apply(rt, rt); + matrix.apply(rb, rb); + var x0 = Math.min(lt.x, lb.x, rt.x, rb.x); + var y0 = Math.min(lt.y, lb.y, rt.y, rb.y); + var x1 = Math.max(lt.x, lb.x, rt.x, rb.x); + var y1 = Math.max(lt.y, lb.y, rt.y, rb.y); + rect.x = x0; + rect.y = y0; + rect.width = x1 - x0; + rect.height = y1 - y0; + }; + FilterSystem.prototype.roundFrame = function (frame, resolution, bindingSourceFrame, bindingDestinationFrame, transform) { + if (frame.width <= 0 || frame.height <= 0 || bindingSourceFrame.width <= 0 || bindingSourceFrame.height <= 0) { + return; + } + if (transform) { + var a = transform.a, b = transform.b, c = transform.c, d = transform.d; + // Skip if skew/rotation present in matrix, except for multiple of 90° rotation. If rotation + // is a multiple of 90°, then either pair of (b,c) or (a,d) will be (0,0). + if ((Math.abs(b) > 1e-4 || Math.abs(c) > 1e-4) + && (Math.abs(a) > 1e-4 || Math.abs(d) > 1e-4)) { + return; + } + } + transform = transform ? tempMatrix$2.copyFrom(transform) : tempMatrix$2.identity(); + // Get forward transform from world space to screen space + transform + .translate(-bindingSourceFrame.x, -bindingSourceFrame.y) + .scale(bindingDestinationFrame.width / bindingSourceFrame.width, bindingDestinationFrame.height / bindingSourceFrame.height) + .translate(bindingDestinationFrame.x, bindingDestinationFrame.y); + // Convert frame to screen space + this.transformAABB(transform, frame); + // Round frame in screen space + frame.ceil(resolution); + // Project back into world space. + this.transformAABB(transform.invert(), frame); + }; + return FilterSystem; + }()); -var _Shader3 = _interopRequireDefault(_Shader2); + /** + * Base for a common object renderer that can be used as a + * system renderer plugin. + * @memberof PIXI + */ + var ObjectRenderer = /** @class */ (function () { + /** + * @param renderer - The renderer this manager works for. + */ + function ObjectRenderer(renderer) { + this.renderer = renderer; + } + /** Stub method that should be used to empty the current batch by rendering objects now. */ + ObjectRenderer.prototype.flush = function () { + // flush! + }; + /** Generic destruction method that frees all resources. This should be called by subclasses. */ + ObjectRenderer.prototype.destroy = function () { + this.renderer = null; + }; + /** + * Stub method that initializes any state required before + * rendering starts. It is different from the `prerender` + * signal, which occurs every frame, in that it is called + * whenever an object requests _this_ renderer specifically. + */ + ObjectRenderer.prototype.start = function () { + // set the shader.. + }; + /** Stops the renderer. It should free up any state and become dormant. */ + ObjectRenderer.prototype.stop = function () { + this.flush(); + }; + /** + * Keeps the object to render. It doesn't have to be + * rendered immediately. + * @param {PIXI.DisplayObject} _object - The object to render. + */ + ObjectRenderer.prototype.render = function (_object) { + // render the object + }; + return ObjectRenderer; + }()); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** + * System plugin to the renderer to manage batching. + * @memberof PIXI + */ + var BatchSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this System works for. + */ + function BatchSystem(renderer) { + this.renderer = renderer; + this.emptyRenderer = new ObjectRenderer(renderer); + this.currentRenderer = this.emptyRenderer; + } + /** + * Changes the current renderer to the one given in parameter + * @param objectRenderer - The object renderer to use. + */ + BatchSystem.prototype.setObjectRenderer = function (objectRenderer) { + if (this.currentRenderer === objectRenderer) { + return; + } + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); + }; + /** + * This should be called if you wish to do some custom rendering + * It will basically render anything that may be batched up such as sprites + */ + BatchSystem.prototype.flush = function () { + this.setObjectRenderer(this.emptyRenderer); + }; + /** Reset the system to an empty renderer */ + BatchSystem.prototype.reset = function () { + this.setObjectRenderer(this.emptyRenderer); + }; + /** + * Handy function for batch renderers: copies bound textures in first maxTextures locations to array + * sets actual _batchLocation for them + * @param arr - arr copy destination + * @param maxTextures - number of copied elements + */ + BatchSystem.prototype.copyBoundTextures = function (arr, maxTextures) { + var boundTextures = this.renderer.texture.boundTextures; + for (var i = maxTextures - 1; i >= 0; --i) { + arr[i] = boundTextures[i] || null; + if (arr[i]) { + arr[i]._batchLocation = i; + } + } + }; + /** + * Assigns batch locations to textures in array based on boundTextures state. + * All textures in texArray should have `_batchEnabled = _batchId`, + * and their count should be less than `maxTextures`. + * @param texArray - textures to bound + * @param boundTextures - current state of bound textures + * @param batchId - marker for _batchEnabled param of textures in texArray + * @param maxTextures - number of texture locations to manipulate + */ + BatchSystem.prototype.boundArray = function (texArray, boundTextures, batchId, maxTextures) { + var elements = texArray.elements, ids = texArray.ids, count = texArray.count; + var j = 0; + for (var i = 0; i < count; i++) { + var tex = elements[i]; + var loc = tex._batchLocation; + if (loc >= 0 && loc < maxTextures + && boundTextures[loc] === tex) { + ids[i] = loc; + continue; + } + while (j < maxTextures) { + var bound = boundTextures[j]; + if (bound && bound._batchEnabled === batchId + && bound._batchLocation === j) { + j++; + continue; + } + ids[i] = j; + tex._batchLocation = j; + boundTextures[j] = tex; + break; + } + } + }; + /** + * @ignore + */ + BatchSystem.prototype.destroy = function () { + this.renderer = null; + }; + return BatchSystem; + }()); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var CONTEXT_UID_COUNTER = 0; + /** + * System plugin to the renderer to manage the context. + * @memberof PIXI + */ + var ContextSystem = /** @class */ (function () { + /** @param renderer - The renderer this System works for. */ + function ContextSystem(renderer) { + this.renderer = renderer; + this.webGLVersion = 1; + this.extensions = {}; + this.supports = { + uint32Indices: false, + }; + // Bind functions + this.handleContextLost = this.handleContextLost.bind(this); + this.handleContextRestored = this.handleContextRestored.bind(this); + renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); + renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); + } + Object.defineProperty(ContextSystem.prototype, "isLost", { + /** + * `true` if the context is lost + * @readonly + */ + get: function () { + return (!this.gl || this.gl.isContextLost()); + }, + enumerable: false, + configurable: true + }); + /** + * Handles the context change event. + * @param {WebGLRenderingContext} gl - New WebGL context. + */ + ContextSystem.prototype.contextChange = function (gl) { + this.gl = gl; + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID_COUNTER++; + }; + /** + * Initializes the context. + * @protected + * @param {WebGLRenderingContext} gl - WebGL context + */ + ContextSystem.prototype.initFromContext = function (gl) { + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID_COUNTER++; + this.renderer.runners.contextChange.emit(gl); + }; + /** + * Initialize from context options + * @protected + * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext + * @param {object} options - context attributes + */ + ContextSystem.prototype.initFromOptions = function (options) { + var gl = this.createContext(this.renderer.view, options); + this.initFromContext(gl); + }; + /** + * Helper class to create a WebGL Context + * @param canvas - the canvas element that we will get the context from + * @param options - An options object that gets passed in to the canvas element containing the + * context attributes + * @see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext + * @returns {WebGLRenderingContext} the WebGL context + */ + ContextSystem.prototype.createContext = function (canvas, options) { + var gl; + if (settings.PREFER_ENV >= exports.ENV.WEBGL2) { + gl = canvas.getContext('webgl2', options); + } + if (gl) { + this.webGLVersion = 2; + } + else { + this.webGLVersion = 1; + gl = canvas.getContext('webgl', options) || canvas.getContext('experimental-webgl', options); + if (!gl) { + // fail, not able to get a context + throw new Error('This browser does not support WebGL. Try using the canvas renderer'); + } + } + this.gl = gl; + this.getExtensions(); + return this.gl; + }; + /** Auto-populate the {@link PIXI.ContextSystem.extensions extensions}. */ + ContextSystem.prototype.getExtensions = function () { + // time to set up default extensions that Pixi uses. + var gl = this.gl; + var common = { + loseContext: gl.getExtension('WEBGL_lose_context'), + anisotropicFiltering: gl.getExtension('EXT_texture_filter_anisotropic'), + floatTextureLinear: gl.getExtension('OES_texture_float_linear'), + s3tc: gl.getExtension('WEBGL_compressed_texture_s3tc'), + s3tc_sRGB: gl.getExtension('WEBGL_compressed_texture_s3tc_srgb'), + etc: gl.getExtension('WEBGL_compressed_texture_etc'), + etc1: gl.getExtension('WEBGL_compressed_texture_etc1'), + pvrtc: gl.getExtension('WEBGL_compressed_texture_pvrtc') + || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'), + atc: gl.getExtension('WEBGL_compressed_texture_atc'), + astc: gl.getExtension('WEBGL_compressed_texture_astc') + }; + if (this.webGLVersion === 1) { + Object.assign(this.extensions, common, { + drawBuffers: gl.getExtension('WEBGL_draw_buffers'), + depthTexture: gl.getExtension('WEBGL_depth_texture'), + vertexArrayObject: gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'), + uint32ElementIndex: gl.getExtension('OES_element_index_uint'), + // Floats and half-floats + floatTexture: gl.getExtension('OES_texture_float'), + floatTextureLinear: gl.getExtension('OES_texture_float_linear'), + textureHalfFloat: gl.getExtension('OES_texture_half_float'), + textureHalfFloatLinear: gl.getExtension('OES_texture_half_float_linear'), + }); + } + else if (this.webGLVersion === 2) { + Object.assign(this.extensions, common, { + // Floats and half-floats + colorBufferFloat: gl.getExtension('EXT_color_buffer_float') + }); + } + }; + /** + * Handles a lost webgl context + * @param {WebGLContextEvent} event - The context lost event. + */ + ContextSystem.prototype.handleContextLost = function (event) { + var _this = this; + // Prevent default to be able to restore the context + event.preventDefault(); + // Restore the context after this event has exited + setTimeout(function () { + if (_this.gl.isContextLost() && _this.extensions.loseContext) { + _this.extensions.loseContext.restoreContext(); + } + }, 0); + }; + /** Handles a restored webgl context. */ + ContextSystem.prototype.handleContextRestored = function () { + this.renderer.runners.contextChange.emit(this.gl); + }; + ContextSystem.prototype.destroy = function () { + var view = this.renderer.view; + this.renderer = null; + // remove listeners + view.removeEventListener('webglcontextlost', this.handleContextLost); + view.removeEventListener('webglcontextrestored', this.handleContextRestored); + this.gl.useProgram(null); + if (this.extensions.loseContext) { + this.extensions.loseContext.loseContext(); + } + }; + /** Handle the post-render runner event. */ + ContextSystem.prototype.postrender = function () { + if (this.renderer.renderingToScreen) { + this.gl.flush(); + } + }; + /** + * Validate context. + * @param {WebGLRenderingContext} gl - Render context. + */ + ContextSystem.prototype.validateContext = function (gl) { + var attributes = gl.getContextAttributes(); + var isWebGl2 = 'WebGL2RenderingContext' in globalThis && gl instanceof globalThis.WebGL2RenderingContext; + if (isWebGl2) { + this.webGLVersion = 2; + } + // this is going to be fairly simple for now.. but at least we have room to grow! + if (attributes && !attributes.stencil) { + /* eslint-disable max-len, no-console */ + console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); + /* eslint-enable max-len, no-console */ + } + var hasuint32 = isWebGl2 || !!gl.getExtension('OES_element_index_uint'); + this.supports.uint32Indices = hasuint32; + if (!hasuint32) { + /* eslint-disable max-len, no-console */ + console.warn('Provided WebGL context does not support 32 index buffer, complex graphics may not render correctly'); + /* eslint-enable max-len, no-console */ + } + }; + return ContextSystem; + }()); -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + /** + * Internal framebuffer for WebGL context. + * @memberof PIXI + */ + var GLFramebuffer = /** @class */ (function () { + function GLFramebuffer(framebuffer) { + this.framebuffer = framebuffer; + this.stencil = null; + this.dirtyId = -1; + this.dirtyFormat = -1; + this.dirtySize = -1; + this.multisample = exports.MSAA_QUALITY.NONE; + this.msaaBuffer = null; + this.blitFramebuffer = null; + this.mipLevel = 0; + } + return GLFramebuffer; + }()); -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + var tempRectangle = new Rectangle(); + /** + * System plugin to the renderer to manage framebuffers. + * @memberof PIXI + */ + var FramebufferSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this System works for. + */ + function FramebufferSystem(renderer) { + this.renderer = renderer; + this.managedFramebuffers = []; + this.unknownFramebuffer = new Framebuffer(10, 10); + this.msaaSamples = null; + } + /** Sets up the renderer context and necessary buffers. */ + FramebufferSystem.prototype.contextChange = function () { + this.disposeAll(true); + var gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.current = this.unknownFramebuffer; + this.viewport = new Rectangle(); + this.hasMRT = true; + this.writeDepthTexture = true; + // webgl2 + if (this.renderer.context.webGLVersion === 1) { + // webgl 1! + var nativeDrawBuffersExtension_1 = this.renderer.context.extensions.drawBuffers; + var nativeDepthTextureExtension = this.renderer.context.extensions.depthTexture; + if (settings.PREFER_ENV === exports.ENV.WEBGL_LEGACY) { + nativeDrawBuffersExtension_1 = null; + nativeDepthTextureExtension = null; + } + if (nativeDrawBuffersExtension_1) { + gl.drawBuffers = function (activeTextures) { + return nativeDrawBuffersExtension_1.drawBuffersWEBGL(activeTextures); + }; + } + else { + this.hasMRT = false; + gl.drawBuffers = function () { + // empty + }; + } + if (!nativeDepthTextureExtension) { + this.writeDepthTexture = false; + } + } + else { + // WebGL2 + // cache possible MSAA samples + this.msaaSamples = gl.getInternalformatParameter(gl.RENDERBUFFER, gl.RGBA8, gl.SAMPLES); + } + }; + /** + * Bind a framebuffer. + * @param framebuffer + * @param frame - frame, default is framebuffer size + * @param mipLevel - optional mip level to set on the framebuffer - defaults to 0 + */ + FramebufferSystem.prototype.bind = function (framebuffer, frame, mipLevel) { + if (mipLevel === void 0) { mipLevel = 0; } + var gl = this.gl; + if (framebuffer) { + // TODO caching layer! + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + if (this.current !== framebuffer) { + this.current = framebuffer; + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); + } + // make sure all textures are unbound.. + if (fbo.mipLevel !== mipLevel) { + framebuffer.dirtyId++; + framebuffer.dirtyFormat++; + fbo.mipLevel = mipLevel; + } + // now check for updates... + if (fbo.dirtyId !== framebuffer.dirtyId) { + fbo.dirtyId = framebuffer.dirtyId; + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { + fbo.dirtyFormat = framebuffer.dirtyFormat; + fbo.dirtySize = framebuffer.dirtySize; + this.updateFramebuffer(framebuffer, mipLevel); + } + else if (fbo.dirtySize !== framebuffer.dirtySize) { + fbo.dirtySize = framebuffer.dirtySize; + this.resizeFramebuffer(framebuffer); + } + } + for (var i = 0; i < framebuffer.colorTextures.length; i++) { + var tex = framebuffer.colorTextures[i]; + this.renderer.texture.unbind(tex.parentTextureArray || tex); + } + if (framebuffer.depthTexture) { + this.renderer.texture.unbind(framebuffer.depthTexture); + } + if (frame) { + var mipWidth = (frame.width >> mipLevel); + var mipHeight = (frame.height >> mipLevel); + var scale = mipWidth / frame.width; + this.setViewport(frame.x * scale, frame.y * scale, mipWidth, mipHeight); + } + else { + var mipWidth = (framebuffer.width >> mipLevel); + var mipHeight = (framebuffer.height >> mipLevel); + this.setViewport(0, 0, mipWidth, mipHeight); + } + } + else { + if (this.current) { + this.current = null; + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + } + if (frame) { + this.setViewport(frame.x, frame.y, frame.width, frame.height); + } + else { + this.setViewport(0, 0, this.renderer.width, this.renderer.height); + } + } + }; + /** + * Set the WebGLRenderingContext's viewport. + * @param x - X position of viewport + * @param y - Y position of viewport + * @param width - Width of viewport + * @param height - Height of viewport + */ + FramebufferSystem.prototype.setViewport = function (x, y, width, height) { + var v = this.viewport; + x = Math.round(x); + y = Math.round(y); + width = Math.round(width); + height = Math.round(height); + if (v.width !== width || v.height !== height || v.x !== x || v.y !== y) { + v.x = x; + v.y = y; + v.width = width; + v.height = height; + this.gl.viewport(x, y, width, height); + } + }; + Object.defineProperty(FramebufferSystem.prototype, "size", { + /** + * Get the size of the current width and height. Returns object with `width` and `height` values. + * @readonly + */ + get: function () { + if (this.current) { + // TODO store temp + return { x: 0, y: 0, width: this.current.width, height: this.current.height }; + } + return { x: 0, y: 0, width: this.renderer.width, height: this.renderer.height }; + }, + enumerable: false, + configurable: true + }); + /** + * Clear the color of the context + * @param r - Red value from 0 to 1 + * @param g - Green value from 0 to 1 + * @param b - Blue value from 0 to 1 + * @param a - Alpha value from 0 to 1 + * @param {PIXI.BUFFER_BITS} [mask=BUFFER_BITS.COLOR | BUFFER_BITS.DEPTH] - Bitwise OR of masks + * that indicate the buffers to be cleared, by default COLOR and DEPTH buffers. + */ + FramebufferSystem.prototype.clear = function (r, g, b, a, mask) { + if (mask === void 0) { mask = exports.BUFFER_BITS.COLOR | exports.BUFFER_BITS.DEPTH; } + var gl = this.gl; + // TODO clear color can be set only one right? + gl.clearColor(r, g, b, a); + gl.clear(mask); + }; + /** + * Initialize framebuffer for this context + * @protected + * @param framebuffer + * @returns - created GLFramebuffer + */ + FramebufferSystem.prototype.initFramebuffer = function (framebuffer) { + var gl = this.gl; + var fbo = new GLFramebuffer(gl.createFramebuffer()); + fbo.multisample = this.detectSamples(framebuffer.multisample); + framebuffer.glFramebuffers[this.CONTEXT_UID] = fbo; + this.managedFramebuffers.push(framebuffer); + framebuffer.disposeRunner.add(this); + return fbo; + }; + /** + * Resize the framebuffer + * @param framebuffer + * @protected + */ + FramebufferSystem.prototype.resizeFramebuffer = function (framebuffer) { + var gl = this.gl; + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + if (fbo.msaaBuffer) { + gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.msaaBuffer); + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.RGBA8, framebuffer.width, framebuffer.height); + } + if (fbo.stencil) { + gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil); + if (fbo.msaaBuffer) { + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, framebuffer.width, framebuffer.height); + } + else { + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + } + } + var colorTextures = framebuffer.colorTextures; + var count = colorTextures.length; + if (!gl.drawBuffers) { + count = Math.min(count, 1); + } + for (var i = 0; i < count; i++) { + var texture = colorTextures[i]; + var parentTexture = texture.parentTextureArray || texture; + this.renderer.texture.bind(parentTexture, 0); + } + if (framebuffer.depthTexture && this.writeDepthTexture) { + this.renderer.texture.bind(framebuffer.depthTexture, 0); + } + }; + /** + * Update the framebuffer + * @param framebuffer + * @param mipLevel + * @protected + */ + FramebufferSystem.prototype.updateFramebuffer = function (framebuffer, mipLevel) { + var gl = this.gl; + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + // bind the color texture + var colorTextures = framebuffer.colorTextures; + var count = colorTextures.length; + if (!gl.drawBuffers) { + count = Math.min(count, 1); + } + if (fbo.multisample > 1 && this.canMultisampleFramebuffer(framebuffer)) { + fbo.msaaBuffer = fbo.msaaBuffer || gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.msaaBuffer); + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.RGBA8, framebuffer.width, framebuffer.height); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, fbo.msaaBuffer); + } + else if (fbo.msaaBuffer) { + gl.deleteRenderbuffer(fbo.msaaBuffer); + fbo.msaaBuffer = null; + if (fbo.blitFramebuffer) { + fbo.blitFramebuffer.dispose(); + fbo.blitFramebuffer = null; + } + } + var activeTextures = []; + for (var i = 0; i < count; i++) { + var texture = colorTextures[i]; + var parentTexture = texture.parentTextureArray || texture; + this.renderer.texture.bind(parentTexture, 0); + if (i === 0 && fbo.msaaBuffer) { + continue; + } + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, texture.target, parentTexture._glTextures[this.CONTEXT_UID].texture, mipLevel); + activeTextures.push(gl.COLOR_ATTACHMENT0 + i); + } + if (activeTextures.length > 1) { + gl.drawBuffers(activeTextures); + } + if (framebuffer.depthTexture) { + var writeDepthTexture = this.writeDepthTexture; + if (writeDepthTexture) { + var depthTexture = framebuffer.depthTexture; + this.renderer.texture.bind(depthTexture, 0); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._glTextures[this.CONTEXT_UID].texture, mipLevel); + } + } + if ((framebuffer.stencil || framebuffer.depth) && !(framebuffer.depthTexture && this.writeDepthTexture)) { + fbo.stencil = fbo.stencil || gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil); + if (fbo.msaaBuffer) { + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, framebuffer.width, framebuffer.height); + } + else { + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + } + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); + } + else if (fbo.stencil) { + gl.deleteRenderbuffer(fbo.stencil); + fbo.stencil = null; + } + }; + /** + * Returns true if the frame buffer can be multisampled. + * @param framebuffer + */ + FramebufferSystem.prototype.canMultisampleFramebuffer = function (framebuffer) { + return this.renderer.context.webGLVersion !== 1 + && framebuffer.colorTextures.length <= 1 && !framebuffer.depthTexture; + }; + /** + * Detects number of samples that is not more than a param but as close to it as possible + * @param samples - number of samples + * @returns - recommended number of samples + */ + FramebufferSystem.prototype.detectSamples = function (samples) { + var msaaSamples = this.msaaSamples; + var res = exports.MSAA_QUALITY.NONE; + if (samples <= 1 || msaaSamples === null) { + return res; + } + for (var i = 0; i < msaaSamples.length; i++) { + if (msaaSamples[i] <= samples) { + res = msaaSamples[i]; + break; + } + } + if (res === 1) { + res = exports.MSAA_QUALITY.NONE; + } + return res; + }; + /** + * Only works with WebGL2 + * + * blits framebuffer to another of the same or bigger size + * after that target framebuffer is bound + * + * Fails with WebGL warning if blits multisample framebuffer to different size + * @param framebuffer - by default it blits "into itself", from renderBuffer to texture. + * @param sourcePixels - source rectangle in pixels + * @param destPixels - dest rectangle in pixels, assumed to be the same as sourcePixels + */ + FramebufferSystem.prototype.blit = function (framebuffer, sourcePixels, destPixels) { + var _a = this, current = _a.current, renderer = _a.renderer, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; + if (renderer.context.webGLVersion !== 2) { + return; + } + if (!current) { + return; + } + var fbo = current.glFramebuffers[CONTEXT_UID]; + if (!fbo) { + return; + } + if (!framebuffer) { + if (!fbo.msaaBuffer) { + return; + } + var colorTexture = current.colorTextures[0]; + if (!colorTexture) { + return; + } + if (!fbo.blitFramebuffer) { + fbo.blitFramebuffer = new Framebuffer(current.width, current.height); + fbo.blitFramebuffer.addColorTexture(0, colorTexture); + } + framebuffer = fbo.blitFramebuffer; + if (framebuffer.colorTextures[0] !== colorTexture) { + framebuffer.colorTextures[0] = colorTexture; + framebuffer.dirtyId++; + framebuffer.dirtyFormat++; + } + if (framebuffer.width !== current.width || framebuffer.height !== current.height) { + framebuffer.width = current.width; + framebuffer.height = current.height; + framebuffer.dirtyId++; + framebuffer.dirtySize++; + } + } + if (!sourcePixels) { + sourcePixels = tempRectangle; + sourcePixels.width = current.width; + sourcePixels.height = current.height; + } + if (!destPixels) { + destPixels = sourcePixels; + } + var sameSize = sourcePixels.width === destPixels.width && sourcePixels.height === destPixels.height; + this.bind(framebuffer); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fbo.framebuffer); + gl.blitFramebuffer(sourcePixels.left, sourcePixels.top, sourcePixels.right, sourcePixels.bottom, destPixels.left, destPixels.top, destPixels.right, destPixels.bottom, gl.COLOR_BUFFER_BIT, sameSize ? gl.NEAREST : gl.LINEAR); + }; + /** + * Disposes framebuffer. + * @param framebuffer - framebuffer that has to be disposed of + * @param contextLost - If context was lost, we suppress all delete function calls + */ + FramebufferSystem.prototype.disposeFramebuffer = function (framebuffer, contextLost) { + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + var gl = this.gl; + if (!fbo) { + return; + } + delete framebuffer.glFramebuffers[this.CONTEXT_UID]; + var index = this.managedFramebuffers.indexOf(framebuffer); + if (index >= 0) { + this.managedFramebuffers.splice(index, 1); + } + framebuffer.disposeRunner.remove(this); + if (!contextLost) { + gl.deleteFramebuffer(fbo.framebuffer); + if (fbo.msaaBuffer) { + gl.deleteRenderbuffer(fbo.msaaBuffer); + } + if (fbo.stencil) { + gl.deleteRenderbuffer(fbo.stencil); + } + } + if (fbo.blitFramebuffer) { + fbo.blitFramebuffer.dispose(); + } + }; + /** + * Disposes all framebuffers, but not textures bound to them. + * @param [contextLost=false] - If context was lost, we suppress all delete function calls + */ + FramebufferSystem.prototype.disposeAll = function (contextLost) { + var list = this.managedFramebuffers; + this.managedFramebuffers = []; + for (var i = 0; i < list.length; i++) { + this.disposeFramebuffer(list[i], contextLost); + } + }; + /** + * Forcing creation of stencil buffer for current framebuffer, if it wasn't done before. + * Used by MaskSystem, when its time to use stencil mask for Graphics element. + * + * Its an alternative for public lazy `framebuffer.enableStencil`, in case we need stencil without rebind. + * @private + */ + FramebufferSystem.prototype.forceStencil = function () { + var framebuffer = this.current; + if (!framebuffer) { + return; + } + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + if (!fbo || fbo.stencil) { + return; + } + framebuffer.stencil = true; + var w = framebuffer.width; + var h = framebuffer.height; + var gl = this.gl; + var stencil = gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, stencil); + if (fbo.msaaBuffer) { + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, w, h); + } + else { + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, w, h); + } + fbo.stencil = stencil; + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, stencil); + }; + /** Resets framebuffer stored state, binds screen framebuffer. Should be called before renderTexture reset(). */ + FramebufferSystem.prototype.reset = function () { + this.current = this.unknownFramebuffer; + this.viewport = new Rectangle(); + }; + FramebufferSystem.prototype.destroy = function () { + this.renderer = null; + }; + return FramebufferSystem; + }()); + + var byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; + /** + * System plugin to the renderer to manage geometry. + * @memberof PIXI + */ + var GeometrySystem = /** @class */ (function () { + /** @param renderer - The renderer this System works for. */ + function GeometrySystem(renderer) { + this.renderer = renderer; + this._activeGeometry = null; + this._activeVao = null; + this.hasVao = true; + this.hasInstance = true; + this.canUseUInt32ElementIndex = false; + this.managedGeometries = {}; + } + /** Sets up the renderer context and necessary buffers. */ + GeometrySystem.prototype.contextChange = function () { + this.disposeAll(true); + var gl = this.gl = this.renderer.gl; + var context = this.renderer.context; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + // webgl2 + if (context.webGLVersion !== 2) { + // webgl 1! + var nativeVaoExtension_1 = this.renderer.context.extensions.vertexArrayObject; + if (settings.PREFER_ENV === exports.ENV.WEBGL_LEGACY) { + nativeVaoExtension_1 = null; + } + if (nativeVaoExtension_1) { + gl.createVertexArray = function () { + return nativeVaoExtension_1.createVertexArrayOES(); + }; + gl.bindVertexArray = function (vao) { + return nativeVaoExtension_1.bindVertexArrayOES(vao); + }; + gl.deleteVertexArray = function (vao) { + return nativeVaoExtension_1.deleteVertexArrayOES(vao); + }; + } + else { + this.hasVao = false; + gl.createVertexArray = function () { + return null; + }; + gl.bindVertexArray = function () { + return null; + }; + gl.deleteVertexArray = function () { + return null; + }; + } + } + if (context.webGLVersion !== 2) { + var instanceExt_1 = gl.getExtension('ANGLE_instanced_arrays'); + if (instanceExt_1) { + gl.vertexAttribDivisor = function (a, b) { + return instanceExt_1.vertexAttribDivisorANGLE(a, b); + }; + gl.drawElementsInstanced = function (a, b, c, d, e) { + return instanceExt_1.drawElementsInstancedANGLE(a, b, c, d, e); + }; + gl.drawArraysInstanced = function (a, b, c, d) { + return instanceExt_1.drawArraysInstancedANGLE(a, b, c, d); + }; + } + else { + this.hasInstance = false; + } + } + this.canUseUInt32ElementIndex = context.webGLVersion === 2 || !!context.extensions.uint32ElementIndex; + }; + /** + * Binds geometry so that is can be drawn. Creating a Vao if required + * @param geometry - Instance of geometry to bind. + * @param shader - Instance of shader to use vao for. + */ + GeometrySystem.prototype.bind = function (geometry, shader) { + shader = shader || this.renderer.shader.shader; + var gl = this.gl; + // not sure the best way to address this.. + // currently different shaders require different VAOs for the same geometry + // Still mulling over the best way to solve this one.. + // will likely need to modify the shader attribute locations at run time! + var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; + var incRefCount = false; + if (!vaos) { + this.managedGeometries[geometry.id] = geometry; + geometry.disposeRunner.add(this); + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; + incRefCount = true; + } + var vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader, incRefCount); + this._activeGeometry = geometry; + if (this._activeVao !== vao) { + this._activeVao = vao; + if (this.hasVao) { + gl.bindVertexArray(vao); + } + else { + this.activateVao(geometry, shader.program); + } + } + // TODO - optimise later! + // don't need to loop through if nothing changed! + // maybe look to add an 'autoupdate' to geometry? + this.updateBuffers(); + }; + /** Reset and unbind any active VAO and geometry. */ + GeometrySystem.prototype.reset = function () { + this.unbind(); + }; + /** Update buffers of the currently bound geometry. */ + GeometrySystem.prototype.updateBuffers = function () { + var geometry = this._activeGeometry; + var bufferSystem = this.renderer.buffer; + for (var i = 0; i < geometry.buffers.length; i++) { + var buffer = geometry.buffers[i]; + bufferSystem.update(buffer); + } + }; + /** + * Check compatibility between a geometry and a program + * @param geometry - Geometry instance. + * @param program - Program instance. + */ + GeometrySystem.prototype.checkCompatibility = function (geometry, program) { + // geometry must have at least all the attributes that the shader requires. + var geometryAttributes = geometry.attributes; + var shaderAttributes = program.attributeData; + for (var j in shaderAttributes) { + if (!geometryAttributes[j]) { + throw new Error("shader and geometry incompatible, geometry missing the \"" + j + "\" attribute"); + } + } + }; + /** + * Takes a geometry and program and generates a unique signature for them. + * @param geometry - To get signature from. + * @param program - To test geometry against. + * @returns - Unique signature of the geometry and program + */ + GeometrySystem.prototype.getSignature = function (geometry, program) { + var attribs = geometry.attributes; + var shaderAttributes = program.attributeData; + var strings = ['g', geometry.id]; + for (var i in attribs) { + if (shaderAttributes[i]) { + strings.push(i, shaderAttributes[i].location); + } + } + return strings.join('-'); + }; + /** + * Creates or gets Vao with the same structure as the geometry and stores it on the geometry. + * If vao is created, it is bound automatically. We use a shader to infer what and how to set up the + * attribute locations. + * @param geometry - Instance of geometry to to generate Vao for. + * @param shader - Instance of the shader. + * @param incRefCount - Increment refCount of all geometry buffers. + */ + GeometrySystem.prototype.initGeometryVao = function (geometry, shader, incRefCount) { + if (incRefCount === void 0) { incRefCount = true; } + var gl = this.gl; + var CONTEXT_UID = this.CONTEXT_UID; + var bufferSystem = this.renderer.buffer; + var program = shader.program; + if (!program.glPrograms[CONTEXT_UID]) { + this.renderer.shader.generateProgram(shader); + } + this.checkCompatibility(geometry, program); + var signature = this.getSignature(geometry, program); + var vaoObjectHash = geometry.glVertexArrayObjects[this.CONTEXT_UID]; + var vao = vaoObjectHash[signature]; + if (vao) { + // this will give us easy access to the vao + vaoObjectHash[program.id] = vao; + return vao; + } + var buffers = geometry.buffers; + var attributes = geometry.attributes; + var tempStride = {}; + var tempStart = {}; + for (var j in buffers) { + tempStride[j] = 0; + tempStart[j] = 0; + } + for (var j in attributes) { + if (!attributes[j].size && program.attributeData[j]) { + attributes[j].size = program.attributeData[j].size; + } + else if (!attributes[j].size) { + console.warn("PIXI Geometry attribute '" + j + "' size cannot be determined (likely the bound shader does not have the attribute)"); // eslint-disable-line + } + tempStride[attributes[j].buffer] += attributes[j].size * byteSizeMap[attributes[j].type]; + } + for (var j in attributes) { + var attribute = attributes[j]; + var attribSize = attribute.size; + if (attribute.stride === undefined) { + if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) { + attribute.stride = 0; + } + else { + attribute.stride = tempStride[attribute.buffer]; + } + } + if (attribute.start === undefined) { + attribute.start = tempStart[attribute.buffer]; + tempStart[attribute.buffer] += attribSize * byteSizeMap[attribute.type]; + } + } + vao = gl.createVertexArray(); + gl.bindVertexArray(vao); + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (var i = 0; i < buffers.length; i++) { + var buffer = buffers[i]; + bufferSystem.bind(buffer); + if (incRefCount) { + buffer._glBuffers[CONTEXT_UID].refCount++; + } + } + // TODO - maybe make this a data object? + // lets wait to see if we need to first! + this.activateVao(geometry, program); + this._activeVao = vao; + // add it to the cache! + vaoObjectHash[program.id] = vao; + vaoObjectHash[signature] = vao; + return vao; + }; + /** + * Disposes geometry. + * @param geometry - Geometry with buffers. Only VAO will be disposed + * @param [contextLost=false] - If context was lost, we suppress deleteVertexArray + */ + GeometrySystem.prototype.disposeGeometry = function (geometry, contextLost) { + var _a; + if (!this.managedGeometries[geometry.id]) { + return; + } + delete this.managedGeometries[geometry.id]; + var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; + var gl = this.gl; + var buffers = geometry.buffers; + var bufferSystem = (_a = this.renderer) === null || _a === void 0 ? void 0 : _a.buffer; + geometry.disposeRunner.remove(this); + if (!vaos) { + return; + } + // bufferSystem may have already been destroyed.. + // if this is the case, there is no need to destroy the geometry buffers... + // they already have been! + if (bufferSystem) { + for (var i = 0; i < buffers.length; i++) { + var buf = buffers[i]._glBuffers[this.CONTEXT_UID]; + // my be null as context may have changed right before the dispose is called + if (buf) { + buf.refCount--; + if (buf.refCount === 0 && !contextLost) { + bufferSystem.dispose(buffers[i], contextLost); + } + } + } + } + if (!contextLost) { + for (var vaoId in vaos) { + // delete only signatures, everything else are copies + if (vaoId[0] === 'g') { + var vao = vaos[vaoId]; + if (this._activeVao === vao) { + this.unbind(); + } + gl.deleteVertexArray(vao); + } + } + } + delete geometry.glVertexArrayObjects[this.CONTEXT_UID]; + }; + /** + * Dispose all WebGL resources of all managed geometries. + * @param [contextLost=false] - If context was lost, we suppress `gl.delete` calls + */ + GeometrySystem.prototype.disposeAll = function (contextLost) { + var all = Object.keys(this.managedGeometries); + for (var i = 0; i < all.length; i++) { + this.disposeGeometry(this.managedGeometries[all[i]], contextLost); + } + }; + /** + * Activate vertex array object. + * @param geometry - Geometry instance. + * @param program - Shader program instance. + */ + GeometrySystem.prototype.activateVao = function (geometry, program) { + var gl = this.gl; + var CONTEXT_UID = this.CONTEXT_UID; + var bufferSystem = this.renderer.buffer; + var buffers = geometry.buffers; + var attributes = geometry.attributes; + if (geometry.indexBuffer) { + // first update the index buffer if we have one.. + bufferSystem.bind(geometry.indexBuffer); + } + var lastBuffer = null; + // add a new one! + for (var j in attributes) { + var attribute = attributes[j]; + var buffer = buffers[attribute.buffer]; + var glBuffer = buffer._glBuffers[CONTEXT_UID]; + if (program.attributeData[j]) { + if (lastBuffer !== glBuffer) { + bufferSystem.bind(buffer); + lastBuffer = glBuffer; + } + var location = program.attributeData[j].location; + // TODO introduce state again + // we can optimise this for older devices that have no VAOs + gl.enableVertexAttribArray(location); + gl.vertexAttribPointer(location, attribute.size, attribute.type || gl.FLOAT, attribute.normalized, attribute.stride, attribute.start); + if (attribute.instance) { + // TODO calculate instance count based of this... + if (this.hasInstance) { + gl.vertexAttribDivisor(location, 1); + } + else { + throw new Error('geometry error, GPU Instancing is not supported on this device'); + } + } + } + } + }; + /** + * Draws the currently bound geometry. + * @param type - The type primitive to render. + * @param size - The number of elements to be rendered. If not specified, all vertices after the + * starting vertex will be drawn. + * @param start - The starting vertex in the geometry to start drawing from. If not specified, + * drawing will start from the first vertex. + * @param instanceCount - The number of instances of the set of elements to execute. If not specified, + * all instances will be drawn. + */ + GeometrySystem.prototype.draw = function (type, size, start, instanceCount) { + var gl = this.gl; + var geometry = this._activeGeometry; + // TODO.. this should not change so maybe cache the function? + if (geometry.indexBuffer) { + var byteSize = geometry.indexBuffer.data.BYTES_PER_ELEMENT; + var glType = byteSize === 2 ? gl.UNSIGNED_SHORT : gl.UNSIGNED_INT; + if (byteSize === 2 || (byteSize === 4 && this.canUseUInt32ElementIndex)) { + if (geometry.instanced) { + /* eslint-disable max-len */ + gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize, instanceCount || 1); + /* eslint-enable max-len */ + } + else { + /* eslint-disable max-len */ + gl.drawElements(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize); + /* eslint-enable max-len */ + } + } + else { + console.warn('unsupported index buffer type: uint32'); + } + } + else if (geometry.instanced) { + // TODO need a better way to calculate size.. + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } + else { + gl.drawArrays(type, start, size || geometry.getSize()); + } + return this; + }; + /** Unbind/reset everything. */ + GeometrySystem.prototype.unbind = function () { + this.gl.bindVertexArray(null); + this._activeVao = null; + this._activeGeometry = null; + }; + GeometrySystem.prototype.destroy = function () { + this.renderer = null; + }; + return GeometrySystem; + }()); -/** - * @class - * @extends PIXI.Shader - * @memberof PIXI - */ -var ParticleShader = function (_Shader) { - _inherits(ParticleShader, _Shader); - - /** - * @param {PIXI.Shader} gl - The webgl shader manager this shader works for. - */ - function ParticleShader(gl) { - _classCallCheck(this, ParticleShader); - - return _possibleConstructorReturn(this, _Shader.call(this, gl, - // vertex shader - ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'attribute float aColor;', 'attribute vec2 aPositionCoord;', 'attribute vec2 aScale;', 'attribute float aRotation;', 'uniform mat3 projectionMatrix;', 'varying vec2 vTextureCoord;', 'varying float vColor;', 'void main(void){', ' vec2 v = aVertexPosition;', ' v.x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);', ' v.y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);', ' v = v + aPositionCoord;', ' gl_Position = vec4((projectionMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = aColor;', '}'].join('\n'), - // hello - ['varying vec2 vTextureCoord;', 'varying float vColor;', 'uniform sampler2D uSampler;', 'uniform vec4 uColor;', 'void main(void){', ' vec4 color = texture2D(uSampler, vTextureCoord) * vColor * uColor;', ' if (color.a == 0.0) discard;', ' gl_FragColor = color;', '}'].join('\n'))); - } + /** + * Component for masked elements. + * + * Holds mask mode and temporary data about current mask. + * @memberof PIXI + */ + var MaskData = /** @class */ (function () { + /** + * Create MaskData + * @param {PIXI.DisplayObject} [maskObject=null] - object that describes the mask + */ + function MaskData(maskObject) { + if (maskObject === void 0) { maskObject = null; } + this.type = exports.MASK_TYPES.NONE; + this.autoDetect = true; + this.maskObject = maskObject || null; + this.pooled = false; + this.isMaskData = true; + this.resolution = null; + this.multisample = settings.FILTER_MULTISAMPLE; + this.enabled = true; + this.colorMask = 0xf; + this._filters = null; + this._stencilCounter = 0; + this._scissorCounter = 0; + this._scissorRect = null; + this._scissorRectLocal = null; + this._colorMask = 0xf; + this._target = null; + } + Object.defineProperty(MaskData.prototype, "filter", { + /** + * The sprite mask filter. + * If set to `null`, the default sprite mask filter is used. + * @default null + */ + get: function () { + return this._filters ? this._filters[0] : null; + }, + set: function (value) { + if (value) { + if (this._filters) { + this._filters[0] = value; + } + else { + this._filters = [value]; + } + } + else { + this._filters = null; + } + }, + enumerable: false, + configurable: true + }); + /** Resets the mask data after popMask(). */ + MaskData.prototype.reset = function () { + if (this.pooled) { + this.maskObject = null; + this.type = exports.MASK_TYPES.NONE; + this.autoDetect = true; + } + this._target = null; + this._scissorRectLocal = null; + }; + /** + * Copies counters from maskData above, called from pushMask(). + * @param maskAbove + */ + MaskData.prototype.copyCountersOrReset = function (maskAbove) { + if (maskAbove) { + this._stencilCounter = maskAbove._stencilCounter; + this._scissorCounter = maskAbove._scissorCounter; + this._scissorRect = maskAbove._scissorRect; + } + else { + this._stencilCounter = 0; + this._scissorCounter = 0; + this._scissorRect = null; + } + }; + return MaskData; + }()); - return ParticleShader; -}(_Shader3.default); + /** + * @private + * @param {WebGLRenderingContext} gl - The current WebGL context {WebGLProgram} + * @param {number} type - the type, can be either VERTEX_SHADER or FRAGMENT_SHADER + * @param {string} src - The vertex shader source as an array of strings. + * @returns {WebGLShader} the shader + */ + function compileShader(gl, type, src) { + var shader = gl.createShader(type); + gl.shaderSource(shader, src); + gl.compileShader(shader); + return shader; + } -exports.default = ParticleShader; + /** + * will log a shader error highlighting the lines with the error + * also will add numbers along the side. + * @param gl - the WebGLContext + * @param shader - the shader to log errors for + */ + function logPrettyShaderError(gl, shader) { + var shaderSrc = gl.getShaderSource(shader) + .split('\n') + .map(function (line, index) { return index + ": " + line; }); + var shaderLog = gl.getShaderInfoLog(shader); + var splitShader = shaderLog.split('\n'); + var dedupe = {}; + var lineNumbers = splitShader.map(function (line) { return parseFloat(line.replace(/^ERROR\: 0\:([\d]+)\:.*$/, '$1')); }) + .filter(function (n) { + if (n && !dedupe[n]) { + dedupe[n] = true; + return true; + } + return false; + }); + var logArgs = ['']; + lineNumbers.forEach(function (number) { + shaderSrc[number - 1] = "%c" + shaderSrc[number - 1] + "%c"; + logArgs.push('background: #FF0000; color:#FFFFFF; font-size: 10px', 'font-size: 10px'); + }); + var fragmentSourceToLog = shaderSrc + .join('\n'); + logArgs[0] = fragmentSourceToLog; + console.error(shaderLog); + // eslint-disable-next-line no-console + console.groupCollapsed('click to view full shader code'); + console.warn.apply(console, logArgs); + // eslint-disable-next-line no-console + console.groupEnd(); + } + /** + * + * logs out any program errors + * @param gl - The current WebGL context + * @param program - the WebGL program to display errors for + * @param vertexShader - the fragment WebGL shader program + * @param fragmentShader - the vertex WebGL shader program + */ + function logProgramError(gl, program, vertexShader, fragmentShader) { + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) { + logPrettyShaderError(gl, vertexShader); + } + if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) { + logPrettyShaderError(gl, fragmentShader); + } + console.error('PixiJS Error: Could not initialize shader.'); + // if there is a program info log, log it + if (gl.getProgramInfoLog(program) !== '') { + console.warn('PixiJS Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + } + } + } -},{"../../core/Shader":44}],178:[function(require,module,exports){ -"use strict"; + function booleanArray(size) { + var array = new Array(size); + for (var i = 0; i < array.length; i++) { + array[i] = false; + } + return array; + } + /** + * @method defaultValue + * @memberof PIXI.glCore.shader + * @param {string} type - Type of value + * @param {number} size + * @private + */ + function defaultValue(type, size) { + switch (type) { + case 'float': + return 0; + case 'vec2': + return new Float32Array(2 * size); + case 'vec3': + return new Float32Array(3 * size); + case 'vec4': + return new Float32Array(4 * size); + case 'int': + case 'uint': + case 'sampler2D': + case 'sampler2DArray': + return 0; + case 'ivec2': + return new Int32Array(2 * size); + case 'ivec3': + return new Int32Array(3 * size); + case 'ivec4': + return new Int32Array(4 * size); + case 'uvec2': + return new Uint32Array(2 * size); + case 'uvec3': + return new Uint32Array(3 * size); + case 'uvec4': + return new Uint32Array(4 * size); + case 'bool': + return false; + case 'bvec2': + return booleanArray(2 * size); + case 'bvec3': + return booleanArray(3 * size); + case 'bvec4': + return booleanArray(4 * size); + case 'mat2': + return new Float32Array([1, 0, + 0, 1]); + case 'mat3': + return new Float32Array([1, 0, 0, + 0, 1, 0, + 0, 0, 1]); + case 'mat4': + return new Float32Array([1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); + } + return null; + } -// References: -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + var unknownContext = {}; + var context = unknownContext; + /** + * returns a little WebGL context to use for program inspection. + * @static + * @private + * @returns {WebGLRenderingContext} a gl context to test with + */ + function getTestContext() { + if (context === unknownContext || (context && context.isContextLost())) { + var canvas = settings.ADAPTER.createCanvas(); + var gl = void 0; + if (settings.PREFER_ENV >= exports.ENV.WEBGL2) { + gl = canvas.getContext('webgl2', {}); + } + if (!gl) { + gl = (canvas.getContext('webgl', {}) + || canvas.getContext('experimental-webgl', {})); + if (!gl) { + // fail, not able to get a context + gl = null; + } + else { + // for shader testing.. + gl.getExtension('WEBGL_draw_buffers'); + } + } + context = gl; + } + return context; + } -if (!Math.sign) { - Math.sign = function mathSign(x) { - x = Number(x); + var maxFragmentPrecision; + function getMaxFragmentPrecision() { + if (!maxFragmentPrecision) { + maxFragmentPrecision = exports.PRECISION.MEDIUM; + var gl = getTestContext(); + if (gl) { + if (gl.getShaderPrecisionFormat) { + var shaderFragment = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT); + maxFragmentPrecision = shaderFragment.precision ? exports.PRECISION.HIGH : exports.PRECISION.MEDIUM; + } + } + } + return maxFragmentPrecision; + } - if (x === 0 || isNaN(x)) { - return x; - } + /** + * Sets the float precision on the shader, ensuring the device supports the request precision. + * If the precision is already present, it just ensures that the device is able to handle it. + * @private + * @param {string} src - The shader source + * @param {PIXI.PRECISION} requestedPrecision - The request float precision of the shader. + * @param {PIXI.PRECISION} maxSupportedPrecision - The maximum precision the shader supports. + * @returns {string} modified shader source + */ + function setPrecision(src, requestedPrecision, maxSupportedPrecision) { + if (src.substring(0, 9) !== 'precision') { + // no precision supplied, so PixiJS will add the requested level. + var precision = requestedPrecision; + // If highp is requested but not supported, downgrade precision to a level all devices support. + if (requestedPrecision === exports.PRECISION.HIGH && maxSupportedPrecision !== exports.PRECISION.HIGH) { + precision = exports.PRECISION.MEDIUM; + } + return "precision " + precision + " float;\n" + src; + } + else if (maxSupportedPrecision !== exports.PRECISION.HIGH && src.substring(0, 15) === 'precision highp') { + // precision was supplied, but at a level this device does not support, so downgrading to mediump. + return src.replace('precision highp', 'precision mediump'); + } + return src; + } - return x > 0 ? 1 : -1; - }; -} + var GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + uint: 1, + uvec2: 2, + uvec3: 3, + uvec4: 4, + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + mat2: 4, + mat3: 9, + mat4: 16, + sampler2D: 1, + }; + /** + * @private + * @method mapSize + * @memberof PIXI.glCore.shader + * @param {string} type + */ + function mapSize(type) { + return GLSL_TO_SIZE[type]; + } -},{}],179:[function(require,module,exports){ -'use strict'; + var GL_TABLE = null; + var GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + UNSIGNED_INT: 'uint', + UNSIGNED_INT_VEC2: 'uvec2', + UNSIGNED_INT_VEC3: 'uvec3', + UNSIGNED_INT_VEC4: 'uvec4', + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + SAMPLER_2D: 'sampler2D', + INT_SAMPLER_2D: 'sampler2D', + UNSIGNED_INT_SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + INT_SAMPLER_CUBE: 'samplerCube', + UNSIGNED_INT_SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', + INT_SAMPLER_2D_ARRAY: 'sampler2DArray', + UNSIGNED_INT_SAMPLER_2D_ARRAY: 'sampler2DArray', + }; + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + function mapType(gl, type) { + if (!GL_TABLE) { + var typeNames = Object.keys(GL_TO_GLSL_TYPES); + GL_TABLE = {}; + for (var i = 0; i < typeNames.length; ++i) { + var tn = typeNames[i]; + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; + } + } + return GL_TABLE[type]; + } -var _objectAssign = require('object-assign'); + /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ + // Parsers, each one of these will take a look at the type of shader property and uniform. + // if they pass the test function then the code function is called that returns a the shader upload code for that uniform. + // Shader upload code is automagically generated with these parsers. + // If no parser is valid then the default upload functions are used. + // exposing Parsers means that custom upload logic can be added to pixi's shaders. + // A good example would be a pixi rectangle can be directly set on a uniform. + // If the shader sees it it knows how to upload the rectangle structure as a vec4 + // format is as follows: + // + // { + // test: (data, uniform) => {} <--- test is this code should be used for this uniform + // code: (name, uniform) => {} <--- returns the string of the piece of code that uploads the uniform + // codeUbo: (name, uniform) => {} <--- returns the string of the piece of code that uploads the + // uniform to a uniform buffer + // } + var uniformParsers = [ + // a float cache layer + { + test: function (data) { + return data.type === 'float' && data.size === 1 && !data.isArray; + }, + code: function (name) { + return "\n if(uv[\"" + name + "\"] !== ud[\"" + name + "\"].value)\n {\n ud[\"" + name + "\"].value = uv[\"" + name + "\"]\n gl.uniform1f(ud[\"" + name + "\"].location, uv[\"" + name + "\"])\n }\n "; + }, + }, + // handling samplers + { + test: function (data, uniform) { + // eslint-disable-next-line max-len,no-eq-null,eqeqeq + return (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray && (uniform == null || uniform.castToBaseTexture !== undefined); + }, + code: function (name) { return "t = syncData.textureCount++;\n\n renderer.texture.bind(uv[\"" + name + "\"], t);\n\n if(ud[\"" + name + "\"].value !== t)\n {\n ud[\"" + name + "\"].value = t;\n gl.uniform1i(ud[\"" + name + "\"].location, t);\n; // eslint-disable-line max-len\n }"; }, + }, + // uploading pixi matrix object to mat3 + { + test: function (data, uniform) { + return data.type === 'mat3' && data.size === 1 && !data.isArray && uniform.a !== undefined; + }, + code: function (name) { + // TODO and some smart caching dirty ids here! + return "\n gl.uniformMatrix3fv(ud[\"" + name + "\"].location, false, uv[\"" + name + "\"].toArray(true));\n "; + }, + codeUbo: function (name) { + return "\n var " + name + "_matrix = uv." + name + ".toArray(true);\n\n data[offset] = " + name + "_matrix[0];\n data[offset+1] = " + name + "_matrix[1];\n data[offset+2] = " + name + "_matrix[2];\n \n data[offset + 4] = " + name + "_matrix[3];\n data[offset + 5] = " + name + "_matrix[4];\n data[offset + 6] = " + name + "_matrix[5];\n \n data[offset + 8] = " + name + "_matrix[6];\n data[offset + 9] = " + name + "_matrix[7];\n data[offset + 10] = " + name + "_matrix[8];\n "; + }, + }, + // uploading a pixi point as a vec2 with caching layer + { + test: function (data, uniform) { + return data.type === 'vec2' && data.size === 1 && !data.isArray && uniform.x !== undefined; + }, + code: function (name) { + return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v.x || cv[1] !== v.y)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n gl.uniform2f(ud[\"" + name + "\"].location, v.x, v.y);\n }"; + }, + codeUbo: function (name) { + return "\n v = uv." + name + ";\n\n data[offset] = v.x;\n data[offset+1] = v.y;\n "; + } + }, + // caching layer for a vec2 + { + test: function (data) { + return data.type === 'vec2' && data.size === 1 && !data.isArray; + }, + code: function (name) { + return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n gl.uniform2f(ud[\"" + name + "\"].location, v[0], v[1]);\n }\n "; + }, + }, + // upload a pixi rectangle as a vec4 with caching layer + { + test: function (data, uniform) { + return data.type === 'vec4' && data.size === 1 && !data.isArray && uniform.width !== undefined; + }, + code: function (name) { + return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.width || cv[3] !== v.height)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n cv[2] = v.width;\n cv[3] = v.height;\n gl.uniform4f(ud[\"" + name + "\"].location, v.x, v.y, v.width, v.height)\n }"; + }, + codeUbo: function (name) { + return "\n v = uv." + name + ";\n\n data[offset] = v.x;\n data[offset+1] = v.y;\n data[offset+2] = v.width;\n data[offset+3] = v.height;\n "; + } + }, + // a caching layer for vec4 uploading + { + test: function (data) { + return data.type === 'vec4' && data.size === 1 && !data.isArray; + }, + code: function (name) { + return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(ud[\"" + name + "\"].location, v[0], v[1], v[2], v[3])\n }"; + }, + } ]; + + // cu = Cached value's uniform data field + // cv = Cached value + // v = value to upload + // ud = uniformData + // uv = uniformValue + // l = location + var GLSL_TO_SINGLE_SETTERS_CACHED = { + float: "\n if (cv !== v)\n {\n cu.value = v;\n gl.uniform1f(location, v);\n }", + vec2: "\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2f(location, v[0], v[1])\n }", + vec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3f(location, v[0], v[1], v[2])\n }", + vec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(location, v[0], v[1], v[2], v[3]);\n }", + int: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }", + ivec2: "\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2i(location, v[0], v[1]);\n }", + ivec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3i(location, v[0], v[1], v[2]);\n }", + ivec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n }", + uint: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1ui(location, v);\n }", + uvec2: "\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2ui(location, v[0], v[1]);\n }", + uvec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3ui(location, v[0], v[1], v[2]);\n }", + uvec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4ui(location, v[0], v[1], v[2], v[3]);\n }", + bool: "\n if (cv !== v)\n {\n cu.value = v;\n gl.uniform1i(location, v);\n }", + bvec2: "\n if (cv[0] != v[0] || cv[1] != v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2i(location, v[0], v[1]);\n }", + bvec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3i(location, v[0], v[1], v[2]);\n }", + bvec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n }", + mat2: 'gl.uniformMatrix2fv(location, false, v)', + mat3: 'gl.uniformMatrix3fv(location, false, v)', + mat4: 'gl.uniformMatrix4fv(location, false, v)', + sampler2D: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }", + samplerCube: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }", + sampler2DArray: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }", + }; + var GLSL_TO_ARRAY_SETTERS = { + float: "gl.uniform1fv(location, v)", + vec2: "gl.uniform2fv(location, v)", + vec3: "gl.uniform3fv(location, v)", + vec4: 'gl.uniform4fv(location, v)', + mat4: 'gl.uniformMatrix4fv(location, false, v)', + mat3: 'gl.uniformMatrix3fv(location, false, v)', + mat2: 'gl.uniformMatrix2fv(location, false, v)', + int: 'gl.uniform1iv(location, v)', + ivec2: 'gl.uniform2iv(location, v)', + ivec3: 'gl.uniform3iv(location, v)', + ivec4: 'gl.uniform4iv(location, v)', + uint: 'gl.uniform1uiv(location, v)', + uvec2: 'gl.uniform2uiv(location, v)', + uvec3: 'gl.uniform3uiv(location, v)', + uvec4: 'gl.uniform4uiv(location, v)', + bool: 'gl.uniform1iv(location, v)', + bvec2: 'gl.uniform2iv(location, v)', + bvec3: 'gl.uniform3iv(location, v)', + bvec4: 'gl.uniform4iv(location, v)', + sampler2D: 'gl.uniform1iv(location, v)', + samplerCube: 'gl.uniform1iv(location, v)', + sampler2DArray: 'gl.uniform1iv(location, v)', + }; + function generateUniformsSync(group, uniformData) { + var _a; + var funcFragments = ["\n var v = null;\n var cv = null;\n var cu = null;\n var t = 0;\n var gl = renderer.gl;\n "]; + for (var i in group.uniforms) { + var data = uniformData[i]; + if (!data) { + if ((_a = group.uniforms[i]) === null || _a === void 0 ? void 0 : _a.group) { + if (group.uniforms[i].ubo) { + funcFragments.push("\n renderer.shader.syncUniformBufferGroup(uv." + i + ", '" + i + "');\n "); + } + else { + funcFragments.push("\n renderer.shader.syncUniformGroup(uv." + i + ", syncData);\n "); + } + } + continue; + } + var uniform = group.uniforms[i]; + var parsed = false; + for (var j = 0; j < uniformParsers.length; j++) { + if (uniformParsers[j].test(data, uniform)) { + funcFragments.push(uniformParsers[j].code(i, uniform)); + parsed = true; + break; + } + } + if (!parsed) { + var templateType = data.size === 1 && !data.isArray ? GLSL_TO_SINGLE_SETTERS_CACHED : GLSL_TO_ARRAY_SETTERS; + var template = templateType[data.type].replace('location', "ud[\"" + i + "\"].location"); + funcFragments.push("\n cu = ud[\"" + i + "\"];\n cv = cu.value;\n v = uv[\"" + i + "\"];\n " + template + ";"); + } + } + /* + * the introduction of syncData is to solve an issue where textures in uniform groups are not set correctly + * the texture count was always starting from 0 in each group. This needs to increment each time a texture is used + * no matter which group is being used + * + */ + // eslint-disable-next-line no-new-func + return new Function('ud', 'uv', 'renderer', 'syncData', funcFragments.join('\n')); + } -var _objectAssign2 = _interopRequireDefault(_objectAssign); + var fragTemplate$1 = [ + 'precision mediump float;', + 'void main(void){', + 'float test = 0.1;', + '%forloop%', + 'gl_FragColor = vec4(0.0);', + '}' ].join('\n'); + function generateIfTestSrc(maxIfs) { + var src = ''; + for (var i = 0; i < maxIfs; ++i) { + if (i > 0) { + src += '\nelse '; + } + if (i < maxIfs - 1) { + src += "if(test == " + i + ".0){}"; + } + } + return src; + } + function checkMaxIfStatementsInShader(maxIfs, gl) { + if (maxIfs === 0) { + throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); + } + var shader = gl.createShader(gl.FRAGMENT_SHADER); + while (true) // eslint-disable-line no-constant-condition + { + var fragmentSrc = fragTemplate$1.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + maxIfs = (maxIfs / 2) | 0; + } + else { + // valid! + break; + } + } + return maxIfs; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // Cache the result to prevent running this over and over + var unsafeEval; + /** + * Not all platforms allow to generate function code (e.g., `new Function`). + * this provides the platform-level detection. + * @private + * @returns {boolean} `true` if `new Function` is supported. + */ + function unsafeEvalSupported() { + if (typeof unsafeEval === 'boolean') { + return unsafeEval; + } + try { + /* eslint-disable no-new-func */ + var func = new Function('param1', 'param2', 'param3', 'return param1[param2] === param3;'); + /* eslint-enable no-new-func */ + unsafeEval = func({ a: 'b' }, 'a', 'b') === true; + } + catch (e) { + unsafeEval = false; + } + return unsafeEval; + } -if (!Object.assign) { - Object.assign = _objectAssign2.default; -} // References: -// https://github.com/sindresorhus/object-assign -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + var defaultFragment$2 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor *= texture2D(uSampler, vTextureCoord);\n}"; -},{"object-assign":5}],180:[function(require,module,exports){ -'use strict'; + var defaultVertex$3 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}\n"; -require('./Object.assign'); + var UID$1 = 0; + var nameCache = {}; + /** + * Helper class to create a shader program. + * @memberof PIXI + */ + var Program = /** @class */ (function () { + /** + * @param vertexSrc - The source of the vertex shader. + * @param fragmentSrc - The source of the fragment shader. + * @param name - Name for shader + */ + function Program(vertexSrc, fragmentSrc, name) { + if (name === void 0) { name = 'pixi-shader'; } + this.id = UID$1++; + this.vertexSrc = vertexSrc || Program.defaultVertexSrc; + this.fragmentSrc = fragmentSrc || Program.defaultFragmentSrc; + this.vertexSrc = this.vertexSrc.trim(); + this.fragmentSrc = this.fragmentSrc.trim(); + if (this.vertexSrc.substring(0, 8) !== '#version') { + name = name.replace(/\s+/g, '-'); + if (nameCache[name]) { + nameCache[name]++; + name += "-" + nameCache[name]; + } + else { + nameCache[name] = 1; + } + this.vertexSrc = "#define SHADER_NAME " + name + "\n" + this.vertexSrc; + this.fragmentSrc = "#define SHADER_NAME " + name + "\n" + this.fragmentSrc; + this.vertexSrc = setPrecision(this.vertexSrc, settings.PRECISION_VERTEX, exports.PRECISION.HIGH); + this.fragmentSrc = setPrecision(this.fragmentSrc, settings.PRECISION_FRAGMENT, getMaxFragmentPrecision()); + } + // currently this does not extract structs only default types + // this is where we store shader references.. + this.glPrograms = {}; + this.syncUniforms = null; + } + Object.defineProperty(Program, "defaultVertexSrc", { + /** + * The default vertex shader source. + * @constant + */ + get: function () { + return defaultVertex$3; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Program, "defaultFragmentSrc", { + /** + * The default fragment shader source. + * @constant + */ + get: function () { + return defaultFragment$2; + }, + enumerable: false, + configurable: true + }); + /** + * A short hand function to create a program based of a vertex and fragment shader. + * + * This method will also check to see if there is a cached program. + * @param vertexSrc - The source of the vertex shader. + * @param fragmentSrc - The source of the fragment shader. + * @param name - Name for shader + * @returns A shiny new PixiJS shader program! + */ + Program.from = function (vertexSrc, fragmentSrc, name) { + var key = vertexSrc + fragmentSrc; + var program = ProgramCache[key]; + if (!program) { + ProgramCache[key] = program = new Program(vertexSrc, fragmentSrc, name); + } + return program; + }; + return Program; + }()); -require('./requestAnimationFrame'); + /** + * A helper class for shaders. + * @memberof PIXI + */ + var Shader = /** @class */ (function () { + /** + * @param program - The program the shader will use. + * @param uniforms - Custom uniforms to use to augment the built-in ones. + */ + function Shader(program, uniforms) { + /** + * Used internally to bind uniform buffer objects. + * @ignore + */ + this.uniformBindCount = 0; + this.program = program; + // lets see whats been passed in + // uniforms should be converted to a uniform group + if (uniforms) { + if (uniforms instanceof UniformGroup) { + this.uniformGroup = uniforms; + } + else { + this.uniformGroup = new UniformGroup(uniforms); + } + } + else { + this.uniformGroup = new UniformGroup({}); + } + this.disposeRunner = new Runner('disposeShader'); + } + // TODO move to shader system.. + Shader.prototype.checkUniformExists = function (name, group) { + if (group.uniforms[name]) { + return true; + } + for (var i in group.uniforms) { + var uniform = group.uniforms[i]; + if (uniform.group) { + if (this.checkUniformExists(name, uniform)) { + return true; + } + } + } + return false; + }; + Shader.prototype.destroy = function () { + // usage count on programs? + // remove if not used! + this.uniformGroup = null; + this.disposeRunner.emit(this); + this.disposeRunner.destroy(); + }; + Object.defineProperty(Shader.prototype, "uniforms", { + /** + * Shader uniform values, shortcut for `uniformGroup.uniforms`. + * @readonly + */ + get: function () { + return this.uniformGroup.uniforms; + }, + enumerable: false, + configurable: true + }); + /** + * A short hand function to create a shader based of a vertex and fragment shader. + * @param vertexSrc - The source of the vertex shader. + * @param fragmentSrc - The source of the fragment shader. + * @param uniforms - Custom uniforms to use to augment the built-in ones. + * @returns A shiny new PixiJS shader! + */ + Shader.from = function (vertexSrc, fragmentSrc, uniforms) { + var program = Program.from(vertexSrc, fragmentSrc); + return new Shader(program, uniforms); + }; + return Shader; + }()); + + /* eslint-disable max-len */ + var BLEND$1 = 0; + var OFFSET$1 = 1; + var CULLING$1 = 2; + var DEPTH_TEST$1 = 3; + var WINDING$1 = 4; + var DEPTH_MASK$1 = 5; + /** + * This is a WebGL state, and is is passed to {@link PIXI.StateSystem}. + * + * Each mesh rendered may require WebGL to be in a different state. + * For example you may want different blend mode or to enable polygon offsets + * @memberof PIXI + */ + var State = /** @class */ (function () { + function State() { + this.data = 0; + this.blendMode = exports.BLEND_MODES.NORMAL; + this.polygonOffset = 0; + this.blend = true; + this.depthMask = true; + // this.depthTest = true; + } + Object.defineProperty(State.prototype, "blend", { + /** + * Activates blending of the computed fragment color values. + * @default true + */ + get: function () { + return !!(this.data & (1 << BLEND$1)); + }, + set: function (value) { + if (!!(this.data & (1 << BLEND$1)) !== value) { + this.data ^= (1 << BLEND$1); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "offsets", { + /** + * Activates adding an offset to depth values of polygon's fragments + * @default false + */ + get: function () { + return !!(this.data & (1 << OFFSET$1)); + }, + set: function (value) { + if (!!(this.data & (1 << OFFSET$1)) !== value) { + this.data ^= (1 << OFFSET$1); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "culling", { + /** + * Activates culling of polygons. + * @default false + */ + get: function () { + return !!(this.data & (1 << CULLING$1)); + }, + set: function (value) { + if (!!(this.data & (1 << CULLING$1)) !== value) { + this.data ^= (1 << CULLING$1); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "depthTest", { + /** + * Activates depth comparisons and updates to the depth buffer. + * @default false + */ + get: function () { + return !!(this.data & (1 << DEPTH_TEST$1)); + }, + set: function (value) { + if (!!(this.data & (1 << DEPTH_TEST$1)) !== value) { + this.data ^= (1 << DEPTH_TEST$1); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "depthMask", { + /** + * Enables or disables writing to the depth buffer. + * @default true + */ + get: function () { + return !!(this.data & (1 << DEPTH_MASK$1)); + }, + set: function (value) { + if (!!(this.data & (1 << DEPTH_MASK$1)) !== value) { + this.data ^= (1 << DEPTH_MASK$1); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "clockwiseFrontFace", { + /** + * Specifies whether or not front or back-facing polygons can be culled. + * @default false + */ + get: function () { + return !!(this.data & (1 << WINDING$1)); + }, + set: function (value) { + if (!!(this.data & (1 << WINDING$1)) !== value) { + this.data ^= (1 << WINDING$1); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "blendMode", { + /** + * The blend mode to be applied when this state is set. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * Setting this mode to anything other than NO_BLEND will automatically switch blending on. + * @default PIXI.BLEND_MODES.NORMAL + */ + get: function () { + return this._blendMode; + }, + set: function (value) { + this.blend = (value !== exports.BLEND_MODES.NONE); + this._blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "polygonOffset", { + /** + * The polygon offset. Setting this property to anything other than 0 will automatically enable polygon offset fill. + * @default 0 + */ + get: function () { + return this._polygonOffset; + }, + set: function (value) { + this.offsets = !!value; + this._polygonOffset = value; + }, + enumerable: false, + configurable: true + }); + State.prototype.toString = function () { + return "[@pixi/core:State " + + ("blendMode=" + this.blendMode + " ") + + ("clockwiseFrontFace=" + this.clockwiseFrontFace + " ") + + ("culling=" + this.culling + " ") + + ("depthMask=" + this.depthMask + " ") + + ("polygonOffset=" + this.polygonOffset) + + "]"; + }; + State.for2d = function () { + var state = new State(); + state.depthTest = false; + state.blend = true; + return state; + }; + return State; + }()); + + var defaultFragment$1 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n"; + + var defaultVertex$2 = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"; -require('./Math.sign'); + /** + * A filter is a special shader that applies post-processing effects to an input texture and writes into an output + * render-target. + * + * {@link http://pixijs.io/examples/#/filters/blur-filter.js Example} of the + * {@link PIXI.filters.BlurFilter BlurFilter}. + * + * ### Usage + * Filters can be applied to any DisplayObject or Container. + * PixiJS' `FilterSystem` renders the container into temporary Framebuffer, + * then filter renders it to the screen. + * Multiple filters can be added to the `filters` array property and stacked on each other. + * + * ``` + * const filter = new PIXI.Filter(myShaderVert, myShaderFrag, { myUniform: 0.5 }); + * const container = new PIXI.Container(); + * container.filters = [filter]; + * ``` + * + * ### Previous Version Differences + * + * In PixiJS **v3**, a filter was always applied to _whole screen_. + * + * In PixiJS **v4**, a filter can be applied _only part of the screen_. + * Developers had to create a set of uniforms to deal with coordinates. + * + * In PixiJS **v5** combines _both approaches_. + * Developers can use normal coordinates of v3 and then allow filter to use partial Framebuffers, + * bringing those extra uniforms into account. + * + * Also be aware that we have changed default vertex shader, please consult + * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}. + * + * ### Frames + * + * The following table summarizes the coordinate spaces used in the filtering pipeline: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Coordinate SpaceDescription
Texture Coordinates + * The texture (or UV) coordinates in the input base-texture's space. These are normalized into the (0,1) range along + * both axes. + *
World Space + * A point in the same space as the world bounds of any display-object (i.e. in the scene graph's space). + *
Physical Pixels + * This is base-texture's space with the origin on the top-left. You can calculate these by multiplying the texture + * coordinates by the dimensions of the texture. + *
+ * + * ### Built-in Uniforms + * + * PixiJS viewport uses screen (CSS) coordinates, `(0, 0, renderer.screen.width, renderer.screen.height)`, + * and `projectionMatrix` uniform maps it to the gl viewport. + * + * **uSampler** + * + * The most important uniform is the input texture that container was rendered into. + * _Important note: as with all Framebuffers in PixiJS, both input and output are + * premultiplied by alpha._ + * + * By default, input normalized coordinates are passed to fragment shader with `vTextureCoord`. + * Use it to sample the input. + * + * ``` + * const fragment = ` + * varying vec2 vTextureCoord; + * uniform sampler2D uSampler; + * void main(void) + * { + * gl_FragColor = texture2D(uSampler, vTextureCoord); + * } + * `; + * + * const myFilter = new PIXI.Filter(null, fragment); + * ``` + * + * This filter is just one uniform less than {@link PIXI.filters.AlphaFilter AlphaFilter}. + * + * **outputFrame** + * + * The `outputFrame` holds the rectangle where filter is applied in screen (CSS) coordinates. + * It's the same as `renderer.screen` for a fullscreen filter. + * Only a part of `outputFrame.zw` size of temporary Framebuffer is used, + * `(0, 0, outputFrame.width, outputFrame.height)`, + * + * Filters uses this quad to normalized (0-1) space, its passed into `aVertexPosition` attribute. + * To calculate vertex position in screen space using normalized (0-1) space: + * + * ``` + * vec4 filterVertexPosition( void ) + * { + * vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy; + * return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0); + * } + * ``` + * + * **inputSize** + * + * Temporary framebuffer is different, it can be either the size of screen, either power-of-two. + * The `inputSize.xy` are size of temporary framebuffer that holds input. + * The `inputSize.zw` is inverted, it's a shortcut to evade division inside the shader. + * + * Set `inputSize.xy = outputFrame.zw` for a fullscreen filter. + * + * To calculate input normalized coordinate, you have to map it to filter normalized space. + * Multiply by `outputFrame.zw` to get input coordinate. + * Divide by `inputSize.xy` to get input normalized coordinate. + * + * ``` + * vec2 filterTextureCoord( void ) + * { + * return aVertexPosition * (outputFrame.zw * inputSize.zw); // same as /inputSize.xy + * } + * ``` + * **resolution** + * + * The `resolution` is the ratio of screen (CSS) pixels to real pixels. + * + * **inputPixel** + * + * `inputPixel.xy` is the size of framebuffer in real pixels, same as `inputSize.xy * resolution` + * `inputPixel.zw` is inverted `inputPixel.xy`. + * + * It's handy for filters that use neighbour pixels, like {@link PIXI.filters.FXAAFilter FXAAFilter}. + * + * **inputClamp** + * + * If you try to get info from outside of used part of Framebuffer - you'll get undefined behaviour. + * For displacements, coordinates has to be clamped. + * + * The `inputClamp.xy` is left-top pixel center, you may ignore it, because we use left-top part of Framebuffer + * `inputClamp.zw` is bottom-right pixel center. + * + * ``` + * vec4 color = texture2D(uSampler, clamp(modifiedTextureCoord, inputClamp.xy, inputClamp.zw)) + * ``` + * OR + * ``` + * vec4 color = texture2D(uSampler, min(modifigedTextureCoord, inputClamp.zw)) + * ``` + * + * ### Additional Information + * + * Complete documentation on Filter usage is located in the + * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}. + * + * Since PixiJS only had a handful of built-in filters, additional filters can be downloaded + * {@link https://github.com/pixijs/pixi-filters here} from the PixiJS Filters repository. + * @memberof PIXI + */ + var Filter = /** @class */ (function (_super) { + __extends$i(Filter, _super); + /** + * @param vertexSrc - The source of the vertex shader. + * @param fragmentSrc - The source of the fragment shader. + * @param uniforms - Custom uniforms to use to augment the built-in ones. + */ + function Filter(vertexSrc, fragmentSrc, uniforms) { + var _this = this; + var program = Program.from(vertexSrc || Filter.defaultVertexSrc, fragmentSrc || Filter.defaultFragmentSrc); + _this = _super.call(this, program, uniforms) || this; + _this.padding = 0; + _this.resolution = settings.FILTER_RESOLUTION; + _this.multisample = settings.FILTER_MULTISAMPLE; + _this.enabled = true; + _this.autoFit = true; + _this.state = new State(); + return _this; + } + /** + * Applies the filter + * @param {PIXI.FilterSystem} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTexture} input - The input render target. + * @param {PIXI.RenderTexture} output - The target to output to. + * @param {PIXI.CLEAR_MODES} [clearMode] - Should the output be cleared before rendering to it. + * @param {object} [_currentState] - It's current state of filter. + * There are some useful properties in the currentState : + * target, filters, sourceFrame, destinationFrame, renderTarget, resolution + */ + Filter.prototype.apply = function (filterManager, input, output, clearMode, _currentState) { + // do as you please! + filterManager.applyFilter(this, input, output, clearMode); + // or just do a regular render.. + }; + Object.defineProperty(Filter.prototype, "blendMode", { + /** + * Sets the blend mode of the filter. + * @default PIXI.BLEND_MODES.NORMAL + */ + get: function () { + return this.state.blendMode; + }, + set: function (value) { + this.state.blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Filter.prototype, "resolution", { + /** + * The resolution of the filter. Setting this to be lower will lower the quality but + * increase the performance of the filter. + */ + get: function () { + return this._resolution; + }, + set: function (value) { + this._resolution = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Filter, "defaultVertexSrc", { + /** + * The default vertex shader source + * @constant + */ + get: function () { + return defaultVertex$2; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Filter, "defaultFragmentSrc", { + /** + * The default fragment shader source + * @constant + */ + get: function () { + return defaultFragment$1; + }, + enumerable: false, + configurable: true + }); + return Filter; + }(Shader)); + + var vertex$4 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n"; + + var fragment$7 = "varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform float npmAlpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);\n\n original *= (alphaMul * masky.r * alpha * clip);\n\n gl_FragColor = original;\n}\n"; + + var tempMat$1 = new Matrix(); + /** + * Class controls uv mapping from Texture normal space to BaseTexture normal space. + * + * Takes `trim` and `rotate` into account. May contain clamp settings for Meshes and TilingSprite. + * + * Can be used in Texture `uvMatrix` field, or separately, you can use different clamp settings on the same texture. + * If you want to add support for texture region of certain feature or filter, that's what you're looking for. + * + * Takes track of Texture changes through `_lastTextureID` private field. + * Use `update()` method call to track it from outside. + * @see PIXI.Texture + * @see PIXI.Mesh + * @see PIXI.TilingSprite + * @memberof PIXI + */ + var TextureMatrix = /** @class */ (function () { + /** + * @param texture - observed texture + * @param clampMargin - Changes frame clamping, 0.5 by default. Use -0.5 for extra border. + */ + function TextureMatrix(texture, clampMargin) { + this._texture = texture; + this.mapCoord = new Matrix(); + this.uClampFrame = new Float32Array(4); + this.uClampOffset = new Float32Array(2); + this._textureID = -1; + this._updateID = 0; + this.clampOffset = 0; + this.clampMargin = (typeof clampMargin === 'undefined') ? 0.5 : clampMargin; + this.isSimple = false; + } + Object.defineProperty(TextureMatrix.prototype, "texture", { + /** Texture property. */ + get: function () { + return this._texture; + }, + set: function (value) { + this._texture = value; + this._textureID = -1; + }, + enumerable: false, + configurable: true + }); + /** + * Multiplies uvs array to transform + * @param uvs - mesh uvs + * @param [out=uvs] - output + * @returns - output + */ + TextureMatrix.prototype.multiplyUvs = function (uvs, out) { + if (out === undefined) { + out = uvs; + } + var mat = this.mapCoord; + for (var i = 0; i < uvs.length; i += 2) { + var x = uvs[i]; + var y = uvs[i + 1]; + out[i] = (x * mat.a) + (y * mat.c) + mat.tx; + out[i + 1] = (x * mat.b) + (y * mat.d) + mat.ty; + } + return out; + }; + /** + * Updates matrices if texture was changed. + * @param [forceUpdate=false] - if true, matrices will be updated any case + * @returns - Whether or not it was updated + */ + TextureMatrix.prototype.update = function (forceUpdate) { + var tex = this._texture; + if (!tex || !tex.valid) { + return false; + } + if (!forceUpdate + && this._textureID === tex._updateID) { + return false; + } + this._textureID = tex._updateID; + this._updateID++; + var uvs = tex._uvs; + this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); + var orig = tex.orig; + var trim = tex.trim; + if (trim) { + tempMat$1.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); + this.mapCoord.append(tempMat$1); + } + var texBase = tex.baseTexture; + var frame = this.uClampFrame; + var margin = this.clampMargin / texBase.resolution; + var offset = this.clampOffset; + frame[0] = (tex._frame.x + margin + offset) / texBase.width; + frame[1] = (tex._frame.y + margin + offset) / texBase.height; + frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; + frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; + this.uClampOffset[0] = offset / texBase.realWidth; + this.uClampOffset[1] = offset / texBase.realHeight; + this.isSimple = tex._frame.width === texBase.width + && tex._frame.height === texBase.height + && tex.rotate === 0; + return true; + }; + return TextureMatrix; + }()); -if (!window.ArrayBuffer) { - window.ArrayBuffer = Array; -} + /** + * This handles a Sprite acting as a mask, as opposed to a Graphic. + * + * WebGL only. + * @memberof PIXI + */ + var SpriteMaskFilter = /** @class */ (function (_super) { + __extends$i(SpriteMaskFilter, _super); + /** @ignore */ + function SpriteMaskFilter(vertexSrc, fragmentSrc, uniforms) { + var _this = this; + var sprite = null; + if (typeof vertexSrc !== 'string' && fragmentSrc === undefined && uniforms === undefined) { + sprite = vertexSrc; + vertexSrc = undefined; + fragmentSrc = undefined; + uniforms = undefined; + } + _this = _super.call(this, vertexSrc || vertex$4, fragmentSrc || fragment$7, uniforms) || this; + _this.maskSprite = sprite; + _this.maskMatrix = new Matrix(); + return _this; + } + Object.defineProperty(SpriteMaskFilter.prototype, "maskSprite", { + /** + * Sprite mask + * @type {PIXI.DisplayObject} + */ + get: function () { + return this._maskSprite; + }, + set: function (value) { + this._maskSprite = value; + if (this._maskSprite) { + this._maskSprite.renderable = false; + } + }, + enumerable: false, + configurable: true + }); + /** + * Applies the filter + * @param filterManager - The renderer to retrieve the filter from + * @param input - The input render target. + * @param output - The target to output to. + * @param clearMode - Should the output be cleared before rendering to it. + */ + SpriteMaskFilter.prototype.apply = function (filterManager, input, output, clearMode) { + var maskSprite = this._maskSprite; + var tex = maskSprite._texture; + if (!tex.valid) { + return; + } + if (!tex.uvMatrix) { + // margin = 0.0, let it bleed a bit, shader code becomes easier + // assuming that atlas textures were made with 1-pixel padding + tex.uvMatrix = new TextureMatrix(tex, 0.0); + } + tex.uvMatrix.update(); + this.uniforms.npmAlpha = tex.baseTexture.alphaMode ? 0.0 : 1.0; + this.uniforms.mask = tex; + // get _normalized sprite texture coords_ and convert them to _normalized atlas texture coords_ with `prepend` + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite) + .prepend(tex.uvMatrix.mapCoord); + this.uniforms.alpha = maskSprite.worldAlpha; + this.uniforms.maskClamp = tex.uvMatrix.uClampFrame; + filterManager.applyFilter(this, input, output, clearMode); + }; + return SpriteMaskFilter; + }(Filter)); -if (!window.Float32Array) { - window.Float32Array = Array; -} + /** + * System plugin to the renderer to manage masks. + * + * There are three built-in types of masking: + * **Scissor Masking**: Scissor masking discards pixels that are outside of a rectangle called the scissor box. It is + * the most performant as the scissor test is inexpensive. However, it can only be used when the mask is rectangular. + * **Stencil Masking**: Stencil masking discards pixels that don't overlap with the pixels rendered into the stencil + * buffer. It is the next fastest option as it does not require rendering into a separate framebuffer. However, it does + * cause the mask to be rendered **twice** for each masking operation; hence, minimize the rendering cost of your masks. + * **Sprite Mask Filtering**: Sprite mask filtering discards pixels based on the red channel of the sprite-mask's + * texture. (Generally, the masking texture is grayscale). Using advanced techniques, you might be able to embed this + * type of masking in a custom shader - and hence, bypassing the masking system fully for performance wins. + * + * The best type of masking is auto-detected when you `push` one. To use scissor masking, you must pass in a `Graphics` + * object with just a rectangle drawn. + * + * ## Mask Stacks + * + * In the scene graph, masks can be applied recursively, i.e. a mask can be applied during a masking operation. The mask + * stack stores the currently applied masks in order. Each {@link PIXI.BaseRenderTexture} holds its own mask stack, i.e. + * when you switch render-textures, the old masks only applied when you switch back to rendering to the old render-target. + * @memberof PIXI + */ + var MaskSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this System works for. + */ + function MaskSystem(renderer) { + this.renderer = renderer; + this.enableScissor = true; + this.alphaMaskPool = []; + this.maskDataPool = []; + this.maskStack = []; + this.alphaMaskIndex = 0; + } + /** + * Changes the mask stack that is used by this System. + * @param maskStack - The mask stack + */ + MaskSystem.prototype.setMaskStack = function (maskStack) { + this.maskStack = maskStack; + this.renderer.scissor.setMaskStack(maskStack); + this.renderer.stencil.setMaskStack(maskStack); + }; + /** + * Enables the mask and appends it to the current mask stack. + * + * NOTE: The batch renderer should be flushed beforehand to prevent pending renders from being masked. + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.MaskData|PIXI.Sprite|PIXI.Graphics|PIXI.DisplayObject} maskDataOrTarget - The masking data. + */ + MaskSystem.prototype.push = function (target, maskDataOrTarget) { + var maskData = maskDataOrTarget; + if (!maskData.isMaskData) { + var d = this.maskDataPool.pop() || new MaskData(); + d.pooled = true; + d.maskObject = maskDataOrTarget; + maskData = d; + } + var maskAbove = this.maskStack.length !== 0 ? this.maskStack[this.maskStack.length - 1] : null; + maskData.copyCountersOrReset(maskAbove); + maskData._colorMask = maskAbove ? maskAbove._colorMask : 0xf; + if (maskData.autoDetect) { + this.detect(maskData); + } + maskData._target = target; + if (maskData.type !== exports.MASK_TYPES.SPRITE) { + this.maskStack.push(maskData); + } + if (maskData.enabled) { + switch (maskData.type) { + case exports.MASK_TYPES.SCISSOR: + this.renderer.scissor.push(maskData); + break; + case exports.MASK_TYPES.STENCIL: + this.renderer.stencil.push(maskData); + break; + case exports.MASK_TYPES.SPRITE: + maskData.copyCountersOrReset(null); + this.pushSpriteMask(maskData); + break; + case exports.MASK_TYPES.COLOR: + this.pushColorMask(maskData); + break; + } + } + if (maskData.type === exports.MASK_TYPES.SPRITE) { + this.maskStack.push(maskData); + } + }; + /** + * Removes the last mask from the mask stack and doesn't return it. + * + * NOTE: The batch renderer should be flushed beforehand to render the masked contents before the mask is removed. + * @param {PIXI.IMaskTarget} target - Display Object to pop the mask from + */ + MaskSystem.prototype.pop = function (target) { + var maskData = this.maskStack.pop(); + if (!maskData || maskData._target !== target) { + // TODO: add an assert when we have it + return; + } + if (maskData.enabled) { + switch (maskData.type) { + case exports.MASK_TYPES.SCISSOR: + this.renderer.scissor.pop(maskData); + break; + case exports.MASK_TYPES.STENCIL: + this.renderer.stencil.pop(maskData.maskObject); + break; + case exports.MASK_TYPES.SPRITE: + this.popSpriteMask(maskData); + break; + case exports.MASK_TYPES.COLOR: + this.popColorMask(maskData); + break; + } + } + maskData.reset(); + if (maskData.pooled) { + this.maskDataPool.push(maskData); + } + if (this.maskStack.length !== 0) { + var maskCurrent = this.maskStack[this.maskStack.length - 1]; + if (maskCurrent.type === exports.MASK_TYPES.SPRITE && maskCurrent._filters) { + maskCurrent._filters[0].maskSprite = maskCurrent.maskObject; + } + } + }; + /** + * Sets type of MaskData based on its maskObject. + * @param maskData + */ + MaskSystem.prototype.detect = function (maskData) { + var maskObject = maskData.maskObject; + if (!maskObject) { + maskData.type = exports.MASK_TYPES.COLOR; + } + else if (maskObject.isSprite) { + maskData.type = exports.MASK_TYPES.SPRITE; + } + else if (this.enableScissor && this.renderer.scissor.testScissor(maskData)) { + maskData.type = exports.MASK_TYPES.SCISSOR; + } + else { + maskData.type = exports.MASK_TYPES.STENCIL; + } + }; + /** + * Applies the Mask and adds it to the current filter stack. + * @param maskData - Sprite to be used as the mask. + */ + MaskSystem.prototype.pushSpriteMask = function (maskData) { + var _a, _b; + var maskObject = maskData.maskObject; + var target = maskData._target; + var alphaMaskFilter = maskData._filters; + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new SpriteMaskFilter()]; + } + } + var renderer = this.renderer; + var renderTextureSystem = renderer.renderTexture; + var resolution; + var multisample; + if (renderTextureSystem.current) { + var renderTexture = renderTextureSystem.current; + resolution = maskData.resolution || renderTexture.resolution; + multisample = (_a = maskData.multisample) !== null && _a !== void 0 ? _a : renderTexture.multisample; + } + else { + resolution = maskData.resolution || renderer.resolution; + multisample = (_b = maskData.multisample) !== null && _b !== void 0 ? _b : renderer.multisample; + } + alphaMaskFilter[0].resolution = resolution; + alphaMaskFilter[0].multisample = multisample; + alphaMaskFilter[0].maskSprite = maskObject; + var stashFilterArea = target.filterArea; + target.filterArea = maskObject.getBounds(true); + renderer.filter.push(target, alphaMaskFilter); + target.filterArea = stashFilterArea; + if (!maskData._filters) { + this.alphaMaskIndex++; + } + }; + /** + * Removes the last filter from the filter stack and doesn't return it. + * @param maskData - Sprite to be used as the mask. + */ + MaskSystem.prototype.popSpriteMask = function (maskData) { + this.renderer.filter.pop(); + if (maskData._filters) { + maskData._filters[0].maskSprite = null; + } + else { + this.alphaMaskIndex--; + this.alphaMaskPool[this.alphaMaskIndex][0].maskSprite = null; + } + }; + /** + * Pushes the color mask. + * @param maskData - The mask data + */ + MaskSystem.prototype.pushColorMask = function (maskData) { + var currColorMask = maskData._colorMask; + var nextColorMask = maskData._colorMask = currColorMask & maskData.colorMask; + if (nextColorMask !== currColorMask) { + this.renderer.gl.colorMask((nextColorMask & 0x1) !== 0, (nextColorMask & 0x2) !== 0, (nextColorMask & 0x4) !== 0, (nextColorMask & 0x8) !== 0); + } + }; + /** + * Pops the color mask. + * @param maskData - The mask data + */ + MaskSystem.prototype.popColorMask = function (maskData) { + var currColorMask = maskData._colorMask; + var nextColorMask = this.maskStack.length > 0 + ? this.maskStack[this.maskStack.length - 1]._colorMask : 0xf; + if (nextColorMask !== currColorMask) { + this.renderer.gl.colorMask((nextColorMask & 0x1) !== 0, (nextColorMask & 0x2) !== 0, (nextColorMask & 0x4) !== 0, (nextColorMask & 0x8) !== 0); + } + }; + MaskSystem.prototype.destroy = function () { + this.renderer = null; + }; + return MaskSystem; + }()); -if (!window.Uint32Array) { - window.Uint32Array = Array; -} + /** + * System plugin to the renderer to manage specific types of masking operations. + * @memberof PIXI + */ + var AbstractMaskSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this System works for. + */ + function AbstractMaskSystem(renderer) { + this.renderer = renderer; + this.maskStack = []; + this.glConst = 0; + } + /** Gets count of masks of certain type. */ + AbstractMaskSystem.prototype.getStackLength = function () { + return this.maskStack.length; + }; + /** + * Changes the mask stack that is used by this System. + * @param {PIXI.MaskData[]} maskStack - The mask stack + */ + AbstractMaskSystem.prototype.setMaskStack = function (maskStack) { + var gl = this.renderer.gl; + var curStackLen = this.getStackLength(); + this.maskStack = maskStack; + var newStackLen = this.getStackLength(); + if (newStackLen !== curStackLen) { + if (newStackLen === 0) { + gl.disable(this.glConst); + } + else { + gl.enable(this.glConst); + this._useCurrent(); + } + } + }; + /** + * Setup renderer to use the current mask data. + * @private + */ + AbstractMaskSystem.prototype._useCurrent = function () { + // OVERWRITE; + }; + /** Destroys the mask stack. */ + AbstractMaskSystem.prototype.destroy = function () { + this.renderer = null; + this.maskStack = null; + }; + return AbstractMaskSystem; + }()); + + var tempMatrix$1 = new Matrix(); + var rectPool = []; + /** + * System plugin to the renderer to manage scissor masking. + * + * Scissor masking discards pixels outside of a rectangle called the scissor box. The scissor box is in the framebuffer + * viewport's space; however, the mask's rectangle is projected from world-space to viewport space automatically + * by this system. + * @memberof PIXI + */ + var ScissorSystem = /** @class */ (function (_super) { + __extends$i(ScissorSystem, _super); + /** + * @param {PIXI.Renderer} renderer - The renderer this System works for. + */ + function ScissorSystem(renderer) { + var _this = _super.call(this, renderer) || this; + _this.glConst = settings.ADAPTER.getWebGLRenderingContext().SCISSOR_TEST; + return _this; + } + ScissorSystem.prototype.getStackLength = function () { + var maskData = this.maskStack[this.maskStack.length - 1]; + if (maskData) { + return maskData._scissorCounter; + } + return 0; + }; + /** + * evaluates _boundsTransformed, _scissorRect for MaskData + * @param maskData + */ + ScissorSystem.prototype.calcScissorRect = function (maskData) { + var _a; + if (maskData._scissorRectLocal) { + return; + } + var prevData = maskData._scissorRect; + var maskObject = maskData.maskObject; + var renderer = this.renderer; + var renderTextureSystem = renderer.renderTexture; + var rect = maskObject.getBounds(true, (_a = rectPool.pop()) !== null && _a !== void 0 ? _a : new Rectangle()); + this.roundFrameToPixels(rect, renderTextureSystem.current ? renderTextureSystem.current.resolution : renderer.resolution, renderTextureSystem.sourceFrame, renderTextureSystem.destinationFrame, renderer.projection.transform); + if (prevData) { + rect.fit(prevData); + } + maskData._scissorRectLocal = rect; + }; + ScissorSystem.isMatrixRotated = function (matrix) { + if (!matrix) { + return false; + } + var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d; + // Skip if skew/rotation present in matrix, except for multiple of 90° rotation. If rotation + // is a multiple of 90°, then either pair of (b,c) or (a,d) will be (0,0). + return ((Math.abs(b) > 1e-4 || Math.abs(c) > 1e-4) + && (Math.abs(a) > 1e-4 || Math.abs(d) > 1e-4)); + }; + /** + * Test, whether the object can be scissor mask with current renderer projection. + * Calls "calcScissorRect()" if its true. + * @param maskData - mask data + * @returns whether Whether the object can be scissor mask + */ + ScissorSystem.prototype.testScissor = function (maskData) { + var maskObject = maskData.maskObject; + if (!maskObject.isFastRect || !maskObject.isFastRect()) { + return false; + } + if (ScissorSystem.isMatrixRotated(maskObject.worldTransform)) { + return false; + } + if (ScissorSystem.isMatrixRotated(this.renderer.projection.transform)) { + return false; + } + this.calcScissorRect(maskData); + var rect = maskData._scissorRectLocal; + return rect.width > 0 && rect.height > 0; + }; + ScissorSystem.prototype.roundFrameToPixels = function (frame, resolution, bindingSourceFrame, bindingDestinationFrame, transform) { + if (ScissorSystem.isMatrixRotated(transform)) { + return; + } + transform = transform ? tempMatrix$1.copyFrom(transform) : tempMatrix$1.identity(); + // Get forward transform from world space to screen space + transform + .translate(-bindingSourceFrame.x, -bindingSourceFrame.y) + .scale(bindingDestinationFrame.width / bindingSourceFrame.width, bindingDestinationFrame.height / bindingSourceFrame.height) + .translate(bindingDestinationFrame.x, bindingDestinationFrame.y); + // Convert frame to screen space + this.renderer.filter.transformAABB(transform, frame); + frame.fit(bindingDestinationFrame); + frame.x = Math.round(frame.x * resolution); + frame.y = Math.round(frame.y * resolution); + frame.width = Math.round(frame.width * resolution); + frame.height = Math.round(frame.height * resolution); + }; + /** + * Applies the Mask and adds it to the current stencil stack. + * @author alvin + * @param maskData - The mask data. + */ + ScissorSystem.prototype.push = function (maskData) { + if (!maskData._scissorRectLocal) { + this.calcScissorRect(maskData); + } + var gl = this.renderer.gl; + if (!maskData._scissorRect) { + gl.enable(gl.SCISSOR_TEST); + } + maskData._scissorCounter++; + maskData._scissorRect = maskData._scissorRectLocal; + this._useCurrent(); + }; + /** + * This should be called after a mask is popped off the mask stack. It will rebind the scissor box to be latest with the + * last mask in the stack. + * + * This can also be called when you directly modify the scissor box and want to restore PixiJS state. + * @param maskData - The mask data. + */ + ScissorSystem.prototype.pop = function (maskData) { + var gl = this.renderer.gl; + if (maskData) { + rectPool.push(maskData._scissorRectLocal); + } + if (this.getStackLength() > 0) { + this._useCurrent(); + } + else { + gl.disable(gl.SCISSOR_TEST); + } + }; + /** + * Setup renderer to use the current scissor data. + * @private + */ + ScissorSystem.prototype._useCurrent = function () { + var rect = this.maskStack[this.maskStack.length - 1]._scissorRect; + var y; + if (this.renderer.renderTexture.current) { + y = rect.y; + } + else { + // flipY. In future we'll have it over renderTextures as an option + y = this.renderer.height - rect.height - rect.y; + } + this.renderer.gl.scissor(rect.x, y, rect.width, rect.height); + }; + return ScissorSystem; + }(AbstractMaskSystem)); -if (!window.Uint16Array) { - window.Uint16Array = Array; -} + /** + * System plugin to the renderer to manage stencils (used for masks). + * @memberof PIXI + */ + var StencilSystem = /** @class */ (function (_super) { + __extends$i(StencilSystem, _super); + /** + * @param renderer - The renderer this System works for. + */ + function StencilSystem(renderer) { + var _this = _super.call(this, renderer) || this; + _this.glConst = settings.ADAPTER.getWebGLRenderingContext().STENCIL_TEST; + return _this; + } + StencilSystem.prototype.getStackLength = function () { + var maskData = this.maskStack[this.maskStack.length - 1]; + if (maskData) { + return maskData._stencilCounter; + } + return 0; + }; + /** + * Applies the Mask and adds it to the current stencil stack. + * @param maskData - The mask data + */ + StencilSystem.prototype.push = function (maskData) { + var maskObject = maskData.maskObject; + var gl = this.renderer.gl; + var prevMaskCount = maskData._stencilCounter; + if (prevMaskCount === 0) { + // force use stencil texture in current framebuffer + this.renderer.framebuffer.forceStencil(); + gl.clearStencil(0); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.enable(gl.STENCIL_TEST); + } + maskData._stencilCounter++; + var colorMask = maskData._colorMask; + if (colorMask !== 0) { + maskData._colorMask = 0; + gl.colorMask(false, false, false, false); + } + // Increment the reference stencil value where the new mask overlaps with the old ones. + gl.stencilFunc(gl.EQUAL, prevMaskCount, 0xFFFFFFFF); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + maskObject.renderable = true; + maskObject.render(this.renderer); + this.renderer.batch.flush(); + maskObject.renderable = false; + if (colorMask !== 0) { + maskData._colorMask = colorMask; + gl.colorMask((colorMask & 1) !== 0, (colorMask & 2) !== 0, (colorMask & 4) !== 0, (colorMask & 8) !== 0); + } + this._useCurrent(); + }; + /** + * Pops stencil mask. MaskData is already removed from stack + * @param {PIXI.DisplayObject} maskObject - object of popped mask data + */ + StencilSystem.prototype.pop = function (maskObject) { + var gl = this.renderer.gl; + if (this.getStackLength() === 0) { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + } + else { + var maskData = this.maskStack.length !== 0 ? this.maskStack[this.maskStack.length - 1] : null; + var colorMask = maskData ? maskData._colorMask : 0xf; + if (colorMask !== 0) { + maskData._colorMask = 0; + gl.colorMask(false, false, false, false); + } + // Decrement the reference stencil value where the popped mask overlaps with the other ones + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + maskObject.renderable = true; + maskObject.render(this.renderer); + this.renderer.batch.flush(); + maskObject.renderable = false; + if (colorMask !== 0) { + maskData._colorMask = colorMask; + gl.colorMask((colorMask & 0x1) !== 0, (colorMask & 0x2) !== 0, (colorMask & 0x4) !== 0, (colorMask & 0x8) !== 0); + } + this._useCurrent(); + } + }; + /** + * Setup renderer to use the current stencil data. + * @private + */ + StencilSystem.prototype._useCurrent = function () { + var gl = this.renderer.gl; + gl.stencilFunc(gl.EQUAL, this.getStackLength(), 0xFFFFFFFF); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + }; + return StencilSystem; + }(AbstractMaskSystem)); -},{"./Math.sign":178,"./Object.assign":179,"./requestAnimationFrame":181}],181:[function(require,module,exports){ -(function (global){ -'use strict'; + /** + * System plugin to the renderer to manage the projection matrix. + * + * The `projectionMatrix` is a global uniform provided to all shaders. It is used to transform points in world space to + * normalized device coordinates. + * @memberof PIXI + */ + var ProjectionSystem = /** @class */ (function () { + /** @param renderer - The renderer this System works for. */ + function ProjectionSystem(renderer) { + this.renderer = renderer; + this.destinationFrame = null; + this.sourceFrame = null; + this.defaultFrame = null; + this.projectionMatrix = new Matrix(); + this.transform = null; + } + /** + * Updates the projection-matrix based on the sourceFrame → destinationFrame mapping provided. + * + * NOTE: It is expected you call `renderer.framebuffer.setViewport(destinationFrame)` after this. This is because + * the framebuffer viewport converts shader vertex output in normalized device coordinates to window coordinates. + * + * NOTE-2: {@link RenderTextureSystem#bind} updates the projection-matrix when you bind a render-texture. It is expected + * that you dirty the current bindings when calling this manually. + * @param destinationFrame - The rectangle in the render-target to render the contents into. If rendering to the canvas, + * the origin is on the top-left; if rendering to a render-texture, the origin is on the bottom-left. + * @param sourceFrame - The rectangle in world space that contains the contents being rendered. + * @param resolution - The resolution of the render-target, which is the ratio of + * world-space (or CSS) pixels to physical pixels. + * @param root - Whether the render-target is the screen. This is required because rendering to textures + * is y-flipped (i.e. upside down relative to the screen). + */ + ProjectionSystem.prototype.update = function (destinationFrame, sourceFrame, resolution, root) { + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame; + // Calculate object-space to clip-space projection + this.calculateProjection(this.destinationFrame, this.sourceFrame, resolution, root); + if (this.transform) { + this.projectionMatrix.append(this.transform); + } + var renderer = this.renderer; + renderer.globalUniforms.uniforms.projectionMatrix = this.projectionMatrix; + renderer.globalUniforms.update(); + // this will work for now + // but would be sweet to stick and even on the global uniforms.. + if (renderer.shader.shader) { + renderer.shader.syncUniformGroup(renderer.shader.shader.uniforms.globals); + } + }; + /** + * Calculates the `projectionMatrix` to map points inside `sourceFrame` to inside `destinationFrame`. + * @param _destinationFrame - The destination frame in the render-target. + * @param sourceFrame - The source frame in world space. + * @param _resolution - The render-target's resolution, i.e. ratio of CSS to physical pixels. + * @param root - Whether rendering into the screen. Otherwise, if rendering to a framebuffer, the projection + * is y-flipped. + */ + ProjectionSystem.prototype.calculateProjection = function (_destinationFrame, sourceFrame, _resolution, root) { + var pm = this.projectionMatrix; + var sign = !root ? 1 : -1; + pm.identity(); + pm.a = (1 / sourceFrame.width * 2); + pm.d = sign * (1 / sourceFrame.height * 2); + pm.tx = -1 - (sourceFrame.x * pm.a); + pm.ty = -sign - (sourceFrame.y * pm.d); + }; + /** + * Sets the transform of the active render target to the given matrix. + * @param _matrix - The transformation matrix + */ + ProjectionSystem.prototype.setTransform = function (_matrix) { + // this._activeRenderTarget.transform = matrix; + }; + ProjectionSystem.prototype.destroy = function () { + this.renderer = null; + }; + return ProjectionSystem; + }()); + + // Temporary rectangle for assigned sourceFrame or destinationFrame + var tempRect = new Rectangle(); + // Temporary rectangle for renderTexture destinationFrame + var tempRect2 = new Rectangle(); + /* eslint-disable max-len */ + /** + * System plugin to the renderer to manage render textures. + * + * Should be added after FramebufferSystem + * + * ### Frames + * + * The `RenderTextureSystem` holds a sourceFrame → destinationFrame projection. The following table explains the different + * coordinate spaces used: + * + * | Frame | Description | Coordinate System | + * | ---------------------- | ---------------------------------------------------------------- | ------------------------------------------------------- | + * | sourceFrame | The rectangle inside of which display-objects are being rendered | **World Space**: The origin on the top-left | + * | destinationFrame | The rectangle in the render-target (canvas or texture) into which contents should be rendered | If rendering to the canvas, this is in screen space and the origin is on the top-left. If rendering to a render-texture, this is in its base-texture's space with the origin on the bottom-left. | + * | viewportFrame | The framebuffer viewport corresponding to the destination-frame | **Window Coordinates**: The origin is always on the bottom-left. | + * @memberof PIXI + */ + var RenderTextureSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this System works for. + */ + function RenderTextureSystem(renderer) { + this.renderer = renderer; + this.clearColor = renderer._backgroundColorRgba; + this.defaultMaskStack = []; + this.current = null; + this.sourceFrame = new Rectangle(); + this.destinationFrame = new Rectangle(); + this.viewportFrame = new Rectangle(); + } + /** + * Bind the current render texture. + * @param renderTexture - RenderTexture to bind, by default its `null` - the screen. + * @param sourceFrame - Part of world that is mapped to the renderTexture. + * @param destinationFrame - Part of renderTexture, by default it has the same size as sourceFrame. + */ + RenderTextureSystem.prototype.bind = function (renderTexture, sourceFrame, destinationFrame) { + if (renderTexture === void 0) { renderTexture = null; } + var renderer = this.renderer; + this.current = renderTexture; + var baseTexture; + var framebuffer; + var resolution; + if (renderTexture) { + baseTexture = renderTexture.baseTexture; + resolution = baseTexture.resolution; + if (!sourceFrame) { + tempRect.width = renderTexture.frame.width; + tempRect.height = renderTexture.frame.height; + sourceFrame = tempRect; + } + if (!destinationFrame) { + tempRect2.x = renderTexture.frame.x; + tempRect2.y = renderTexture.frame.y; + tempRect2.width = sourceFrame.width; + tempRect2.height = sourceFrame.height; + destinationFrame = tempRect2; + } + framebuffer = baseTexture.framebuffer; + } + else { + resolution = renderer.resolution; + if (!sourceFrame) { + tempRect.width = renderer.screen.width; + tempRect.height = renderer.screen.height; + sourceFrame = tempRect; + } + if (!destinationFrame) { + destinationFrame = tempRect; + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; + } + } + var viewportFrame = this.viewportFrame; + viewportFrame.x = destinationFrame.x * resolution; + viewportFrame.y = destinationFrame.y * resolution; + viewportFrame.width = destinationFrame.width * resolution; + viewportFrame.height = destinationFrame.height * resolution; + if (!renderTexture) { + viewportFrame.y = renderer.view.height - (viewportFrame.y + viewportFrame.height); + } + viewportFrame.ceil(); + this.renderer.framebuffer.bind(framebuffer, viewportFrame); + this.renderer.projection.update(destinationFrame, sourceFrame, resolution, !framebuffer); + if (renderTexture) { + this.renderer.mask.setMaskStack(baseTexture.maskStack); + } + else { + this.renderer.mask.setMaskStack(this.defaultMaskStack); + } + this.sourceFrame.copyFrom(sourceFrame); + this.destinationFrame.copyFrom(destinationFrame); + }; + /** + * Erases the render texture and fills the drawing area with a colour. + * @param clearColor - The color as rgba, default to use the renderer backgroundColor + * @param [mask=BUFFER_BITS.COLOR | BUFFER_BITS.DEPTH] - Bitwise OR of masks + * that indicate the buffers to be cleared, by default COLOR and DEPTH buffers. + */ + RenderTextureSystem.prototype.clear = function (clearColor, mask) { + if (this.current) { + clearColor = clearColor || this.current.baseTexture.clearColor; + } + else { + clearColor = clearColor || this.clearColor; + } + var destinationFrame = this.destinationFrame; + var baseFrame = this.current ? this.current.baseTexture : this.renderer.screen; + var clearMask = destinationFrame.width !== baseFrame.width || destinationFrame.height !== baseFrame.height; + if (clearMask) { + var _a = this.viewportFrame, x = _a.x, y = _a.y, width = _a.width, height = _a.height; + x = Math.round(x); + y = Math.round(y); + width = Math.round(width); + height = Math.round(height); + // TODO: ScissorSystem should cache whether the scissor test is enabled or not. + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + this.renderer.gl.scissor(x, y, width, height); + } + this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3], mask); + if (clearMask) { + // Restore the scissor box + this.renderer.scissor.pop(); + } + }; + RenderTextureSystem.prototype.resize = function () { + // resize the root only! + this.bind(null); + }; + /** Resets render-texture state. */ + RenderTextureSystem.prototype.reset = function () { + this.bind(null); + }; + RenderTextureSystem.prototype.destroy = function () { + this.renderer = null; + }; + return RenderTextureSystem; + }()); + + function uboUpdate(_ud, _uv, _renderer, _syncData, buffer) { + _renderer.buffer.update(buffer); + } + // cv = CachedValue + // v = value + // ud = uniformData + // uv = uniformValue + // l = location + var UBO_TO_SINGLE_SETTERS = { + float: "\n data[offset] = v;\n ", + vec2: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n ", + vec3: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n\n ", + vec4: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n data[offset+3] = v[3];\n ", + mat2: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n\n data[offset+4] = v[2];\n data[offset+5] = v[3];\n ", + mat3: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n\n data[offset + 4] = v[3];\n data[offset + 5] = v[4];\n data[offset + 6] = v[5];\n\n data[offset + 8] = v[6];\n data[offset + 9] = v[7];\n data[offset + 10] = v[8];\n ", + mat4: "\n for(var i = 0; i < 16; i++)\n {\n data[offset + i] = v[i];\n }\n " + }; + var GLSL_TO_STD40_SIZE = { + float: 4, + vec2: 8, + vec3: 12, + vec4: 16, + int: 4, + ivec2: 8, + ivec3: 12, + ivec4: 16, + uint: 4, + uvec2: 8, + uvec3: 12, + uvec4: 16, + bool: 4, + bvec2: 8, + bvec3: 12, + bvec4: 16, + mat2: 16 * 2, + mat3: 16 * 3, + mat4: 16 * 4, + }; + /** + * logic originally from here: https://github.com/sketchpunk/FunWithWebGL2/blob/master/lesson_022/Shaders.js + * rewrote it, but this was a great starting point to get a solid understanding of whats going on :) + * @ignore + * @param uniformData + */ + function createUBOElements(uniformData) { + var uboElements = uniformData.map(function (data) { + return ({ + data: data, + offset: 0, + dataLen: 0, + dirty: 0 + }); + }); + var size = 0; + var chunkSize = 0; + var offset = 0; + for (var i = 0; i < uboElements.length; i++) { + var uboElement = uboElements[i]; + size = GLSL_TO_STD40_SIZE[uboElement.data.type]; + if (uboElement.data.size > 1) { + size = Math.max(size, 16) * uboElement.data.size; + } + uboElement.dataLen = size; + // add some size offset.. + // must align to the nearest 16 bytes or internally nearest round size + if (chunkSize % size !== 0 && chunkSize < 16) { + // diff required to line up.. + var lineUpValue = (chunkSize % size) % 16; + chunkSize += lineUpValue; + offset += lineUpValue; + } + if ((chunkSize + size) > 16) { + offset = Math.ceil(offset / 16) * 16; + uboElement.offset = offset; + offset += size; + chunkSize = size; + } + else { + uboElement.offset = offset; + chunkSize += size; + offset += size; + } + } + offset = Math.ceil(offset / 16) * 16; + return { uboElements: uboElements, size: offset }; + } + function getUBOData(uniforms, uniformData) { + var usedUniformDatas = []; + // build.. + for (var i in uniforms) { + if (uniformData[i]) { + usedUniformDatas.push(uniformData[i]); + } + } + // sort them out by index! + usedUniformDatas.sort(function (a, b) { return a.index - b.index; }); + return usedUniformDatas; + } + function generateUniformBufferSync(group, uniformData) { + if (!group.autoManage) { + // if the group is nott automatically managed, we don't need to generate a special function for it... + return { size: 0, syncFunc: uboUpdate }; + } + var usedUniformDatas = getUBOData(group.uniforms, uniformData); + var _a = createUBOElements(usedUniformDatas), uboElements = _a.uboElements, size = _a.size; + var funcFragments = ["\n var v = null;\n var v2 = null;\n var cv = null;\n var t = 0;\n var gl = renderer.gl\n var index = 0;\n var data = buffer.data;\n "]; + for (var i = 0; i < uboElements.length; i++) { + var uboElement = uboElements[i]; + var uniform = group.uniforms[uboElement.data.name]; + var name = uboElement.data.name; + var parsed = false; + for (var j = 0; j < uniformParsers.length; j++) { + var uniformParser = uniformParsers[j]; + if (uniformParser.codeUbo && uniformParser.test(uboElement.data, uniform)) { + funcFragments.push("offset = " + uboElement.offset / 4 + ";", uniformParsers[j].codeUbo(uboElement.data.name, uniform)); + parsed = true; + break; + } + } + if (!parsed) { + if (uboElement.data.size > 1) { + var size_1 = mapSize(uboElement.data.type); + var rowSize = Math.max(GLSL_TO_STD40_SIZE[uboElement.data.type] / 16, 1); + var elementSize = size_1 / rowSize; + var remainder = (4 - (elementSize % 4)) % 4; + funcFragments.push("\n cv = ud." + name + ".value;\n v = uv." + name + ";\n offset = " + uboElement.offset / 4 + ";\n\n t = 0;\n\n for(var i=0; i < " + uboElement.data.size * rowSize + "; i++)\n {\n for(var j = 0; j < " + elementSize + "; j++)\n {\n data[offset++] = v[t++];\n }\n offset += " + remainder + ";\n }\n\n "); + } + else { + var template = UBO_TO_SINGLE_SETTERS[uboElement.data.type]; + funcFragments.push("\n cv = ud." + name + ".value;\n v = uv." + name + ";\n offset = " + uboElement.offset / 4 + ";\n " + template + ";\n "); + } + } + } + funcFragments.push("\n renderer.buffer.update(buffer);\n "); + return { + size: size, + // eslint-disable-next-line no-new-func + syncFunc: new Function('ud', 'uv', 'renderer', 'syncData', 'buffer', funcFragments.join('\n')) + }; + } -// References: -// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ -// https://gist.github.com/1579671 -// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision -// https://gist.github.com/timhall/4078614 -// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + /** + * @private + */ + var IGLUniformData = /** @class */ (function () { + function IGLUniformData() { + } + return IGLUniformData; + }()); + /** + * Helper class to create a WebGL Program + * @memberof PIXI + */ + var GLProgram = /** @class */ (function () { + /** + * Makes a new Pixi program. + * @param program - webgl program + * @param uniformData - uniforms + */ + function GLProgram(program, uniformData) { + this.program = program; + this.uniformData = uniformData; + this.uniformGroups = {}; + this.uniformDirtyGroups = {}; + this.uniformBufferBindings = {}; + } + /** Destroys this program. */ + GLProgram.prototype.destroy = function () { + this.uniformData = null; + this.uniformGroups = null; + this.uniformDirtyGroups = null; + this.uniformBufferBindings = null; + this.program = null; + }; + return GLProgram; + }()); -// Expected to be used with Browserfiy -// Browserify automatically detects the use of `global` and passes the -// correct reference of `global`, `self`, and finally `window` + /** + * returns the attribute data from the program + * @private + * @param {WebGLProgram} [program] - the WebGL program + * @param {WebGLRenderingContext} [gl] - the WebGL context + * @returns {object} the attribute data for this program + */ + function getAttributeData(program, gl) { + var attributes = {}; + var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + for (var i = 0; i < totalAttributes; i++) { + var attribData = gl.getActiveAttrib(program, i); + if (attribData.name.indexOf('gl_') === 0) { + continue; + } + var type = mapType(gl, attribData.type); + var data = { + type: type, + name: attribData.name, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + }; + attributes[attribData.name] = data; + } + return attributes; + } -var ONE_FRAME_TIME = 16; + /** + * returns the uniform data from the program + * @private + * @param program - the webgl program + * @param gl - the WebGL context + * @returns {object} the uniform data for this program + */ + function getUniformData(program, gl) { + var uniforms = {}; + var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + for (var i = 0; i < totalUniforms; i++) { + var uniformData = gl.getActiveUniform(program, i); + var name = uniformData.name.replace(/\[.*?\]$/, ''); + var isArray = !!(uniformData.name.match(/\[.*?\]$/)); + var type = mapType(gl, uniformData.type); + uniforms[name] = { + name: name, + index: i, + type: type, + size: uniformData.size, + isArray: isArray, + value: defaultValue(type, uniformData.size), + }; + } + return uniforms; + } -// Date.now -if (!(Date.now && Date.prototype.getTime)) { - Date.now = function now() { - return new Date().getTime(); - }; -} + /** + * generates a WebGL Program object from a high level Pixi Program. + * @param gl - a rendering context on which to generate the program + * @param program - the high level Pixi Program. + */ + function generateProgram(gl, program) { + var glVertShader = compileShader(gl, gl.VERTEX_SHADER, program.vertexSrc); + var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, program.fragmentSrc); + var webGLProgram = gl.createProgram(); + gl.attachShader(webGLProgram, glVertShader); + gl.attachShader(webGLProgram, glFragShader); + gl.linkProgram(webGLProgram); + if (!gl.getProgramParameter(webGLProgram, gl.LINK_STATUS)) { + logProgramError(gl, webGLProgram, glVertShader, glFragShader); + } + program.attributeData = getAttributeData(webGLProgram, gl); + program.uniformData = getUniformData(webGLProgram, gl); + // GLSL 1.00: bind attributes sorted by name in ascending order + // GLSL 3.00: don't change the attribute locations that where chosen by the compiler + // or assigned by the layout specifier in the shader source code + if (!(/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m).test(program.vertexSrc)) { + var keys = Object.keys(program.attributeData); + keys.sort(function (a, b) { return (a > b) ? 1 : -1; }); // eslint-disable-line no-confusing-arrow + for (var i = 0; i < keys.length; i++) { + program.attributeData[keys[i]].location = i; + gl.bindAttribLocation(webGLProgram, i, keys[i]); + } + gl.linkProgram(webGLProgram); + } + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + var uniformData = {}; + for (var i in program.uniformData) { + var data = program.uniformData[i]; + uniformData[i] = { + location: gl.getUniformLocation(webGLProgram, i), + value: defaultValue(data.type, data.size), + }; + } + var glProgram = new GLProgram(webGLProgram, uniformData); + return glProgram; + } -// performance.now -if (!(global.performance && global.performance.now)) { - var startTime = Date.now(); + var UID = 0; + // default sync data so we don't create a new one each time! + var defaultSyncData = { textureCount: 0, uboCount: 0 }; + /** + * System plugin to the renderer to manage shaders. + * @memberof PIXI + */ + var ShaderSystem = /** @class */ (function () { + /** @param renderer - The renderer this System works for. */ + function ShaderSystem(renderer) { + this.destroyed = false; + this.renderer = renderer; + // Validation check that this environment support `new Function` + this.systemCheck(); + this.gl = null; + this.shader = null; + this.program = null; + this.cache = {}; + this._uboCache = {}; + this.id = UID++; + } + /** + * Overrideable function by `@pixi/unsafe-eval` to silence + * throwing an error if platform doesn't support unsafe-evals. + * @private + */ + ShaderSystem.prototype.systemCheck = function () { + if (!unsafeEvalSupported()) { + throw new Error('Current environment does not allow unsafe-eval, ' + + 'please use @pixi/unsafe-eval module to enable support.'); + } + }; + ShaderSystem.prototype.contextChange = function (gl) { + this.gl = gl; + this.reset(); + }; + /** + * Changes the current shader to the one given in parameter. + * @param shader - the new shader + * @param dontSync - false if the shader should automatically sync its uniforms. + * @returns the glProgram that belongs to the shader. + */ + ShaderSystem.prototype.bind = function (shader, dontSync) { + shader.disposeRunner.add(this); + shader.uniforms.globals = this.renderer.globalUniforms; + var program = shader.program; + var glProgram = program.glPrograms[this.renderer.CONTEXT_UID] || this.generateProgram(shader); + this.shader = shader; + // TODO - some current Pixi plugins bypass this.. so it not safe to use yet.. + if (this.program !== program) { + this.program = program; + this.gl.useProgram(glProgram.program); + } + if (!dontSync) { + defaultSyncData.textureCount = 0; + defaultSyncData.uboCount = 0; + this.syncUniformGroup(shader.uniformGroup, defaultSyncData); + } + return glProgram; + }; + /** + * Uploads the uniforms values to the currently bound shader. + * @param uniforms - the uniforms values that be applied to the current shader + */ + ShaderSystem.prototype.setUniforms = function (uniforms) { + var shader = this.shader.program; + var glProgram = shader.glPrograms[this.renderer.CONTEXT_UID]; + shader.syncUniforms(glProgram.uniformData, uniforms, this.renderer); + }; + /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ + /** + * Syncs uniforms on the group + * @param group - the uniform group to sync + * @param syncData - this is data that is passed to the sync function and any nested sync functions + */ + ShaderSystem.prototype.syncUniformGroup = function (group, syncData) { + var glProgram = this.getGlProgram(); + if (!group.static || group.dirtyId !== glProgram.uniformDirtyGroups[group.id]) { + glProgram.uniformDirtyGroups[group.id] = group.dirtyId; + this.syncUniforms(group, glProgram, syncData); + } + }; + /** + * Overrideable by the @pixi/unsafe-eval package to use static syncUniforms instead. + * @param group + * @param glProgram + * @param syncData + */ + ShaderSystem.prototype.syncUniforms = function (group, glProgram, syncData) { + var syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); + syncFunc(glProgram.uniformData, group.uniforms, this.renderer, syncData); + }; + ShaderSystem.prototype.createSyncGroups = function (group) { + var id = this.getSignature(group, this.shader.program.uniformData, 'u'); + if (!this.cache[id]) { + this.cache[id] = generateUniformsSync(group, this.shader.program.uniformData); + } + group.syncUniforms[this.shader.program.id] = this.cache[id]; + return group.syncUniforms[this.shader.program.id]; + }; + /** + * Syncs uniform buffers + * @param group - the uniform buffer group to sync + * @param name - the name of the uniform buffer + */ + ShaderSystem.prototype.syncUniformBufferGroup = function (group, name) { + var glProgram = this.getGlProgram(); + if (!group.static || group.dirtyId !== 0 || !glProgram.uniformGroups[group.id]) { + group.dirtyId = 0; + var syncFunc = glProgram.uniformGroups[group.id] + || this.createSyncBufferGroup(group, glProgram, name); + // TODO wrap update in a cache?? + group.buffer.update(); + syncFunc(glProgram.uniformData, group.uniforms, this.renderer, defaultSyncData, group.buffer); + } + this.renderer.buffer.bindBufferBase(group.buffer, glProgram.uniformBufferBindings[name]); + }; + /** + * Will create a function that uploads a uniform buffer using the STD140 standard. + * The upload function will then be cached for future calls + * If a group is manually managed, then a simple upload function is generated + * @param group - the uniform buffer group to sync + * @param glProgram - the gl program to attach the uniform bindings to + * @param name - the name of the uniform buffer (must exist on the shader) + */ + ShaderSystem.prototype.createSyncBufferGroup = function (group, glProgram, name) { + var gl = this.renderer.gl; + this.renderer.buffer.bind(group.buffer); + // bind them... + var uniformBlockIndex = this.gl.getUniformBlockIndex(glProgram.program, name); + glProgram.uniformBufferBindings[name] = this.shader.uniformBindCount; + gl.uniformBlockBinding(glProgram.program, uniformBlockIndex, this.shader.uniformBindCount); + this.shader.uniformBindCount++; + var id = this.getSignature(group, this.shader.program.uniformData, 'ubo'); + var uboData = this._uboCache[id]; + if (!uboData) { + uboData = this._uboCache[id] = generateUniformBufferSync(group, this.shader.program.uniformData); + } + if (group.autoManage) { + var data = new Float32Array(uboData.size / 4); + group.buffer.update(data); + } + glProgram.uniformGroups[group.id] = uboData.syncFunc; + return glProgram.uniformGroups[group.id]; + }; + /** + * Takes a uniform group and data and generates a unique signature for them. + * @param group - The uniform group to get signature of + * @param group.uniforms + * @param uniformData - Uniform information generated by the shader + * @param preFix + * @returns Unique signature of the uniform group + */ + ShaderSystem.prototype.getSignature = function (group, uniformData, preFix) { + var uniforms = group.uniforms; + var strings = [preFix + "-"]; + for (var i in uniforms) { + strings.push(i); + if (uniformData[i]) { + strings.push(uniformData[i].type); + } + } + return strings.join('-'); + }; + /** + * Returns the underlying GLShade rof the currently bound shader. + * + * This can be handy for when you to have a little more control over the setting of your uniforms. + * @returns The glProgram for the currently bound Shader for this context + */ + ShaderSystem.prototype.getGlProgram = function () { + if (this.shader) { + return this.shader.program.glPrograms[this.renderer.CONTEXT_UID]; + } + return null; + }; + /** + * Generates a glProgram version of the Shader provided. + * @param shader - The shader that the glProgram will be based on. + * @returns A shiny new glProgram! + */ + ShaderSystem.prototype.generateProgram = function (shader) { + var gl = this.gl; + var program = shader.program; + var glProgram = generateProgram(gl, program); + program.glPrograms[this.renderer.CONTEXT_UID] = glProgram; + return glProgram; + }; + /** Resets ShaderSystem state, does not affect WebGL state. */ + ShaderSystem.prototype.reset = function () { + this.program = null; + this.shader = null; + }; + /** + * Disposes shader. + * If disposing one equals with current shader, set current as null. + * @param shader - Shader object + */ + ShaderSystem.prototype.disposeShader = function (shader) { + if (this.shader === shader) { + this.shader = null; + } + }; + /** Destroys this System and removes all its textures. */ + ShaderSystem.prototype.destroy = function () { + this.renderer = null; + // TODO implement destroy method for ShaderSystem + this.destroyed = true; + }; + return ShaderSystem; + }()); - if (!global.performance) { - global.performance = {}; - } + /** + * Maps gl blend combinations to WebGL. + * @memberof PIXI + * @function mapWebGLBlendModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {number[][]} [array=[]] - The array to output into. + * @returns {number[][]} Mapped modes. + */ + function mapWebGLBlendModesToPixi(gl, array) { + if (array === void 0) { array = []; } + // TODO - premultiply alpha would be different. + // add a boolean for that! + array[exports.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.ADD] = [gl.ONE, gl.ONE]; + array[exports.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.NONE] = [0, 0]; + // not-premultiplied blend modes + array[exports.BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE]; + array[exports.BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + // composite operations + array[exports.BLEND_MODES.SRC_IN] = [gl.DST_ALPHA, gl.ZERO]; + array[exports.BLEND_MODES.SRC_OUT] = [gl.ONE_MINUS_DST_ALPHA, gl.ZERO]; + array[exports.BLEND_MODES.SRC_ATOP] = [gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.DST_OVER] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE]; + array[exports.BLEND_MODES.DST_IN] = [gl.ZERO, gl.SRC_ALPHA]; + array[exports.BLEND_MODES.DST_OUT] = [gl.ZERO, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.DST_ATOP] = [gl.ONE_MINUS_DST_ALPHA, gl.SRC_ALPHA]; + array[exports.BLEND_MODES.XOR] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA]; + // SUBTRACT from flash + array[exports.BLEND_MODES.SUBTRACT] = [gl.ONE, gl.ONE, gl.ONE, gl.ONE, gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD]; + return array; + } - global.performance.now = function () { - return Date.now() - startTime; - }; -} + var BLEND = 0; + var OFFSET = 1; + var CULLING = 2; + var DEPTH_TEST = 3; + var WINDING = 4; + var DEPTH_MASK = 5; + /** + * System plugin to the renderer to manage WebGL state machines. + * @memberof PIXI + */ + var StateSystem = /** @class */ (function () { + function StateSystem() { + this.gl = null; + this.stateId = 0; + this.polygonOffset = 0; + this.blendMode = exports.BLEND_MODES.NONE; + this._blendEq = false; + // map functions for when we set state.. + this.map = []; + this.map[BLEND] = this.setBlend; + this.map[OFFSET] = this.setOffset; + this.map[CULLING] = this.setCullFace; + this.map[DEPTH_TEST] = this.setDepthTest; + this.map[WINDING] = this.setFrontFace; + this.map[DEPTH_MASK] = this.setDepthMask; + this.checks = []; + this.defaultState = new State(); + this.defaultState.blend = true; + } + StateSystem.prototype.contextChange = function (gl) { + this.gl = gl; + this.blendModes = mapWebGLBlendModesToPixi(gl); + this.set(this.defaultState); + this.reset(); + }; + /** + * Sets the current state + * @param {*} state - The state to set. + */ + StateSystem.prototype.set = function (state) { + state = state || this.defaultState; + // TODO maybe to an object check? ( this.state === state )? + if (this.stateId !== state.data) { + var diff = this.stateId ^ state.data; + var i = 0; + // order from least to most common + while (diff) { + if (diff & 1) { + // state change! + this.map[i].call(this, !!(state.data & (1 << i))); + } + diff = diff >> 1; + i++; + } + this.stateId = state.data; + } + // based on the above settings we check for specific modes.. + // for example if blend is active we check and set the blend modes + // or of polygon offset is active we check the poly depth. + for (var i = 0; i < this.checks.length; i++) { + this.checks[i](this, state); + } + }; + /** + * Sets the state, when previous state is unknown. + * @param {*} state - The state to set + */ + StateSystem.prototype.forceState = function (state) { + state = state || this.defaultState; + for (var i = 0; i < this.map.length; i++) { + this.map[i].call(this, !!(state.data & (1 << i))); + } + for (var i = 0; i < this.checks.length; i++) { + this.checks[i](this, state); + } + this.stateId = state.data; + }; + /** + * Sets whether to enable or disable blending. + * @param value - Turn on or off WebGl blending. + */ + StateSystem.prototype.setBlend = function (value) { + this.updateCheck(StateSystem.checkBlendMode, value); + this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); + }; + /** + * Sets whether to enable or disable polygon offset fill. + * @param value - Turn on or off webgl polygon offset testing. + */ + StateSystem.prototype.setOffset = function (value) { + this.updateCheck(StateSystem.checkPolygonOffset, value); + this.gl[value ? 'enable' : 'disable'](this.gl.POLYGON_OFFSET_FILL); + }; + /** + * Sets whether to enable or disable depth test. + * @param value - Turn on or off webgl depth testing. + */ + StateSystem.prototype.setDepthTest = function (value) { + this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); + }; + /** + * Sets whether to enable or disable depth mask. + * @param value - Turn on or off webgl depth mask. + */ + StateSystem.prototype.setDepthMask = function (value) { + this.gl.depthMask(value); + }; + /** + * Sets whether to enable or disable cull face. + * @param {boolean} value - Turn on or off webgl cull face. + */ + StateSystem.prototype.setCullFace = function (value) { + this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); + }; + /** + * Sets the gl front face. + * @param {boolean} value - true is clockwise and false is counter-clockwise + */ + StateSystem.prototype.setFrontFace = function (value) { + this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); + }; + /** + * Sets the blend mode. + * @param {number} value - The blend mode to set to. + */ + StateSystem.prototype.setBlendMode = function (value) { + if (value === this.blendMode) { + return; + } + this.blendMode = value; + var mode = this.blendModes[value]; + var gl = this.gl; + if (mode.length === 2) { + gl.blendFunc(mode[0], mode[1]); + } + else { + gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]); + } + if (mode.length === 6) { + this._blendEq = true; + gl.blendEquationSeparate(mode[4], mode[5]); + } + else if (this._blendEq) { + this._blendEq = false; + gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); + } + }; + /** + * Sets the polygon offset. + * @param {number} value - the polygon offset + * @param {number} scale - the polygon offset scale + */ + StateSystem.prototype.setPolygonOffset = function (value, scale) { + this.gl.polygonOffset(value, scale); + }; + // used + /** Resets all the logic and disables the VAOs. */ + StateSystem.prototype.reset = function () { + this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); + this.forceState(this.defaultState); + this._blendEq = true; + this.blendMode = -1; + this.setBlendMode(0); + }; + /** + * Checks to see which updates should be checked based on which settings have been activated. + * + * For example, if blend is enabled then we should check the blend modes each time the state is changed + * or if polygon fill is activated then we need to check if the polygon offset changes. + * The idea is that we only check what we have too. + * @param func - the checking function to add or remove + * @param value - should the check function be added or removed. + */ + StateSystem.prototype.updateCheck = function (func, value) { + var index = this.checks.indexOf(func); + if (value && index === -1) { + this.checks.push(func); + } + else if (!value && index !== -1) { + this.checks.splice(index, 1); + } + }; + /** + * A private little wrapper function that we call to check the blend mode. + * @param system - the System to perform the state check on + * @param state - the state that the blendMode will pulled from + */ + StateSystem.checkBlendMode = function (system, state) { + system.setBlendMode(state.blendMode); + }; + /** + * A private little wrapper function that we call to check the polygon offset. + * @param system - the System to perform the state check on + * @param state - the state that the blendMode will pulled from + */ + StateSystem.checkPolygonOffset = function (system, state) { + system.setPolygonOffset(1, state.polygonOffset); + }; + /** + * @ignore + */ + StateSystem.prototype.destroy = function () { + this.gl = null; + }; + return StateSystem; + }()); -// requestAnimationFrame -var lastTime = Date.now(); -var vendors = ['ms', 'moz', 'webkit', 'o']; + /** + * System plugin to the renderer to manage texture garbage collection on the GPU, + * ensuring that it does not get clogged up with textures that are no longer being used. + * @memberof PIXI + */ + var TextureGCSystem = /** @class */ (function () { + /** @param renderer - The renderer this System works for. */ + function TextureGCSystem(renderer) { + this.renderer = renderer; + this.count = 0; + this.checkCount = 0; + this.maxIdle = settings.GC_MAX_IDLE; + this.checkCountMax = settings.GC_MAX_CHECK_COUNT; + this.mode = settings.GC_MODE; + } + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + TextureGCSystem.prototype.postrender = function () { + if (!this.renderer.renderingToScreen) { + return; + } + this.count++; + if (this.mode === exports.GC_MODES.MANUAL) { + return; + } + this.checkCount++; + if (this.checkCount > this.checkCountMax) { + this.checkCount = 0; + this.run(); + } + }; + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + TextureGCSystem.prototype.run = function () { + var tm = this.renderer.texture; + var managedTextures = tm.managedTextures; + var wasRemoved = false; + for (var i = 0; i < managedTextures.length; i++) { + var texture = managedTextures[i]; + // only supports non generated textures at the moment! + if (!texture.framebuffer && this.count - texture.touched > this.maxIdle) { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + if (wasRemoved) { + var j = 0; + for (var i = 0; i < managedTextures.length; i++) { + if (managedTextures[i] !== null) { + managedTextures[j++] = managedTextures[i]; + } + } + managedTextures.length = j; + } + }; + /** + * Removes all the textures within the specified displayObject and its children from the GPU + * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. + */ + TextureGCSystem.prototype.unload = function (displayObject) { + var tm = this.renderer.texture; + var texture = displayObject._texture; + // only destroy non generated textures + if (texture && !texture.framebuffer) { + tm.destroyTexture(texture); + } + for (var i = displayObject.children.length - 1; i >= 0; i--) { + this.unload(displayObject.children[i]); + } + }; + TextureGCSystem.prototype.destroy = function () { + this.renderer = null; + }; + return TextureGCSystem; + }()); -for (var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) { - var p = vendors[x]; + /** + * Returns a lookup table that maps each type-format pair to a compatible internal format. + * @memberof PIXI + * @function mapTypeAndFormatToInternalFormat + * @private + * @param {WebGLRenderingContext} gl - The rendering context. + * @returns Lookup table. + */ + function mapTypeAndFormatToInternalFormat(gl) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x; + var table; + if ('WebGL2RenderingContext' in globalThis && gl instanceof globalThis.WebGL2RenderingContext) { + table = (_a = {}, + _a[exports.TYPES.UNSIGNED_BYTE] = (_b = {}, + _b[exports.FORMATS.RGBA] = gl.RGBA8, + _b[exports.FORMATS.RGB] = gl.RGB8, + _b[exports.FORMATS.RG] = gl.RG8, + _b[exports.FORMATS.RED] = gl.R8, + _b[exports.FORMATS.RGBA_INTEGER] = gl.RGBA8UI, + _b[exports.FORMATS.RGB_INTEGER] = gl.RGB8UI, + _b[exports.FORMATS.RG_INTEGER] = gl.RG8UI, + _b[exports.FORMATS.RED_INTEGER] = gl.R8UI, + _b[exports.FORMATS.ALPHA] = gl.ALPHA, + _b[exports.FORMATS.LUMINANCE] = gl.LUMINANCE, + _b[exports.FORMATS.LUMINANCE_ALPHA] = gl.LUMINANCE_ALPHA, + _b), + _a[exports.TYPES.BYTE] = (_c = {}, + _c[exports.FORMATS.RGBA] = gl.RGBA8_SNORM, + _c[exports.FORMATS.RGB] = gl.RGB8_SNORM, + _c[exports.FORMATS.RG] = gl.RG8_SNORM, + _c[exports.FORMATS.RED] = gl.R8_SNORM, + _c[exports.FORMATS.RGBA_INTEGER] = gl.RGBA8I, + _c[exports.FORMATS.RGB_INTEGER] = gl.RGB8I, + _c[exports.FORMATS.RG_INTEGER] = gl.RG8I, + _c[exports.FORMATS.RED_INTEGER] = gl.R8I, + _c), + _a[exports.TYPES.UNSIGNED_SHORT] = (_d = {}, + _d[exports.FORMATS.RGBA_INTEGER] = gl.RGBA16UI, + _d[exports.FORMATS.RGB_INTEGER] = gl.RGB16UI, + _d[exports.FORMATS.RG_INTEGER] = gl.RG16UI, + _d[exports.FORMATS.RED_INTEGER] = gl.R16UI, + _d[exports.FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT16, + _d), + _a[exports.TYPES.SHORT] = (_e = {}, + _e[exports.FORMATS.RGBA_INTEGER] = gl.RGBA16I, + _e[exports.FORMATS.RGB_INTEGER] = gl.RGB16I, + _e[exports.FORMATS.RG_INTEGER] = gl.RG16I, + _e[exports.FORMATS.RED_INTEGER] = gl.R16I, + _e), + _a[exports.TYPES.UNSIGNED_INT] = (_f = {}, + _f[exports.FORMATS.RGBA_INTEGER] = gl.RGBA32UI, + _f[exports.FORMATS.RGB_INTEGER] = gl.RGB32UI, + _f[exports.FORMATS.RG_INTEGER] = gl.RG32UI, + _f[exports.FORMATS.RED_INTEGER] = gl.R32UI, + _f[exports.FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT24, + _f), + _a[exports.TYPES.INT] = (_g = {}, + _g[exports.FORMATS.RGBA_INTEGER] = gl.RGBA32I, + _g[exports.FORMATS.RGB_INTEGER] = gl.RGB32I, + _g[exports.FORMATS.RG_INTEGER] = gl.RG32I, + _g[exports.FORMATS.RED_INTEGER] = gl.R32I, + _g), + _a[exports.TYPES.FLOAT] = (_h = {}, + _h[exports.FORMATS.RGBA] = gl.RGBA32F, + _h[exports.FORMATS.RGB] = gl.RGB32F, + _h[exports.FORMATS.RG] = gl.RG32F, + _h[exports.FORMATS.RED] = gl.R32F, + _h[exports.FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT32F, + _h), + _a[exports.TYPES.HALF_FLOAT] = (_j = {}, + _j[exports.FORMATS.RGBA] = gl.RGBA16F, + _j[exports.FORMATS.RGB] = gl.RGB16F, + _j[exports.FORMATS.RG] = gl.RG16F, + _j[exports.FORMATS.RED] = gl.R16F, + _j), + _a[exports.TYPES.UNSIGNED_SHORT_5_6_5] = (_k = {}, + _k[exports.FORMATS.RGB] = gl.RGB565, + _k), + _a[exports.TYPES.UNSIGNED_SHORT_4_4_4_4] = (_l = {}, + _l[exports.FORMATS.RGBA] = gl.RGBA4, + _l), + _a[exports.TYPES.UNSIGNED_SHORT_5_5_5_1] = (_m = {}, + _m[exports.FORMATS.RGBA] = gl.RGB5_A1, + _m), + _a[exports.TYPES.UNSIGNED_INT_2_10_10_10_REV] = (_o = {}, + _o[exports.FORMATS.RGBA] = gl.RGB10_A2, + _o[exports.FORMATS.RGBA_INTEGER] = gl.RGB10_A2UI, + _o), + _a[exports.TYPES.UNSIGNED_INT_10F_11F_11F_REV] = (_p = {}, + _p[exports.FORMATS.RGB] = gl.R11F_G11F_B10F, + _p), + _a[exports.TYPES.UNSIGNED_INT_5_9_9_9_REV] = (_q = {}, + _q[exports.FORMATS.RGB] = gl.RGB9_E5, + _q), + _a[exports.TYPES.UNSIGNED_INT_24_8] = (_r = {}, + _r[exports.FORMATS.DEPTH_STENCIL] = gl.DEPTH24_STENCIL8, + _r), + _a[exports.TYPES.FLOAT_32_UNSIGNED_INT_24_8_REV] = (_s = {}, + _s[exports.FORMATS.DEPTH_STENCIL] = gl.DEPTH32F_STENCIL8, + _s), + _a); + } + else { + table = (_t = {}, + _t[exports.TYPES.UNSIGNED_BYTE] = (_u = {}, + _u[exports.FORMATS.RGBA] = gl.RGBA, + _u[exports.FORMATS.RGB] = gl.RGB, + _u[exports.FORMATS.ALPHA] = gl.ALPHA, + _u[exports.FORMATS.LUMINANCE] = gl.LUMINANCE, + _u[exports.FORMATS.LUMINANCE_ALPHA] = gl.LUMINANCE_ALPHA, + _u), + _t[exports.TYPES.UNSIGNED_SHORT_5_6_5] = (_v = {}, + _v[exports.FORMATS.RGB] = gl.RGB, + _v), + _t[exports.TYPES.UNSIGNED_SHORT_4_4_4_4] = (_w = {}, + _w[exports.FORMATS.RGBA] = gl.RGBA, + _w), + _t[exports.TYPES.UNSIGNED_SHORT_5_5_5_1] = (_x = {}, + _x[exports.FORMATS.RGBA] = gl.RGBA, + _x), + _t); + } + return table; + } - global.requestAnimationFrame = global[p + 'RequestAnimationFrame']; - global.cancelAnimationFrame = global[p + 'CancelAnimationFrame'] || global[p + 'CancelRequestAnimationFrame']; -} + /** + * Internal texture for WebGL context. + * @memberof PIXI + */ + var GLTexture = /** @class */ (function () { + function GLTexture(texture) { + this.texture = texture; + this.width = -1; + this.height = -1; + this.dirtyId = -1; + this.dirtyStyleId = -1; + this.mipmap = false; + this.wrapMode = 33071; + this.type = exports.TYPES.UNSIGNED_BYTE; + this.internalFormat = exports.FORMATS.RGBA; + this.samplerType = 0; + } + return GLTexture; + }()); -if (!global.requestAnimationFrame) { - global.requestAnimationFrame = function (callback) { - if (typeof callback !== 'function') { - throw new TypeError(callback + 'is not a function'); - } + /** + * System plugin to the renderer to manage textures. + * @memberof PIXI + */ + var TextureSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this system works for. + */ + function TextureSystem(renderer) { + this.renderer = renderer; + // TODO set to max textures... + this.boundTextures = []; + this.currentLocation = -1; + this.managedTextures = []; + this._unknownBoundTextures = false; + this.unknownTexture = new BaseTexture(); + this.hasIntegerTextures = false; + } + /** Sets up the renderer context and necessary buffers. */ + TextureSystem.prototype.contextChange = function () { + var gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.webGLVersion = this.renderer.context.webGLVersion; + this.internalFormats = mapTypeAndFormatToInternalFormat(gl); + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.boundTextures.length = maxTextures; + for (var i = 0; i < maxTextures; i++) { + this.boundTextures[i] = null; + } + // TODO move this.. to a nice make empty textures class.. + this.emptyTextures = {}; + var emptyTexture2D = new GLTexture(gl.createTexture()); + gl.bindTexture(gl.TEXTURE_2D, emptyTexture2D.texture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4)); + this.emptyTextures[gl.TEXTURE_2D] = emptyTexture2D; + this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(gl.createTexture()); + gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); + for (var i = 0; i < 6; i++) { + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + } + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + for (var i = 0; i < this.boundTextures.length; i++) { + this.bind(null, i); + } + }; + /** + * Bind a texture to a specific location + * + * If you want to unbind something, please use `unbind(texture)` instead of `bind(null, textureLocation)` + * @param texture - Texture to bind + * @param [location=0] - Location to bind at + */ + TextureSystem.prototype.bind = function (texture, location) { + if (location === void 0) { location = 0; } + var gl = this.gl; + texture = texture === null || texture === void 0 ? void 0 : texture.castToBaseTexture(); + // cannot bind partial texture + // TODO: report a warning + if (texture && texture.valid && !texture.parentTextureArray) { + texture.touched = this.renderer.textureGC.count; + var glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + if (this.boundTextures[location] !== texture) { + if (this.currentLocation !== location) { + this.currentLocation = location; + gl.activeTexture(gl.TEXTURE0 + location); + } + gl.bindTexture(texture.target, glTexture.texture); + } + if (glTexture.dirtyId !== texture.dirtyId) { + if (this.currentLocation !== location) { + this.currentLocation = location; + gl.activeTexture(gl.TEXTURE0 + location); + } + this.updateTexture(texture); + } + else if (glTexture.dirtyStyleId !== texture.dirtyStyleId) { + this.updateTextureStyle(texture); + } + this.boundTextures[location] = texture; + } + else { + if (this.currentLocation !== location) { + this.currentLocation = location; + gl.activeTexture(gl.TEXTURE0 + location); + } + gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[gl.TEXTURE_2D].texture); + this.boundTextures[location] = null; + } + }; + /** Resets texture location and bound textures Actual `bind(null, i)` calls will be performed at next `unbind()` call */ + TextureSystem.prototype.reset = function () { + this._unknownBoundTextures = true; + this.hasIntegerTextures = false; + this.currentLocation = -1; + for (var i = 0; i < this.boundTextures.length; i++) { + this.boundTextures[i] = this.unknownTexture; + } + }; + /** + * Unbind a texture. + * @param texture - Texture to bind + */ + TextureSystem.prototype.unbind = function (texture) { + var _a = this, gl = _a.gl, boundTextures = _a.boundTextures; + if (this._unknownBoundTextures) { + this._unknownBoundTextures = false; + // someone changed webGL state, + // we have to be sure that our texture does not appear in multi-texture renderer samplers + for (var i = 0; i < boundTextures.length; i++) { + if (boundTextures[i] === this.unknownTexture) { + this.bind(null, i); + } + } + } + for (var i = 0; i < boundTextures.length; i++) { + if (boundTextures[i] === texture) { + if (this.currentLocation !== i) { + gl.activeTexture(gl.TEXTURE0 + i); + this.currentLocation = i; + } + gl.bindTexture(texture.target, this.emptyTextures[texture.target].texture); + boundTextures[i] = null; + } + } + }; + /** + * Ensures that current boundTextures all have FLOAT sampler type, + * see {@link PIXI.SAMPLER_TYPES} for explanation. + * @param maxTextures - number of locations to check + */ + TextureSystem.prototype.ensureSamplerType = function (maxTextures) { + var _a = this, boundTextures = _a.boundTextures, hasIntegerTextures = _a.hasIntegerTextures, CONTEXT_UID = _a.CONTEXT_UID; + if (!hasIntegerTextures) { + return; + } + for (var i = maxTextures - 1; i >= 0; --i) { + var tex = boundTextures[i]; + if (tex) { + var glTexture = tex._glTextures[CONTEXT_UID]; + if (glTexture.samplerType !== exports.SAMPLER_TYPES.FLOAT) { + this.renderer.texture.unbind(tex); + } + } + } + }; + /** + * Initialize a texture + * @private + * @param texture - Texture to initialize + */ + TextureSystem.prototype.initTexture = function (texture) { + var glTexture = new GLTexture(this.gl.createTexture()); + // guarantee an update.. + glTexture.dirtyId = -1; + texture._glTextures[this.CONTEXT_UID] = glTexture; + this.managedTextures.push(texture); + texture.on('dispose', this.destroyTexture, this); + return glTexture; + }; + TextureSystem.prototype.initTextureType = function (texture, glTexture) { + var _a, _b; + glTexture.internalFormat = (_b = (_a = this.internalFormats[texture.type]) === null || _a === void 0 ? void 0 : _a[texture.format]) !== null && _b !== void 0 ? _b : texture.format; + if (this.webGLVersion === 2 && texture.type === exports.TYPES.HALF_FLOAT) { + // TYPES.HALF_FLOAT is WebGL1 HALF_FLOAT_OES + // we have to convert it to WebGL HALF_FLOAT + glTexture.type = this.gl.HALF_FLOAT; + } + else { + glTexture.type = texture.type; + } + }; + /** + * Update a texture + * @private + * @param {PIXI.BaseTexture} texture - Texture to initialize + */ + TextureSystem.prototype.updateTexture = function (texture) { + var glTexture = texture._glTextures[this.CONTEXT_UID]; + if (!glTexture) { + return; + } + var renderer = this.renderer; + this.initTextureType(texture, glTexture); + if (texture.resource && texture.resource.upload(renderer, texture, glTexture)) { + // texture is uploaded, dont do anything! + if (glTexture.samplerType !== exports.SAMPLER_TYPES.FLOAT) { + this.hasIntegerTextures = true; + } + } + else { + // default, renderTexture-like logic + var width = texture.realWidth; + var height = texture.realHeight; + var gl = renderer.gl; + if (glTexture.width !== width + || glTexture.height !== height + || glTexture.dirtyId < 0) { + glTexture.width = width; + glTexture.height = height; + gl.texImage2D(texture.target, 0, glTexture.internalFormat, width, height, 0, texture.format, glTexture.type, null); + } + } + // lets only update what changes.. + if (texture.dirtyStyleId !== glTexture.dirtyStyleId) { + this.updateTextureStyle(texture); + } + glTexture.dirtyId = texture.dirtyId; + }; + /** + * Deletes the texture from WebGL + * @private + * @param texture - the texture to destroy + * @param [skipRemove=false] - Whether to skip removing the texture from the TextureManager. + */ + TextureSystem.prototype.destroyTexture = function (texture, skipRemove) { + var gl = this.gl; + texture = texture.castToBaseTexture(); + if (texture._glTextures[this.CONTEXT_UID]) { + this.unbind(texture); + gl.deleteTexture(texture._glTextures[this.CONTEXT_UID].texture); + texture.off('dispose', this.destroyTexture, this); + delete texture._glTextures[this.CONTEXT_UID]; + if (!skipRemove) { + var i = this.managedTextures.indexOf(texture); + if (i !== -1) { + removeItems(this.managedTextures, i, 1); + } + } + } + }; + /** + * Update texture style such as mipmap flag + * @private + * @param {PIXI.BaseTexture} texture - Texture to update + */ + TextureSystem.prototype.updateTextureStyle = function (texture) { + var glTexture = texture._glTextures[this.CONTEXT_UID]; + if (!glTexture) { + return; + } + if ((texture.mipmap === exports.MIPMAP_MODES.POW2 || this.webGLVersion !== 2) && !texture.isPowerOfTwo) { + glTexture.mipmap = false; + } + else { + glTexture.mipmap = texture.mipmap >= 1; + } + if (this.webGLVersion !== 2 && !texture.isPowerOfTwo) { + glTexture.wrapMode = exports.WRAP_MODES.CLAMP; + } + else { + glTexture.wrapMode = texture.wrapMode; + } + if (texture.resource && texture.resource.style(this.renderer, texture, glTexture)) { ; } + else { + this.setStyle(texture, glTexture); + } + glTexture.dirtyStyleId = texture.dirtyStyleId; + }; + /** + * Set style for texture + * @private + * @param texture - Texture to update + * @param glTexture + */ + TextureSystem.prototype.setStyle = function (texture, glTexture) { + var gl = this.gl; + if (glTexture.mipmap && texture.mipmap !== exports.MIPMAP_MODES.ON_MANUAL) { + gl.generateMipmap(texture.target); + } + gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, glTexture.wrapMode); + gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, glTexture.wrapMode); + if (glTexture.mipmap) { + /* eslint-disable max-len */ + gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode === exports.SCALE_MODES.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + var anisotropicExt = this.renderer.context.extensions.anisotropicFiltering; + if (anisotropicExt && texture.anisotropicLevel > 0 && texture.scaleMode === exports.SCALE_MODES.LINEAR) { + var level = Math.min(texture.anisotropicLevel, gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT)); + gl.texParameterf(texture.target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, level); + } + } + else { + gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode === exports.SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST); + } + gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode === exports.SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST); + }; + TextureSystem.prototype.destroy = function () { + this.renderer = null; + }; + return TextureSystem; + }()); + + var _systems = { + __proto__: null, + FilterSystem: FilterSystem, + BatchSystem: BatchSystem, + ContextSystem: ContextSystem, + FramebufferSystem: FramebufferSystem, + GeometrySystem: GeometrySystem, + MaskSystem: MaskSystem, + ScissorSystem: ScissorSystem, + StencilSystem: StencilSystem, + ProjectionSystem: ProjectionSystem, + RenderTextureSystem: RenderTextureSystem, + ShaderSystem: ShaderSystem, + StateSystem: StateSystem, + TextureGCSystem: TextureGCSystem, + TextureSystem: TextureSystem + }; - var currentTime = Date.now(); - var delay = ONE_FRAME_TIME + lastTime - currentTime; + var tempMatrix = new Matrix(); + /** + * The AbstractRenderer is the base for a PixiJS Renderer. It is extended by the {@link PIXI.CanvasRenderer} + * and {@link PIXI.Renderer} which can be used for rendering a PixiJS scene. + * @abstract + * @class + * @extends PIXI.utils.EventEmitter + * @memberof PIXI + */ + var AbstractRenderer = /** @class */ (function (_super) { + __extends$i(AbstractRenderer, _super); + /** + * @param type - The renderer type. + * @param {PIXI.IRendererOptions} [options] - The optional renderer parameters. + * @param {boolean} [options.antialias=false] - + * **WebGL Only.** Whether to enable anti-aliasing. This may affect performance. + * @param {boolean} [options.autoDensity=false] - + * Whether the CSS dimensions of the renderer's view should be resized automatically. + * @param {number} [options.backgroundAlpha=1] - + * Transparency of the background color, value from `0` (fully transparent) to `1` (fully opaque). + * @param {number} [options.backgroundColor=0x000000] - + * The background color used to clear the canvas. It accepts hex numbers (e.g. `0xff0000`). + * @param {boolean} [options.clearBeforeRender=true] - Whether to clear the canvas before new render passes. + * @param {PIXI.IRenderingContext} [options.context] - **WebGL Only.** User-provided WebGL rendering context object. + * @param {number} [options.height=600] - The height of the renderer's view. + * @param {string} [options.powerPreference] - + * **WebGL Only.** A hint indicating what configuration of GPU is suitable for the WebGL context, + * can be `'default'`, `'high-performance'` or `'low-power'`. + * Setting to `'high-performance'` will prioritize rendering performance over power consumption, + * while setting to `'low-power'` will prioritize power saving over rendering performance. + * @param {boolean} [options.premultipliedAlpha=true] - + * **WebGL Only.** Whether the compositor will assume the drawing buffer contains colors with premultiplied alpha. + * @param {boolean} [options.preserveDrawingBuffer=false] - + * **WebGL Only.** Whether to enable drawing buffer preservation. If enabled, the drawing buffer will preserve + * its value until cleared or overwritten. Enable this if you need to call `toDataUrl` on the WebGL context. + * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - + * The resolution / device pixel ratio of the renderer. + * @param {boolean} [options.transparent] - + * **Deprecated since 6.0.0, Use `backgroundAlpha` instead.** \ + * `true` sets `backgroundAlpha` to `0`, `false` sets `backgroundAlpha` to `1`. + * @param {boolean|'notMultiplied'} [options.useContextAlpha=true] - + * Pass-through value for canvas' context attribute `alpha`. This option is for cases where the + * canvas needs to be opaque, possibly for performance reasons on some older devices. + * If you want to set transparency, please use `backgroundAlpha`. \ + * **WebGL Only:** When set to `'notMultiplied'`, the canvas' context attribute `alpha` will be + * set to `true` and `premultipliedAlpha` will be to `false`. + * @param {HTMLCanvasElement} [options.view=null] - + * The canvas to use as the view. If omitted, a new canvas will be created. + * @param {number} [options.width=800] - The width of the renderer's view. + */ + function AbstractRenderer(type, options) { + if (type === void 0) { type = exports.RENDERER_TYPE.UNKNOWN; } + var _this = _super.call(this) || this; + // Add the default render options + options = Object.assign({}, settings.RENDER_OPTIONS, options); + /** + * The supplied constructor options. + * @member {object} + * @readonly + */ + _this.options = options; + /** + * The type of the renderer. + * @member {number} + * @default PIXI.RENDERER_TYPE.UNKNOWN + * @see PIXI.RENDERER_TYPE + */ + _this.type = type; + /** + * Measurements of the screen. (0, 0, screenWidth, screenHeight). + * + * Its safe to use as filterArea or hitArea for the whole stage. + * @member {PIXI.Rectangle} + */ + _this.screen = new Rectangle(0, 0, options.width, options.height); + /** + * The canvas element that everything is drawn to. + * @member {HTMLCanvasElement} + */ + _this.view = options.view || settings.ADAPTER.createCanvas(); + /** + * The resolution / device pixel ratio of the renderer. + * @member {number} + * @default PIXI.settings.RESOLUTION + */ + _this.resolution = options.resolution || settings.RESOLUTION; + /** + * Pass-thru setting for the canvas' context `alpha` property. This is typically + * not something you need to fiddle with. If you want transparency, use `backgroundAlpha`. + * @member {boolean} + */ + _this.useContextAlpha = options.useContextAlpha; + /** + * Whether CSS dimensions of canvas view should be resized to screen dimensions automatically. + * @member {boolean} + */ + _this.autoDensity = !!options.autoDensity; + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of + * the stencil buffer is retained after rendering. + * @member {boolean} + */ + _this.preserveDrawingBuffer = options.preserveDrawingBuffer; + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every + * frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect + * to clear the canvas every frame. Disable this by setting this to false. For example, if + * your game has a canvas filling background image you often don't need this set. + * @member {boolean} + * @default + */ + _this.clearBeforeRender = options.clearBeforeRender; + /** + * The background color as a number. + * @member {number} + * @protected + */ + _this._backgroundColor = 0x000000; + /** + * The background color as an [R, G, B, A] array. + * @member {number[]} + * @protected + */ + _this._backgroundColorRgba = [0, 0, 0, 1]; + /** + * The background color as a string. + * @member {string} + * @protected + */ + _this._backgroundColorString = '#000000'; + _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter + _this.backgroundAlpha = options.backgroundAlpha; + // @deprecated + if (options.transparent !== undefined) { + deprecation('6.0.0', 'Option transparent is deprecated, please use backgroundAlpha instead.'); + _this.useContextAlpha = options.transparent; + _this.backgroundAlpha = options.transparent ? 0 : 1; + } + /** + * The last root object that the renderer tried to render. + * @member {PIXI.DisplayObject} + * @protected + */ + _this._lastObjectRendered = null; + /** + * Collection of plugins. + * @readonly + * @member {object} + */ + _this.plugins = {}; + return _this; + } + /** + * Initialize the plugins. + * @protected + * @param {object} staticMap - The dictionary of statically saved plugins. + */ + AbstractRenderer.prototype.initPlugins = function (staticMap) { + for (var o in staticMap) { + this.plugins[o] = new (staticMap[o])(this); + } + }; + Object.defineProperty(AbstractRenderer.prototype, "width", { + /** + * Same as view.width, actual number of pixels in the canvas by horizontal. + * @member {number} + * @readonly + * @default 800 + */ + get: function () { + return this.view.width; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AbstractRenderer.prototype, "height", { + /** + * Same as view.height, actual number of pixels in the canvas by vertical. + * @member {number} + * @readonly + * @default 600 + */ + get: function () { + return this.view.height; + }, + enumerable: false, + configurable: true + }); + /** + * Resizes the screen and canvas as close as possible to the specified width and height. + * Canvas dimensions are multiplied by resolution and rounded to the nearest integers. + * The new canvas dimensions divided by the resolution become the new screen dimensions. + * @param desiredScreenWidth - The desired width of the screen. + * @param desiredScreenHeight - The desired height of the screen. + */ + AbstractRenderer.prototype.resize = function (desiredScreenWidth, desiredScreenHeight) { + this.view.width = Math.round(desiredScreenWidth * this.resolution); + this.view.height = Math.round(desiredScreenHeight * this.resolution); + var screenWidth = this.view.width / this.resolution; + var screenHeight = this.view.height / this.resolution; + this.screen.width = screenWidth; + this.screen.height = screenHeight; + if (this.autoDensity) { + this.view.style.width = screenWidth + "px"; + this.view.style.height = screenHeight + "px"; + } + /** + * Fired after view has been resized. + * @event PIXI.Renderer#resize + * @param {number} screenWidth - The new width of the screen. + * @param {number} screenHeight - The new height of the screen. + */ + this.emit('resize', screenWidth, screenHeight); + }; + /** + * @ignore + */ + AbstractRenderer.prototype.generateTexture = function (displayObject, options, resolution, region) { + if (options === void 0) { options = {}; } + // @deprecated parameters spread, use options instead + if (typeof options === 'number') { + deprecation('6.1.0', 'generateTexture options (scaleMode, resolution, region) are now object options.'); + options = { scaleMode: options, resolution: resolution, region: region }; + } + var manualRegion = options.region, textureOptions = __rest(options, ["region"]); + region = manualRegion || displayObject.getLocalBounds(null, true); + // minimum texture size is 1x1, 0x0 will throw an error + if (region.width === 0) + { region.width = 1; } + if (region.height === 0) + { region.height = 1; } + var renderTexture = RenderTexture.create(__assign({ width: region.width, height: region.height }, textureOptions)); + tempMatrix.tx = -region.x; + tempMatrix.ty = -region.y; + this.render(displayObject, { + renderTexture: renderTexture, + clear: false, + transform: tempMatrix, + skipUpdateTransform: !!displayObject.parent + }); + return renderTexture; + }; + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * @param [removeView=false] - Removes the Canvas element from the DOM. + */ + AbstractRenderer.prototype.destroy = function (removeView) { + for (var o in this.plugins) { + this.plugins[o].destroy(); + this.plugins[o] = null; + } + if (removeView && this.view.parentNode) { + this.view.parentNode.removeChild(this.view); + } + var thisAny = this; + // null-ing all objects, that's a tradition! + thisAny.plugins = null; + thisAny.type = exports.RENDERER_TYPE.UNKNOWN; + thisAny.view = null; + thisAny.screen = null; + thisAny._tempDisplayObjectParent = null; + thisAny.options = null; + this._backgroundColorRgba = null; + this._backgroundColorString = null; + this._lastObjectRendered = null; + }; + Object.defineProperty(AbstractRenderer.prototype, "backgroundColor", { + /** + * The background color to fill if not transparent + * @member {number} + */ + get: function () { + return this._backgroundColor; + }, + set: function (value) { + this._backgroundColor = value; + this._backgroundColorString = hex2string(value); + hex2rgb(value, this._backgroundColorRgba); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AbstractRenderer.prototype, "backgroundAlpha", { + /** + * The background color alpha. Setting this to 0 will make the canvas transparent. + * @member {number} + */ + get: function () { + return this._backgroundColorRgba[3]; + }, + set: function (value) { + this._backgroundColorRgba[3] = value; + }, + enumerable: false, + configurable: true + }); + return AbstractRenderer; + }(eventemitter3)); + + var GLBuffer = /** @class */ (function () { + function GLBuffer(buffer) { + this.buffer = buffer || null; + this.updateID = -1; + this.byteLength = -1; + this.refCount = 0; + } + return GLBuffer; + }()); - if (delay < 0) { - delay = 0; - } + /** + * System plugin to the renderer to manage buffers. + * + * WebGL uses Buffers as a way to store objects to the GPU. + * This system makes working with them a lot easier. + * + * Buffers are used in three main places in WebGL + * - geometry information + * - Uniform information (via uniform buffer objects - a WebGL 2 only feature) + * - Transform feedback information. (WebGL 2 only feature) + * + * This system will handle the binding of buffers to the GPU as well as uploading + * them. With this system, you never need to work directly with GPU buffers, but instead work with + * the PIXI.Buffer class. + * @class + * @memberof PIXI + */ + var BufferSystem = /** @class */ (function () { + /** + * @param {PIXI.Renderer} renderer - The renderer this System works for. + */ + function BufferSystem(renderer) { + this.renderer = renderer; + this.managedBuffers = {}; + this.boundBufferBases = {}; + } + /** + * @ignore + */ + BufferSystem.prototype.destroy = function () { + this.renderer = null; + }; + /** Sets up the renderer context and necessary buffers. */ + BufferSystem.prototype.contextChange = function () { + this.disposeAll(true); + this.gl = this.renderer.gl; + // TODO fill out... + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + }; + /** + * This binds specified buffer. On first run, it will create the webGL buffers for the context too + * @param buffer - the buffer to bind to the renderer + */ + BufferSystem.prototype.bind = function (buffer) { + var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; + var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer); + gl.bindBuffer(buffer.type, glBuffer.buffer); + }; + /** + * Binds an uniform buffer to at the given index. + * + * A cache is used so a buffer will not be bound again if already bound. + * @param buffer - the buffer to bind + * @param index - the base index to bind it to. + */ + BufferSystem.prototype.bindBufferBase = function (buffer, index) { + var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; + if (this.boundBufferBases[index] !== buffer) { + var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer); + this.boundBufferBases[index] = buffer; + gl.bindBufferBase(gl.UNIFORM_BUFFER, index, glBuffer.buffer); + } + }; + /** + * Binds a buffer whilst also binding its range. + * This will make the buffer start from the offset supplied rather than 0 when it is read. + * @param buffer - the buffer to bind + * @param index - the base index to bind at, defaults to 0 + * @param offset - the offset to bind at (this is blocks of 256). 0 = 0, 1 = 256, 2 = 512 etc + */ + BufferSystem.prototype.bindBufferRange = function (buffer, index, offset) { + var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; + offset = offset || 0; + var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer); + gl.bindBufferRange(gl.UNIFORM_BUFFER, index || 0, glBuffer.buffer, offset * 256, 256); + }; + /** + * Will ensure the data in the buffer is uploaded to the GPU. + * @param {PIXI.Buffer} buffer - the buffer to update + */ + BufferSystem.prototype.update = function (buffer) { + var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; + var glBuffer = buffer._glBuffers[CONTEXT_UID]; + if (buffer._updateID === glBuffer.updateID) { + return; + } + glBuffer.updateID = buffer._updateID; + gl.bindBuffer(buffer.type, glBuffer.buffer); + if (glBuffer.byteLength >= buffer.data.byteLength) { + // offset is always zero for now! + gl.bufferSubData(buffer.type, 0, buffer.data); + } + else { + var drawType = buffer.static ? gl.STATIC_DRAW : gl.DYNAMIC_DRAW; + glBuffer.byteLength = buffer.data.byteLength; + gl.bufferData(buffer.type, buffer.data, drawType); + } + }; + /** + * Disposes buffer + * @param {PIXI.Buffer} buffer - buffer with data + * @param {boolean} [contextLost=false] - If context was lost, we suppress deleteVertexArray + */ + BufferSystem.prototype.dispose = function (buffer, contextLost) { + if (!this.managedBuffers[buffer.id]) { + return; + } + delete this.managedBuffers[buffer.id]; + var glBuffer = buffer._glBuffers[this.CONTEXT_UID]; + var gl = this.gl; + buffer.disposeRunner.remove(this); + if (!glBuffer) { + return; + } + if (!contextLost) { + gl.deleteBuffer(glBuffer.buffer); + } + delete buffer._glBuffers[this.CONTEXT_UID]; + }; + /** + * dispose all WebGL resources of all managed buffers + * @param {boolean} [contextLost=false] - If context was lost, we suppress `gl.delete` calls + */ + BufferSystem.prototype.disposeAll = function (contextLost) { + var all = Object.keys(this.managedBuffers); + for (var i = 0; i < all.length; i++) { + this.dispose(this.managedBuffers[all[i]], contextLost); + } + }; + /** + * creates and attaches a GLBuffer object tied to the current context. + * @param buffer + * @protected + */ + BufferSystem.prototype.createGLBuffer = function (buffer) { + var _a = this, CONTEXT_UID = _a.CONTEXT_UID, gl = _a.gl; + buffer._glBuffers[CONTEXT_UID] = new GLBuffer(gl.createBuffer()); + this.managedBuffers[buffer.id] = buffer; + buffer.disposeRunner.add(this); + return buffer._glBuffers[CONTEXT_UID]; + }; + return BufferSystem; + }()); - lastTime = currentTime; + /** + * The Renderer draws the scene and all its content onto a WebGL enabled canvas. + * + * This renderer should be used for browsers that support WebGL. + * + * This renderer works by automatically managing WebGLBatchesm, so no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything! + * + * Renderer is composed of systems that manage specific tasks. The following systems are added by default + * whenever you create a renderer: + * + * | System | Description | + * | ------------------------------------ | ----------------------------------------------------------------------------- | + * | {@link PIXI.BatchSystem} | This manages object renderers that defer rendering until a flush. | + * | {@link PIXI.ContextSystem} | This manages the WebGL context and extensions. | + * | {@link PIXI.EventSystem} | This manages UI events. | + * | {@link PIXI.FilterSystem} | This manages the filtering pipeline for post-processing effects. | + * | {@link PIXI.FramebufferSystem} | This manages framebuffers, which are used for offscreen rendering. | + * | {@link PIXI.GeometrySystem} | This manages geometries & buffers, which are used to draw object meshes. | + * | {@link PIXI.MaskSystem} | This manages masking operations. | + * | {@link PIXI.ProjectionSystem} | This manages the `projectionMatrix`, used by shaders to get NDC coordinates. | + * | {@link PIXI.RenderTextureSystem} | This manages render-textures, which are an abstraction over framebuffers. | + * | {@link PIXI.ScissorSystem} | This handles scissor masking, and is used internally by {@link MaskSystem} | + * | {@link PIXI.ShaderSystem} | This manages shaders, programs that run on the GPU to calculate 'em pixels. | + * | {@link PIXI.StateSystem} | This manages the WebGL state variables like blend mode, depth testing, etc. | + * | {@link PIXI.StencilSystem} | This handles stencil masking, and is used internally by {@link MaskSystem} | + * | {@link PIXI.TextureSystem} | This manages textures and their resources on the GPU. | + * | {@link PIXI.TextureGCSystem} | This will automatically remove textures from the GPU if they are not used. | + * + * The breadth of the API surface provided by the renderer is contained within these systems. + * @memberof PIXI + */ + var Renderer = /** @class */ (function (_super) { + __extends$i(Renderer, _super); + /** + * @param {PIXI.IRendererOptions} [options] - The optional renderer parameters. + * @param {boolean} [options.antialias=false] - + * **WebGL Only.** Whether to enable anti-aliasing. This may affect performance. + * @param {boolean} [options.autoDensity=false] - + * Whether the CSS dimensions of the renderer's view should be resized automatically. + * @param {number} [options.backgroundAlpha=1] - + * Transparency of the background color, value from `0` (fully transparent) to `1` (fully opaque). + * @param {number} [options.backgroundColor=0x000000] - + * The background color used to clear the canvas. It accepts hex numbers (e.g. `0xff0000`). + * @param {boolean} [options.clearBeforeRender=true] - Whether to clear the canvas before new render passes. + * @param {PIXI.IRenderingContext} [options.context] - **WebGL Only.** User-provided WebGL rendering context object. + * @param {number} [options.height=600] - The height of the renderer's view. + * @param {string} [options.powerPreference] - + * **WebGL Only.** A hint indicating what configuration of GPU is suitable for the WebGL context, + * can be `'default'`, `'high-performance'` or `'low-power'`. + * Setting to `'high-performance'` will prioritize rendering performance over power consumption, + * while setting to `'low-power'` will prioritize power saving over rendering performance. + * @param {boolean} [options.premultipliedAlpha=true] - + * **WebGL Only.** Whether the compositor will assume the drawing buffer contains colors with premultiplied alpha. + * @param {boolean} [options.preserveDrawingBuffer=false] - + * **WebGL Only.** Whether to enable drawing buffer preservation. If enabled, the drawing buffer will preserve + * its value until cleared or overwritten. Enable this if you need to call `toDataUrl` on the WebGL context. + * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - + * The resolution / device pixel ratio of the renderer. + * @param {boolean} [options.transparent] - + * **Deprecated since 6.0.0, Use `backgroundAlpha` instead.** \ + * `true` sets `backgroundAlpha` to `0`, `false` sets `backgroundAlpha` to `1`. + * @param {boolean|'notMultiplied'} [options.useContextAlpha=true] - + * Pass-through value for canvas' context attribute `alpha`. This option is for cases where the + * canvas needs to be opaque, possibly for performance reasons on some older devices. + * If you want to set transparency, please use `backgroundAlpha`. \ + * **WebGL Only:** When set to `'notMultiplied'`, the canvas' context attribute `alpha` will be + * set to `true` and `premultipliedAlpha` will be to `false`. + * @param {HTMLCanvasElement} [options.view=null] - + * The canvas to use as the view. If omitted, a new canvas will be created. + * @param {number} [options.width=800] - The width of the renderer's view. + */ + function Renderer(options) { + var _this = _super.call(this, exports.RENDERER_TYPE.WEBGL, options) || this; + // the options will have been modified here in the super constructor with pixi's default settings.. + options = _this.options; + _this.gl = null; + _this.CONTEXT_UID = 0; + _this.runners = { + destroy: new Runner('destroy'), + contextChange: new Runner('contextChange'), + reset: new Runner('reset'), + update: new Runner('update'), + postrender: new Runner('postrender'), + prerender: new Runner('prerender'), + resize: new Runner('resize'), + }; + _this.runners.contextChange.add(_this); + _this.globalUniforms = new UniformGroup({ + projectionMatrix: new Matrix(), + }, true); + _this.addSystem(MaskSystem, 'mask') + .addSystem(ContextSystem, 'context') + .addSystem(StateSystem, 'state') + .addSystem(ShaderSystem, 'shader') + .addSystem(TextureSystem, 'texture') + .addSystem(BufferSystem, 'buffer') + .addSystem(GeometrySystem, 'geometry') + .addSystem(FramebufferSystem, 'framebuffer') + .addSystem(ScissorSystem, 'scissor') + .addSystem(StencilSystem, 'stencil') + .addSystem(ProjectionSystem, 'projection') + .addSystem(TextureGCSystem, 'textureGC') + .addSystem(FilterSystem, 'filter') + .addSystem(RenderTextureSystem, 'renderTexture') + .addSystem(BatchSystem, 'batch'); + _this.initPlugins(Renderer.__plugins); + _this.multisample = undefined; + /* + * The options passed in to create a new WebGL context. + */ + if (options.context) { + _this.context.initFromContext(options.context); + } + else { + _this.context.initFromOptions({ + alpha: !!_this.useContextAlpha, + antialias: options.antialias, + premultipliedAlpha: _this.useContextAlpha && _this.useContextAlpha !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: options.preserveDrawingBuffer, + powerPreference: _this.options.powerPreference, + }); + } + _this.renderingToScreen = true; + sayHello(_this.context.webGLVersion === 2 ? 'WebGL 2' : 'WebGL 1'); + _this.resize(_this.options.width, _this.options.height); + return _this; + } + /** + * Create renderer if WebGL is available. Overrideable + * by the **@pixi/canvas-renderer** package to allow fallback. + * throws error if WebGL is not available. + * @param options + * @private + */ + Renderer.create = function (options) { + if (isWebGLSupported()) { + return new Renderer(options); + } + throw new Error('WebGL unsupported in this browser, use "pixi.js-legacy" for fallback canvas2d support.'); + }; + Renderer.prototype.contextChange = function () { + var gl = this.gl; + var samples; + if (this.context.webGLVersion === 1) { + var framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + samples = gl.getParameter(gl.SAMPLES); + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + } + else { + var framebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null); + samples = gl.getParameter(gl.SAMPLES); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, framebuffer); + } + if (samples >= exports.MSAA_QUALITY.HIGH) { + this.multisample = exports.MSAA_QUALITY.HIGH; + } + else if (samples >= exports.MSAA_QUALITY.MEDIUM) { + this.multisample = exports.MSAA_QUALITY.MEDIUM; + } + else if (samples >= exports.MSAA_QUALITY.LOW) { + this.multisample = exports.MSAA_QUALITY.LOW; + } + else { + this.multisample = exports.MSAA_QUALITY.NONE; + } + }; + /** + * Add a new system to the renderer. + * @param ClassRef - Class reference + * @param name - Property name for system, if not specified + * will use a static `name` property on the class itself. This + * name will be assigned as s property on the Renderer so make + * sure it doesn't collide with properties on Renderer. + * @returns Return instance of renderer + */ + Renderer.prototype.addSystem = function (ClassRef, name) { + var system = new ClassRef(this); + if (this[name]) { + throw new Error("Whoops! The name \"" + name + "\" is already in use"); + } + this[name] = system; + for (var i in this.runners) { + this.runners[i].add(system); + } + /** + * Fired after rendering finishes. + * @event PIXI.Renderer#postrender + */ + /** + * Fired before rendering starts. + * @event PIXI.Renderer#prerender + */ + /** + * Fired when the WebGL context is set. + * @event PIXI.Renderer#context + * @param {WebGLRenderingContext} gl - WebGL context. + */ + return this; + }; + /** + * @ignore + */ + Renderer.prototype.render = function (displayObject, options) { + var renderTexture; + var clear; + var transform; + var skipUpdateTransform; + if (options) { + if (options instanceof RenderTexture) { + deprecation('6.0.0', 'Renderer#render arguments changed, use options instead.'); + /* eslint-disable prefer-rest-params */ + renderTexture = options; + clear = arguments[2]; + transform = arguments[3]; + skipUpdateTransform = arguments[4]; + /* eslint-enable prefer-rest-params */ + } + else { + renderTexture = options.renderTexture; + clear = options.clear; + transform = options.transform; + skipUpdateTransform = options.skipUpdateTransform; + } + } + // can be handy to know! + this.renderingToScreen = !renderTexture; + this.runners.prerender.emit(); + this.emit('prerender'); + // apply a transform at a GPU level + this.projection.transform = transform; + // no point rendering if our context has been blown up! + if (this.context.isLost) { + return; + } + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.enableTempParent(); + displayObject.updateTransform(); + displayObject.disableTempParent(cacheParent); + // displayObject.hitArea = //TODO add a temp hit area + } + this.renderTexture.bind(renderTexture); + this.batch.currentRenderer.start(); + if (clear !== undefined ? clear : this.clearBeforeRender) { + this.renderTexture.clear(); + } + displayObject.render(this); + // apply transform.. + this.batch.currentRenderer.flush(); + if (renderTexture) { + renderTexture.baseTexture.update(); + } + this.runners.postrender.emit(); + // reset transform after render + this.projection.transform = null; + this.emit('postrender'); + }; + /** + * @override + * @ignore + */ + Renderer.prototype.generateTexture = function (displayObject, options, resolution, region) { + if (options === void 0) { options = {}; } + var renderTexture = _super.prototype.generateTexture.call(this, displayObject, options, resolution, region); + this.framebuffer.blit(); + return renderTexture; + }; + /** + * Resizes the WebGL view to the specified width and height. + * @param desiredScreenWidth - The desired width of the screen. + * @param desiredScreenHeight - The desired height of the screen. + */ + Renderer.prototype.resize = function (desiredScreenWidth, desiredScreenHeight) { + _super.prototype.resize.call(this, desiredScreenWidth, desiredScreenHeight); + this.runners.resize.emit(this.screen.height, this.screen.width); + }; + /** + * Resets the WebGL state so you can render things however you fancy! + * @returns Returns itself. + */ + Renderer.prototype.reset = function () { + this.runners.reset.emit(); + return this; + }; + /** Clear the frame buffer. */ + Renderer.prototype.clear = function () { + this.renderTexture.bind(); + this.renderTexture.clear(); + }; + /** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * @param [removeView=false] - Removes the Canvas element from the DOM. + * See: https://github.com/pixijs/pixi.js/issues/2233 + */ + Renderer.prototype.destroy = function (removeView) { + this.runners.destroy.emit(); + for (var r in this.runners) { + this.runners[r].destroy(); + } + // call base destroy + _super.prototype.destroy.call(this, removeView); + // TODO nullify all the managers.. + this.gl = null; + }; + Object.defineProperty(Renderer.prototype, "extract", { + /** + * Please use `plugins.extract` instead. + * @member {PIXI.Extract} extract + * @deprecated since 6.0.0 + * @readonly + */ + get: function () { + deprecation('6.0.0', 'Renderer#extract has been deprecated, please use Renderer#plugins.extract instead.'); + return this.plugins.extract; + }, + enumerable: false, + configurable: true + }); + /** + * Use the {@link PIXI.extensions.add} API to register plugins. + * @deprecated since 6.5.0 + * @param pluginName - The name of the plugin. + * @param ctor - The constructor function or class for the plugin. + */ + Renderer.registerPlugin = function (pluginName, ctor) { + deprecation('6.5.0', 'Renderer.registerPlugin() has been deprecated, please use extensions.add() instead.'); + extensions.add({ + name: pluginName, + type: exports.ExtensionType.RendererPlugin, + ref: ctor, + }); + }; + /** + * Collection of installed plugins. These are included by default in PIXI, but can be excluded + * by creating a custom build. Consult the README for more information about creating custom + * builds and excluding plugins. + * @readonly + * @property {PIXI.AccessibilityManager} accessibility Support tabbing interactive elements. + * @property {PIXI.Extract} extract Extract image data from renderer. + * @property {PIXI.InteractionManager} interaction Handles mouse, touch and pointer events. + * @property {PIXI.ParticleRenderer} particle Renderer for ParticleContainer objects. + * @property {PIXI.Prepare} prepare Pre-render display objects. + * @property {PIXI.BatchRenderer} batch Batching of Sprite, Graphics and Mesh objects. + * @property {PIXI.TilingSpriteRenderer} tilingSprite Renderer for TilingSprite objects. + */ + Renderer.__plugins = {}; + return Renderer; + }(AbstractRenderer)); + // Handle registration of extensions + extensions.handleByMap(exports.ExtensionType.RendererPlugin, Renderer.__plugins); - return setTimeout(function () { - lastTime = Date.now(); - callback(performance.now()); - }, delay); - }; -} + /** + * This helper function will automatically detect which renderer you should be using. + * WebGL is the preferred renderer as it is a lot faster. If WebGL is not supported by + * the browser then this function will return a canvas renderer. + * @memberof PIXI + * @function autoDetectRenderer + * @param {PIXI.IRendererOptionsAuto} [options] - The optional renderer parameters. + * @param {boolean} [options.antialias=false] - + * **WebGL Only.** Whether to enable anti-aliasing. This may affect performance. + * @param {boolean} [options.autoDensity=false] - + * Whether the CSS dimensions of the renderer's view should be resized automatically. + * @param {number} [options.backgroundAlpha=1] - + * Transparency of the background color, value from `0` (fully transparent) to `1` (fully opaque). + * @param {number} [options.backgroundColor=0x000000] - + * The background color used to clear the canvas. It accepts hex numbers (e.g. `0xff0000`). + * @param {boolean} [options.clearBeforeRender=true] - Whether to clear the canvas before new render passes. + * @param {PIXI.IRenderingContext} [options.context] - **WebGL Only.** User-provided WebGL rendering context object. + * @param {boolean} [options.forceCanvas=false] - + * Force using {@link PIXI.CanvasRenderer}, even if WebGL is available. This option only is available when + * using **pixi.js-legacy** or **@pixi/canvas-renderer** packages, otherwise it is ignored. + * @param {number} [options.height=600] - The height of the renderer's view. + * @param {string} [options.powerPreference] - + * **WebGL Only.** A hint indicating what configuration of GPU is suitable for the WebGL context, + * can be `'default'`, `'high-performance'` or `'low-power'`. + * Setting to `'high-performance'` will prioritize rendering performance over power consumption, + * while setting to `'low-power'` will prioritize power saving over rendering performance. + * @param {boolean} [options.premultipliedAlpha=true] - + * **WebGL Only.** Whether the compositor will assume the drawing buffer contains colors with premultiplied alpha. + * @param {boolean} [options.preserveDrawingBuffer=false] - + * **WebGL Only.** Whether to enable drawing buffer preservation. If enabled, the drawing buffer will preserve + * its value until cleared or overwritten. Enable this if you need to call `toDataUrl` on the WebGL context. + * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - + * The resolution / device pixel ratio of the renderer. + * @param {boolean} [options.transparent] - + * **Deprecated since 6.0.0, Use `backgroundAlpha` instead.** \ + * `true` sets `backgroundAlpha` to `0`, `false` sets `backgroundAlpha` to `1`. + * @param {boolean|'notMultiplied'} [options.useContextAlpha=true] - + * Pass-through value for canvas' context attribute `alpha`. This option is for cases where the + * canvas needs to be opaque, possibly for performance reasons on some older devices. + * If you want to set transparency, please use `backgroundAlpha`. \ + * **WebGL Only:** When set to `'notMultiplied'`, the canvas' context attribute `alpha` will be + * set to `true` and `premultipliedAlpha` will be to `false`. + * @param {HTMLCanvasElement} [options.view=null] - + * The canvas to use as the view. If omitted, a new canvas will be created. + * @param {number} [options.width=800] - The width of the renderer's view. + * @returns {PIXI.Renderer|PIXI.CanvasRenderer} + * Returns {@link PIXI.Renderer} if WebGL is available, otherwise {@link PIXI.CanvasRenderer}. + */ + function autoDetectRenderer(options) { + return Renderer.create(options); + } -if (!global.cancelAnimationFrame) { - global.cancelAnimationFrame = function (id) { - return clearTimeout(id); - }; -} + var $defaultVertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}"; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + var $defaultFilterVertex = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"; -},{}],182:[function(require,module,exports){ -'use strict'; + /** + * Default vertex shader + * @memberof PIXI + * @member {string} defaultVertex + */ + /** + * Default filter vertex shader + * @memberof PIXI + * @member {string} defaultFilterVertex + */ + // NOTE: This black magic is so that @microsoft/api-extractor does not complain! This explicitly specifies the types + // of defaultVertex, defaultFilterVertex. + var defaultVertex$1 = $defaultVertex; + var defaultFilterVertex = $defaultFilterVertex; -exports.__esModule = true; + /** + * Use the ISystem interface instead. + * @deprecated since 6.1.0 + * @memberof PIXI + */ + var System = /** @class */ (function () { + /** + * @param renderer - Reference to Renderer + */ + function System(renderer) { + deprecation('6.1.0', 'System class is deprecated, implemement ISystem interface instead.'); + this.renderer = renderer; + } + /** Destroy and don't use after this. */ + System.prototype.destroy = function () { + this.renderer = null; + }; + return System; + }()); -var _core = require('../core'); + /** + * Used by the batcher to draw batches. + * Each one of these contains all information required to draw a bound geometry. + * @memberof PIXI + */ + var BatchDrawCall = /** @class */ (function () { + function BatchDrawCall() { + this.texArray = null; + this.blend = 0; + this.type = exports.DRAW_MODES.TRIANGLES; + this.start = 0; + this.size = 0; + this.data = null; + } + return BatchDrawCall; + }()); -var core = _interopRequireWildcard(_core); + /** + * Used by the batcher to build texture batches. + * Holds list of textures and their respective locations. + * @memberof PIXI + */ + var BatchTextureArray = /** @class */ (function () { + function BatchTextureArray() { + this.elements = []; + this.ids = []; + this.count = 0; + } + BatchTextureArray.prototype.clear = function () { + for (var i = 0; i < this.count; i++) { + this.elements[i] = null; + } + this.count = 0; + }; + return BatchTextureArray; + }()); -var _CountLimiter = require('./limiters/CountLimiter'); + /** + * Flexible wrapper around `ArrayBuffer` that also provides typed array views on demand. + * @memberof PIXI + */ + var ViewableBuffer = /** @class */ (function () { + function ViewableBuffer(sizeOrBuffer) { + if (typeof sizeOrBuffer === 'number') { + this.rawBinaryData = new ArrayBuffer(sizeOrBuffer); + } + else if (sizeOrBuffer instanceof Uint8Array) { + this.rawBinaryData = sizeOrBuffer.buffer; + } + else { + this.rawBinaryData = sizeOrBuffer; + } + this.uint32View = new Uint32Array(this.rawBinaryData); + this.float32View = new Float32Array(this.rawBinaryData); + } + Object.defineProperty(ViewableBuffer.prototype, "int8View", { + /** View on the raw binary data as a `Int8Array`. */ + get: function () { + if (!this._int8View) { + this._int8View = new Int8Array(this.rawBinaryData); + } + return this._int8View; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ViewableBuffer.prototype, "uint8View", { + /** View on the raw binary data as a `Uint8Array`. */ + get: function () { + if (!this._uint8View) { + this._uint8View = new Uint8Array(this.rawBinaryData); + } + return this._uint8View; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ViewableBuffer.prototype, "int16View", { + /** View on the raw binary data as a `Int16Array`. */ + get: function () { + if (!this._int16View) { + this._int16View = new Int16Array(this.rawBinaryData); + } + return this._int16View; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ViewableBuffer.prototype, "uint16View", { + /** View on the raw binary data as a `Uint16Array`. */ + get: function () { + if (!this._uint16View) { + this._uint16View = new Uint16Array(this.rawBinaryData); + } + return this._uint16View; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ViewableBuffer.prototype, "int32View", { + /** View on the raw binary data as a `Int32Array`. */ + get: function () { + if (!this._int32View) { + this._int32View = new Int32Array(this.rawBinaryData); + } + return this._int32View; + }, + enumerable: false, + configurable: true + }); + /** + * Returns the view of the given type. + * @param type - One of `int8`, `uint8`, `int16`, + * `uint16`, `int32`, `uint32`, and `float32`. + * @returns - typed array of given type + */ + ViewableBuffer.prototype.view = function (type) { + return this[type + "View"]; + }; + /** Destroys all buffer references. Do not use after calling this. */ + ViewableBuffer.prototype.destroy = function () { + this.rawBinaryData = null; + this._int8View = null; + this._uint8View = null; + this._int16View = null; + this._uint16View = null; + this._int32View = null; + this.uint32View = null; + this.float32View = null; + }; + ViewableBuffer.sizeOf = function (type) { + switch (type) { + case 'int8': + case 'uint8': + return 1; + case 'int16': + case 'uint16': + return 2; + case 'int32': + case 'uint32': + case 'float32': + return 4; + default: + throw new Error(type + " isn't a valid view type"); + } + }; + return ViewableBuffer; + }()); -var _CountLimiter2 = _interopRequireDefault(_CountLimiter); + /** + * Renderer dedicated to drawing and batching sprites. + * + * This is the default batch renderer. It buffers objects + * with texture-based geometries and renders them in + * batches. It uploads multiple textures to the GPU to + * reduce to the number of draw calls. + * @memberof PIXI + */ + var AbstractBatchRenderer = /** @class */ (function (_super) { + __extends$i(AbstractBatchRenderer, _super); + /** + * This will hook onto the renderer's `contextChange` + * and `prerender` signals. + * @param {PIXI.Renderer} renderer - The renderer this works for. + */ + function AbstractBatchRenderer(renderer) { + var _this = _super.call(this, renderer) || this; + _this.shaderGenerator = null; + _this.geometryClass = null; + _this.vertexSize = null; + _this.state = State.for2d(); + _this.size = settings.SPRITE_BATCH_SIZE * 4; + _this._vertexCount = 0; + _this._indexCount = 0; + _this._bufferedElements = []; + _this._bufferedTextures = []; + _this._bufferSize = 0; + _this._shader = null; + _this._packedGeometries = []; + _this._packedGeometryPoolSize = 2; + _this._flushId = 0; + _this._aBuffers = {}; + _this._iBuffers = {}; + _this.MAX_TEXTURES = 1; + _this.renderer.on('prerender', _this.onPrerender, _this); + renderer.runners.contextChange.add(_this); + _this._dcIndex = 0; + _this._aIndex = 0; + _this._iIndex = 0; + _this._attributeBuffer = null; + _this._indexBuffer = null; + _this._tempBoundTextures = []; + return _this; + } + /** + * Handles the `contextChange` signal. + * + * It calculates `this.MAX_TEXTURES` and allocating the packed-geometry object pool. + */ + AbstractBatchRenderer.prototype.contextChange = function () { + var gl = this.renderer.gl; + if (settings.PREFER_ENV === exports.ENV.WEBGL_LEGACY) { + this.MAX_TEXTURES = 1; + } + else { + // step 1: first check max textures the GPU can handle. + this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), settings.SPRITE_MAX_TEXTURES); + // step 2: check the maximum number of if statements the shader can have too.. + this.MAX_TEXTURES = checkMaxIfStatementsInShader(this.MAX_TEXTURES, gl); + } + this._shader = this.shaderGenerator.generateShader(this.MAX_TEXTURES); + // we use the second shader as the first one depending on your browser + // may omit aTextureId as it is not used by the shader so is optimized out. + for (var i = 0; i < this._packedGeometryPoolSize; i++) { + /* eslint-disable max-len */ + this._packedGeometries[i] = new (this.geometryClass)(); + } + this.initFlushBuffers(); + }; + /** Makes sure that static and dynamic flush pooled objects have correct dimensions. */ + AbstractBatchRenderer.prototype.initFlushBuffers = function () { + var _drawCallPool = AbstractBatchRenderer._drawCallPool, _textureArrayPool = AbstractBatchRenderer._textureArrayPool; + // max draw calls + var MAX_SPRITES = this.size / 4; + // max texture arrays + var MAX_TA = Math.floor(MAX_SPRITES / this.MAX_TEXTURES) + 1; + while (_drawCallPool.length < MAX_SPRITES) { + _drawCallPool.push(new BatchDrawCall()); + } + while (_textureArrayPool.length < MAX_TA) { + _textureArrayPool.push(new BatchTextureArray()); + } + for (var i = 0; i < this.MAX_TEXTURES; i++) { + this._tempBoundTextures[i] = null; + } + }; + /** Handles the `prerender` signal. It ensures that flushes start from the first geometry object again. */ + AbstractBatchRenderer.prototype.onPrerender = function () { + this._flushId = 0; + }; + /** + * Buffers the "batchable" object. It need not be rendered immediately. + * @param {PIXI.DisplayObject} element - the element to render when + * using this renderer + */ + AbstractBatchRenderer.prototype.render = function (element) { + if (!element._texture.valid) { + return; + } + if (this._vertexCount + (element.vertexData.length / 2) > this.size) { + this.flush(); + } + this._vertexCount += element.vertexData.length / 2; + this._indexCount += element.indices.length; + this._bufferedTextures[this._bufferSize] = element._texture.baseTexture; + this._bufferedElements[this._bufferSize++] = element; + }; + AbstractBatchRenderer.prototype.buildTexturesAndDrawCalls = function () { + var _a = this, textures = _a._bufferedTextures, MAX_TEXTURES = _a.MAX_TEXTURES; + var textureArrays = AbstractBatchRenderer._textureArrayPool; + var batch = this.renderer.batch; + var boundTextures = this._tempBoundTextures; + var touch = this.renderer.textureGC.count; + var TICK = ++BaseTexture._globalBatch; + var countTexArrays = 0; + var texArray = textureArrays[0]; + var start = 0; + batch.copyBoundTextures(boundTextures, MAX_TEXTURES); + for (var i = 0; i < this._bufferSize; ++i) { + var tex = textures[i]; + textures[i] = null; + if (tex._batchEnabled === TICK) { + continue; + } + if (texArray.count >= MAX_TEXTURES) { + batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES); + this.buildDrawCalls(texArray, start, i); + start = i; + texArray = textureArrays[++countTexArrays]; + ++TICK; + } + tex._batchEnabled = TICK; + tex.touched = touch; + texArray.elements[texArray.count++] = tex; + } + if (texArray.count > 0) { + batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES); + this.buildDrawCalls(texArray, start, this._bufferSize); + ++countTexArrays; + ++TICK; + } + // Clean-up + for (var i = 0; i < boundTextures.length; i++) { + boundTextures[i] = null; + } + BaseTexture._globalBatch = TICK; + }; + /** + * Populating drawcalls for rendering + * @param texArray + * @param start + * @param finish + */ + AbstractBatchRenderer.prototype.buildDrawCalls = function (texArray, start, finish) { + var _a = this, elements = _a._bufferedElements, _attributeBuffer = _a._attributeBuffer, _indexBuffer = _a._indexBuffer, vertexSize = _a.vertexSize; + var drawCalls = AbstractBatchRenderer._drawCallPool; + var dcIndex = this._dcIndex; + var aIndex = this._aIndex; + var iIndex = this._iIndex; + var drawCall = drawCalls[dcIndex]; + drawCall.start = this._iIndex; + drawCall.texArray = texArray; + for (var i = start; i < finish; ++i) { + var sprite = elements[i]; + var tex = sprite._texture.baseTexture; + var spriteBlendMode = premultiplyBlendMode[tex.alphaMode ? 1 : 0][sprite.blendMode]; + elements[i] = null; + if (start < i && drawCall.blend !== spriteBlendMode) { + drawCall.size = iIndex - drawCall.start; + start = i; + drawCall = drawCalls[++dcIndex]; + drawCall.texArray = texArray; + drawCall.start = iIndex; + } + this.packInterleavedGeometry(sprite, _attributeBuffer, _indexBuffer, aIndex, iIndex); + aIndex += sprite.vertexData.length / 2 * vertexSize; + iIndex += sprite.indices.length; + drawCall.blend = spriteBlendMode; + } + if (start < finish) { + drawCall.size = iIndex - drawCall.start; + ++dcIndex; + } + this._dcIndex = dcIndex; + this._aIndex = aIndex; + this._iIndex = iIndex; + }; + /** + * Bind textures for current rendering + * @param texArray + */ + AbstractBatchRenderer.prototype.bindAndClearTexArray = function (texArray) { + var textureSystem = this.renderer.texture; + for (var j = 0; j < texArray.count; j++) { + textureSystem.bind(texArray.elements[j], texArray.ids[j]); + texArray.elements[j] = null; + } + texArray.count = 0; + }; + AbstractBatchRenderer.prototype.updateGeometry = function () { + var _a = this, packedGeometries = _a._packedGeometries, attributeBuffer = _a._attributeBuffer, indexBuffer = _a._indexBuffer; + if (!settings.CAN_UPLOAD_SAME_BUFFER) { /* Usually on iOS devices, where the browser doesn't + like uploads to the same buffer in a single frame. */ + if (this._packedGeometryPoolSize <= this._flushId) { + this._packedGeometryPoolSize++; + packedGeometries[this._flushId] = new (this.geometryClass)(); + } + packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData); + packedGeometries[this._flushId]._indexBuffer.update(indexBuffer); + this.renderer.geometry.bind(packedGeometries[this._flushId]); + this.renderer.geometry.updateBuffers(); + this._flushId++; + } + else { + // lets use the faster option, always use buffer number 0 + packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData); + packedGeometries[this._flushId]._indexBuffer.update(indexBuffer); + this.renderer.geometry.updateBuffers(); + } + }; + AbstractBatchRenderer.prototype.drawBatches = function () { + var dcCount = this._dcIndex; + var _a = this.renderer, gl = _a.gl, stateSystem = _a.state; + var drawCalls = AbstractBatchRenderer._drawCallPool; + var curTexArray = null; + // Upload textures and do the draw calls + for (var i = 0; i < dcCount; i++) { + var _b = drawCalls[i], texArray = _b.texArray, type = _b.type, size = _b.size, start = _b.start, blend = _b.blend; + if (curTexArray !== texArray) { + curTexArray = texArray; + this.bindAndClearTexArray(texArray); + } + this.state.blendMode = blend; + stateSystem.set(this.state); + gl.drawElements(type, size, gl.UNSIGNED_SHORT, start * 2); + } + }; + /** Renders the content _now_ and empties the current batch. */ + AbstractBatchRenderer.prototype.flush = function () { + if (this._vertexCount === 0) { + return; + } + this._attributeBuffer = this.getAttributeBuffer(this._vertexCount); + this._indexBuffer = this.getIndexBuffer(this._indexCount); + this._aIndex = 0; + this._iIndex = 0; + this._dcIndex = 0; + this.buildTexturesAndDrawCalls(); + this.updateGeometry(); + this.drawBatches(); + // reset elements buffer for the next flush + this._bufferSize = 0; + this._vertexCount = 0; + this._indexCount = 0; + }; + /** Starts a new sprite batch. */ + AbstractBatchRenderer.prototype.start = function () { + this.renderer.state.set(this.state); + this.renderer.texture.ensureSamplerType(this.MAX_TEXTURES); + this.renderer.shader.bind(this._shader); + if (settings.CAN_UPLOAD_SAME_BUFFER) { + // bind buffer #0, we don't need others + this.renderer.geometry.bind(this._packedGeometries[this._flushId]); + } + }; + /** Stops and flushes the current batch. */ + AbstractBatchRenderer.prototype.stop = function () { + this.flush(); + }; + /** Destroys this `AbstractBatchRenderer`. It cannot be used again. */ + AbstractBatchRenderer.prototype.destroy = function () { + for (var i = 0; i < this._packedGeometryPoolSize; i++) { + if (this._packedGeometries[i]) { + this._packedGeometries[i].destroy(); + } + } + this.renderer.off('prerender', this.onPrerender, this); + this._aBuffers = null; + this._iBuffers = null; + this._packedGeometries = null; + this._attributeBuffer = null; + this._indexBuffer = null; + if (this._shader) { + this._shader.destroy(); + this._shader = null; + } + _super.prototype.destroy.call(this); + }; + /** + * Fetches an attribute buffer from `this._aBuffers` that can hold atleast `size` floats. + * @param size - minimum capacity required + * @returns - buffer than can hold atleast `size` floats + */ + AbstractBatchRenderer.prototype.getAttributeBuffer = function (size) { + // 8 vertices is enough for 2 quads + var roundedP2 = nextPow2(Math.ceil(size / 8)); + var roundedSizeIndex = log2(roundedP2); + var roundedSize = roundedP2 * 8; + if (this._aBuffers.length <= roundedSizeIndex) { + this._iBuffers.length = roundedSizeIndex + 1; + } + var buffer = this._aBuffers[roundedSize]; + if (!buffer) { + this._aBuffers[roundedSize] = buffer = new ViewableBuffer(roundedSize * this.vertexSize * 4); + } + return buffer; + }; + /** + * Fetches an index buffer from `this._iBuffers` that can + * have at least `size` capacity. + * @param size - minimum required capacity + * @returns - buffer that can fit `size` indices. + */ + AbstractBatchRenderer.prototype.getIndexBuffer = function (size) { + // 12 indices is enough for 2 quads + var roundedP2 = nextPow2(Math.ceil(size / 12)); + var roundedSizeIndex = log2(roundedP2); + var roundedSize = roundedP2 * 12; + if (this._iBuffers.length <= roundedSizeIndex) { + this._iBuffers.length = roundedSizeIndex + 1; + } + var buffer = this._iBuffers[roundedSizeIndex]; + if (!buffer) { + this._iBuffers[roundedSizeIndex] = buffer = new Uint16Array(roundedSize); + } + return buffer; + }; + /** + * Takes the four batching parameters of `element`, interleaves + * and pushes them into the batching attribute/index buffers given. + * + * It uses these properties: `vertexData` `uvs`, `textureId` and + * `indicies`. It also uses the "tint" of the base-texture, if + * present. + * @param {PIXI.DisplayObject} element - element being rendered + * @param attributeBuffer - attribute buffer. + * @param indexBuffer - index buffer + * @param aIndex - number of floats already in the attribute buffer + * @param iIndex - number of indices already in `indexBuffer` + */ + AbstractBatchRenderer.prototype.packInterleavedGeometry = function (element, attributeBuffer, indexBuffer, aIndex, iIndex) { + var uint32View = attributeBuffer.uint32View, float32View = attributeBuffer.float32View; + var packedVertices = aIndex / this.vertexSize; + var uvs = element.uvs; + var indicies = element.indices; + var vertexData = element.vertexData; + var textureId = element._texture.baseTexture._batchLocation; + var alpha = Math.min(element.worldAlpha, 1.0); + var argb = (alpha < 1.0 + && element._texture.baseTexture.alphaMode) + ? premultiplyTint(element._tintRGB, alpha) + : element._tintRGB + (alpha * 255 << 24); + // lets not worry about tint! for now.. + for (var i = 0; i < vertexData.length; i += 2) { + float32View[aIndex++] = vertexData[i]; + float32View[aIndex++] = vertexData[i + 1]; + float32View[aIndex++] = uvs[i]; + float32View[aIndex++] = uvs[i + 1]; + uint32View[aIndex++] = argb; + float32View[aIndex++] = textureId; + } + for (var i = 0; i < indicies.length; i++) { + indexBuffer[iIndex++] = packedVertices + indicies[i]; + } + }; + /** + * Pool of `BatchDrawCall` objects that `flush` used + * to create "batches" of the objects being rendered. + * + * These are never re-allocated again. + * Shared between all batch renderers because it can be only one "flush" working at the moment. + * @member {PIXI.BatchDrawCall[]} + */ + AbstractBatchRenderer._drawCallPool = []; + /** + * Pool of `BatchDrawCall` objects that `flush` used + * to create "batches" of the objects being rendered. + * + * These are never re-allocated again. + * Shared between all batch renderers because it can be only one "flush" working at the moment. + * @member {PIXI.BatchTextureArray[]} + */ + AbstractBatchRenderer._textureArrayPool = []; + return AbstractBatchRenderer; + }(ObjectRenderer)); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** + * Helper that generates batching multi-texture shader. Use it with your new BatchRenderer + * @memberof PIXI + */ + var BatchShaderGenerator = /** @class */ (function () { + /** + * @param vertexSrc - Vertex shader + * @param fragTemplate - Fragment shader template + */ + function BatchShaderGenerator(vertexSrc, fragTemplate) { + this.vertexSrc = vertexSrc; + this.fragTemplate = fragTemplate; + this.programCache = {}; + this.defaultGroupCache = {}; + if (fragTemplate.indexOf('%count%') < 0) { + throw new Error('Fragment template must contain "%count%".'); + } + if (fragTemplate.indexOf('%forloop%') < 0) { + throw new Error('Fragment template must contain "%forloop%".'); + } + } + BatchShaderGenerator.prototype.generateShader = function (maxTextures) { + if (!this.programCache[maxTextures]) { + var sampleValues = new Int32Array(maxTextures); + for (var i = 0; i < maxTextures; i++) { + sampleValues[i] = i; + } + this.defaultGroupCache[maxTextures] = UniformGroup.from({ uSamplers: sampleValues }, true); + var fragmentSrc = this.fragTemplate; + fragmentSrc = fragmentSrc.replace(/%count%/gi, "" + maxTextures); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, this.generateSampleSrc(maxTextures)); + this.programCache[maxTextures] = new Program(this.vertexSrc, fragmentSrc); + } + var uniforms = { + tint: new Float32Array([1, 1, 1, 1]), + translationMatrix: new Matrix(), + default: this.defaultGroupCache[maxTextures], + }; + return new Shader(this.programCache[maxTextures], uniforms); + }; + BatchShaderGenerator.prototype.generateSampleSrc = function (maxTextures) { + var src = ''; + src += '\n'; + src += '\n'; + for (var i = 0; i < maxTextures; i++) { + if (i > 0) { + src += '\nelse '; + } + if (i < maxTextures - 1) { + src += "if(vTextureId < " + i + ".5)"; + } + src += '\n{'; + src += "\n\tcolor = texture2D(uSamplers[" + i + "], vTextureCoord);"; + src += '\n}'; + } + src += '\n'; + src += '\n'; + return src; + }; + return BatchShaderGenerator; + }()); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + /** + * Geometry used to batch standard PIXI content (e.g. Mesh, Sprite, Graphics objects). + * @memberof PIXI + */ + var BatchGeometry = /** @class */ (function (_super) { + __extends$i(BatchGeometry, _super); + /** + * @param {boolean} [_static=false] - Optimization flag, where `false` + * is updated every frame, `true` doesn't change frame-to-frame. + */ + function BatchGeometry(_static) { + if (_static === void 0) { _static = false; } + var _this = _super.call(this) || this; + _this._buffer = new Buffer(null, _static, false); + _this._indexBuffer = new Buffer(null, _static, true); + _this.addAttribute('aVertexPosition', _this._buffer, 2, false, exports.TYPES.FLOAT) + .addAttribute('aTextureCoord', _this._buffer, 2, false, exports.TYPES.FLOAT) + .addAttribute('aColor', _this._buffer, 4, true, exports.TYPES.UNSIGNED_BYTE) + .addAttribute('aTextureId', _this._buffer, 1, true, exports.TYPES.FLOAT) + .addIndex(_this._indexBuffer); + return _this; + } + return BatchGeometry; + }(Geometry)); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var defaultVertex = "precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform vec4 tint;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor * tint;\n}\n"; -var SharedTicker = core.ticker.shared; + var defaultFragment = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\nuniform sampler2D uSamplers[%count%];\n\nvoid main(void){\n vec4 color;\n %forloop%\n gl_FragColor = color * vColor;\n}\n"; -/** - * Default number of uploads per frame using prepare plugin. - * - * @static - * @memberof PIXI.settings - * @name UPLOADS_PER_FRAME - * @type {number} - * @default 4 - */ -core.settings.UPLOADS_PER_FRAME = 4; + /** @memberof PIXI */ + var BatchPluginFactory = /** @class */ (function () { + function BatchPluginFactory() { + } + /** + * Create a new BatchRenderer plugin for Renderer. this convenience can provide an easy way + * to extend BatchRenderer with all the necessary pieces. + * @example + * const fragment = ` + * varying vec2 vTextureCoord; + * varying vec4 vColor; + * varying float vTextureId; + * uniform sampler2D uSamplers[%count%]; + * + * void main(void){ + * vec4 color; + * %forloop% + * gl_FragColor = vColor * vec4(color.a - color.rgb, color.a); + * } + * `; + * const InvertBatchRenderer = PIXI.BatchPluginFactory.create({ fragment }); + * PIXI.extensions.add({ + * name: 'invert', + * ref: InvertBatchRenderer, + * type: PIXI.ExtensionType.RendererPlugin, + * }); + * const sprite = new PIXI.Sprite(); + * sprite.pluginName = 'invert'; + * @param {object} [options] + * @param {string} [options.vertex=PIXI.BatchPluginFactory.defaultVertexSrc] - Vertex shader source + * @param {string} [options.fragment=PIXI.BatchPluginFactory.defaultFragmentTemplate] - Fragment shader template + * @param {number} [options.vertexSize=6] - Vertex size + * @param {object} [options.geometryClass=PIXI.BatchGeometry] + * @returns {*} New batch renderer plugin + */ + BatchPluginFactory.create = function (options) { + var _a = Object.assign({ + vertex: defaultVertex, + fragment: defaultFragment, + geometryClass: BatchGeometry, + vertexSize: 6, + }, options), vertex = _a.vertex, fragment = _a.fragment, vertexSize = _a.vertexSize, geometryClass = _a.geometryClass; + return /** @class */ (function (_super) { + __extends$i(BatchPlugin, _super); + function BatchPlugin(renderer) { + var _this = _super.call(this, renderer) || this; + _this.shaderGenerator = new BatchShaderGenerator(vertex, fragment); + _this.geometryClass = geometryClass; + _this.vertexSize = vertexSize; + return _this; + } + return BatchPlugin; + }(AbstractBatchRenderer)); + }; + Object.defineProperty(BatchPluginFactory, "defaultVertexSrc", { + /** + * The default vertex shader source + * @readonly + */ + get: function () { + return defaultVertex; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BatchPluginFactory, "defaultFragmentTemplate", { + /** + * The default fragment shader source + * @readonly + */ + get: function () { + return defaultFragment; + }, + enumerable: false, + configurable: true + }); + return BatchPluginFactory; + }()); + // Setup the default BatchRenderer plugin, this is what + // we'll actually export at the root level + var BatchRenderer = BatchPluginFactory.create(); + Object.assign(BatchRenderer, { + extension: { + name: 'batch', + type: exports.ExtensionType.RendererPlugin, + }, + }); -/** - * The prepare manager provides functionality to upload content to the GPU. BasePrepare handles - * basic queuing functionality and is extended by {@link PIXI.prepare.WebGLPrepare} and {@link PIXI.prepare.CanvasPrepare} - * to provide preparation capabilities specific to their respective renderers. - * - * @example - * // Create a sprite - * const sprite = new PIXI.Sprite.fromImage('something.png'); - * - * // Load object into GPU - * app.renderer.plugins.prepare.upload(sprite, () => { - * - * //Texture(s) has been uploaded to GPU - * app.stage.addChild(sprite); - * - * }) - * - * @abstract - * @class - * @memberof PIXI.prepare - */ + /** + * @memberof PIXI + * @namespace resources + * @see PIXI + * @deprecated since 6.0.0 + */ + var resources = {}; + var _loop_1 = function (name) { + Object.defineProperty(resources, name, { + get: function () { + deprecation('6.0.0', "PIXI.systems." + name + " has moved to PIXI." + name); + return _resources[name]; + }, + }); + }; + for (var name in _resources) { + _loop_1(name); + } + /** + * @memberof PIXI + * @namespace systems + * @see PIXI + * @deprecated since 6.0.0 + */ + var systems = {}; + var _loop_2 = function (name) { + Object.defineProperty(systems, name, { + get: function () { + deprecation('6.0.0', "PIXI.resources." + name + " has moved to PIXI." + name); + return _systems[name]; + }, + }); + }; + for (var name in _systems) { + _loop_2(name); + } -var BasePrepare = function () { - /** - * @param {PIXI.SystemRenderer} renderer - A reference to the current renderer - */ - function BasePrepare(renderer) { - var _this = this; - - _classCallCheck(this, BasePrepare); - - /** - * The limiter to be used to control how quickly items are prepared. - * @type {PIXI.prepare.CountLimiter|PIXI.prepare.TimeLimiter} - */ - this.limiter = new _CountLimiter2.default(core.settings.UPLOADS_PER_FRAME); - - /** - * Reference to the renderer. - * @type {PIXI.SystemRenderer} - * @protected - */ - this.renderer = renderer; - - /** - * The only real difference between CanvasPrepare and WebGLPrepare is what they pass - * to upload hooks. That different parameter is stored here. - * @type {PIXI.prepare.CanvasPrepare|PIXI.WebGLRenderer} - * @protected - */ - this.uploadHookHelper = null; - - /** - * Collection of items to uploads at once. - * @type {Array<*>} - * @private - */ - this.queue = []; - - /** - * Collection of additional hooks for finding assets. - * @type {Array} - * @private - */ - this.addHooks = []; - - /** - * Collection of additional hooks for processing assets. - * @type {Array} - * @private - */ - this.uploadHooks = []; - - /** - * Callback to call after completed. - * @type {Array} - * @private - */ - this.completes = []; - - /** - * If prepare is ticking (running). - * @type {boolean} - * @private - */ - this.ticking = false; - - /** - * 'bound' call for prepareItems(). - * @type {Function} - * @private - */ - this.delayedTick = function () { - // unlikely, but in case we were destroyed between tick() and delayedTick() - if (!_this.queue) { - return; - } - _this.prepareItems(); - }; - - // hooks to find the correct texture - this.registerFindHook(findText); - this.registerFindHook(findTextStyle); - this.registerFindHook(findMultipleBaseTextures); - this.registerFindHook(findBaseTexture); - this.registerFindHook(findTexture); - - // upload hooks - this.registerUploadHook(drawText); - this.registerUploadHook(calculateTextStyle); - } + /** + * @namespace PIXI + */ + /** + * String of the current PIXI version. + * @memberof PIXI + */ + var VERSION = '6.5.10'; - /** - * Upload all the textures and graphics to the GPU. - * - * @param {Function|PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text} item - - * Either the container or display object to search for items to upload, the items to upload themselves, - * or the callback function, if items have been added using `prepare.add`. - * @param {Function} [done] - Optional callback when all queued uploads have completed - */ + /*! + * @pixi/accessibility - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/accessibility is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * Default property values of accessible objects + * used by {@link PIXI.AccessibilityManager}. + * @private + * @function accessibleTarget + * @memberof PIXI + * @type {object} + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.accessibleTarget + * ); + */ + var accessibleTarget = { + /** + * Flag for if the object is accessible. If true AccessibilityManager will overlay a + * shadow div with attributes set + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + accessible: false, + /** + * Sets the title attribute of the shadow div + * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * @member {?string} + * @memberof PIXI.DisplayObject# + */ + accessibleTitle: null, + /** + * Sets the aria-label attribute of the shadow div + * @member {string} + * @memberof PIXI.DisplayObject# + */ + accessibleHint: null, + /** + * @member {number} + * @memberof PIXI.DisplayObject# + * @private + * @todo Needs docs. + */ + tabIndex: 0, + /** + * @member {boolean} + * @memberof PIXI.DisplayObject# + * @todo Needs docs. + */ + _accessibleActive: false, + /** + * @member {boolean} + * @memberof PIXI.DisplayObject# + * @todo Needs docs. + */ + _accessibleDiv: null, + /** + * Specify the type of div the accessible layer is. Screen readers treat the element differently + * depending on this type. Defaults to button. + * @member {string} + * @memberof PIXI.DisplayObject# + * @default 'button' + */ + accessibleType: 'button', + /** + * Specify the pointer-events the accessible div will use + * Defaults to auto. + * @member {string} + * @memberof PIXI.DisplayObject# + * @default 'auto' + */ + accessiblePointerEvents: 'auto', + /** + * Setting to false will prevent any children inside this container to + * be accessible. Defaults to true. + * @member {boolean} + * @memberof PIXI.DisplayObject# + * @default true + */ + accessibleChildren: true, + renderId: -1, + }; - BasePrepare.prototype.upload = function upload(item, done) { - if (typeof item === 'function') { - done = item; - item = null; - } + // add some extra variables to the container.. + DisplayObject.mixin(accessibleTarget); + var KEY_CODE_TAB = 9; + var DIV_TOUCH_SIZE = 100; + var DIV_TOUCH_POS_X = 0; + var DIV_TOUCH_POS_Y = 0; + var DIV_TOUCH_ZINDEX = 2; + var DIV_HOOK_SIZE = 1; + var DIV_HOOK_POS_X = -1000; + var DIV_HOOK_POS_Y = -1000; + var DIV_HOOK_ZINDEX = 2; + /** + * The Accessibility manager recreates the ability to tab and have content read by screen readers. + * This is very important as it can possibly help people with disabilities access PixiJS content. + * + * A DisplayObject can be made accessible just like it can be made interactive. This manager will map the + * events as if the mouse was being used, minimizing the effort required to implement. + * + * An instance of this class is automatically created by default, and can be found at `renderer.plugins.accessibility` + * @class + * @memberof PIXI + */ + var AccessibilityManager = /** @class */ (function () { + /** + * @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer + */ + function AccessibilityManager(renderer) { + /** Setting this to true will visually show the divs. */ + this.debug = false; + /** Internal variable, see isActive getter. */ + this._isActive = false; + /** Internal variable, see isMobileAccessibility getter. */ + this._isMobileAccessibility = false; + /** A simple pool for storing divs. */ + this.pool = []; + /** This is a tick used to check if an object is no longer being rendered. */ + this.renderId = 0; + /** The array of currently active accessible items. */ + this.children = []; + /** Count to throttle div updates on android devices. */ + this.androidUpdateCount = 0; + /** The frequency to update the div elements. */ + this.androidUpdateFrequency = 500; // 2fps + this._hookDiv = null; + if (isMobile.tablet || isMobile.phone) { + this.createTouchHook(); + } + // first we create a div that will sit over the PixiJS element. This is where the div overlays will go. + var div = document.createElement('div'); + div.style.width = DIV_TOUCH_SIZE + "px"; + div.style.height = DIV_TOUCH_SIZE + "px"; + div.style.position = 'absolute'; + div.style.top = DIV_TOUCH_POS_X + "px"; + div.style.left = DIV_TOUCH_POS_Y + "px"; + div.style.zIndex = DIV_TOUCH_ZINDEX.toString(); + this.div = div; + this.renderer = renderer; + /** + * pre-bind the functions + * @type {Function} + * @private + */ + this._onKeyDown = this._onKeyDown.bind(this); + /** + * pre-bind the functions + * @type {Function} + * @private + */ + this._onMouseMove = this._onMouseMove.bind(this); + // let listen for tab.. once pressed we can fire up and show the accessibility layer + globalThis.addEventListener('keydown', this._onKeyDown, false); + } + Object.defineProperty(AccessibilityManager.prototype, "isActive", { + /** + * Value of `true` if accessibility is currently active and accessibility layers are showing. + * @member {boolean} + * @readonly + */ + get: function () { + return this._isActive; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AccessibilityManager.prototype, "isMobileAccessibility", { + /** + * Value of `true` if accessibility is enabled for touch devices. + * @member {boolean} + * @readonly + */ + get: function () { + return this._isMobileAccessibility; + }, + enumerable: false, + configurable: true + }); + /** + * Creates the touch hooks. + * @private + */ + AccessibilityManager.prototype.createTouchHook = function () { + var _this = this; + var hookDiv = document.createElement('button'); + hookDiv.style.width = DIV_HOOK_SIZE + "px"; + hookDiv.style.height = DIV_HOOK_SIZE + "px"; + hookDiv.style.position = 'absolute'; + hookDiv.style.top = DIV_HOOK_POS_X + "px"; + hookDiv.style.left = DIV_HOOK_POS_Y + "px"; + hookDiv.style.zIndex = DIV_HOOK_ZINDEX.toString(); + hookDiv.style.backgroundColor = '#FF0000'; + hookDiv.title = 'select to enable accessibility for this content'; + hookDiv.addEventListener('focus', function () { + _this._isMobileAccessibility = true; + _this.activate(); + _this.destroyTouchHook(); + }); + document.body.appendChild(hookDiv); + this._hookDiv = hookDiv; + }; + /** + * Destroys the touch hooks. + * @private + */ + AccessibilityManager.prototype.destroyTouchHook = function () { + if (!this._hookDiv) { + return; + } + document.body.removeChild(this._hookDiv); + this._hookDiv = null; + }; + /** + * Activating will cause the Accessibility layer to be shown. + * This is called when a user presses the tab key. + * @private + */ + AccessibilityManager.prototype.activate = function () { + var _a; + if (this._isActive) { + return; + } + this._isActive = true; + globalThis.document.addEventListener('mousemove', this._onMouseMove, true); + globalThis.removeEventListener('keydown', this._onKeyDown, false); + this.renderer.on('postrender', this.update, this); + (_a = this.renderer.view.parentNode) === null || _a === void 0 ? void 0 : _a.appendChild(this.div); + }; + /** + * Deactivating will cause the Accessibility layer to be hidden. + * This is called when a user moves the mouse. + * @private + */ + AccessibilityManager.prototype.deactivate = function () { + var _a; + if (!this._isActive || this._isMobileAccessibility) { + return; + } + this._isActive = false; + globalThis.document.removeEventListener('mousemove', this._onMouseMove, true); + globalThis.addEventListener('keydown', this._onKeyDown, false); + this.renderer.off('postrender', this.update); + (_a = this.div.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this.div); + }; + /** + * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer. + * @private + * @param {PIXI.Container} displayObject - The DisplayObject to check. + */ + AccessibilityManager.prototype.updateAccessibleObjects = function (displayObject) { + if (!displayObject.visible || !displayObject.accessibleChildren) { + return; + } + if (displayObject.accessible && displayObject.interactive) { + if (!displayObject._accessibleActive) { + this.addChild(displayObject); + } + displayObject.renderId = this.renderId; + } + var children = displayObject.children; + if (children) { + for (var i = 0; i < children.length; i++) { + this.updateAccessibleObjects(children[i]); + } + } + }; + /** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. + * @private + */ + AccessibilityManager.prototype.update = function () { + /* On Android default web browser, tab order seems to be calculated by position rather than tabIndex, + * moving buttons can cause focus to flicker between two buttons making it hard/impossible to navigate, + * so I am just running update every half a second, seems to fix it. + */ + var now = performance.now(); + if (isMobile.android.device && now < this.androidUpdateCount) { + return; + } + this.androidUpdateCount = now + this.androidUpdateFrequency; + if (!this.renderer.renderingToScreen) { + return; + } + // update children... + if (this.renderer._lastObjectRendered) { + this.updateAccessibleObjects(this.renderer._lastObjectRendered); + } + var _a = this.renderer.view.getBoundingClientRect(), left = _a.left, top = _a.top, width = _a.width, height = _a.height; + var _b = this.renderer, viewWidth = _b.width, viewHeight = _b.height, resolution = _b.resolution; + var sx = (width / viewWidth) * resolution; + var sy = (height / viewHeight) * resolution; + var div = this.div; + div.style.left = left + "px"; + div.style.top = top + "px"; + div.style.width = viewWidth + "px"; + div.style.height = viewHeight + "px"; + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + if (child.renderId !== this.renderId) { + child._accessibleActive = false; + removeItems(this.children, i, 1); + this.div.removeChild(child._accessibleDiv); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + i--; + } + else { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; + if (child.hitArea) { + div.style.left = (wt.tx + (hitArea.x * wt.a)) * sx + "px"; + div.style.top = (wt.ty + (hitArea.y * wt.d)) * sy + "px"; + div.style.width = hitArea.width * wt.a * sx + "px"; + div.style.height = hitArea.height * wt.d * sy + "px"; + } + else { + hitArea = child.getBounds(); + this.capHitArea(hitArea); + div.style.left = hitArea.x * sx + "px"; + div.style.top = hitArea.y * sy + "px"; + div.style.width = hitArea.width * sx + "px"; + div.style.height = hitArea.height * sy + "px"; + // update button titles and hints if they exist and they've changed + if (div.title !== child.accessibleTitle && child.accessibleTitle !== null) { + div.title = child.accessibleTitle; + } + if (div.getAttribute('aria-label') !== child.accessibleHint + && child.accessibleHint !== null) { + div.setAttribute('aria-label', child.accessibleHint); + } + } + // the title or index may have changed, if so lets update it! + if (child.accessibleTitle !== div.title || child.tabIndex !== div.tabIndex) { + div.title = child.accessibleTitle; + div.tabIndex = child.tabIndex; + if (this.debug) + { this.updateDebugHTML(div); } + } + } + } + // increment the render id.. + this.renderId++; + }; + /** + * private function that will visually add the information to the + * accessability div + * @param {HTMLElement} div - + */ + AccessibilityManager.prototype.updateDebugHTML = function (div) { + div.innerHTML = "type: " + div.type + "
title : " + div.title + "
tabIndex: " + div.tabIndex; + }; + /** + * Adjust the hit area based on the bounds of a display object + * @param {PIXI.Rectangle} hitArea - Bounds of the child + */ + AccessibilityManager.prototype.capHitArea = function (hitArea) { + if (hitArea.x < 0) { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + if (hitArea.y < 0) { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + var _a = this.renderer, viewWidth = _a.width, viewHeight = _a.height; + if (hitArea.x + hitArea.width > viewWidth) { + hitArea.width = viewWidth - hitArea.x; + } + if (hitArea.y + hitArea.height > viewHeight) { + hitArea.height = viewHeight - hitArea.y; + } + }; + /** + * Adds a DisplayObject to the accessibility manager + * @private + * @param {PIXI.DisplayObject} displayObject - The child to make accessible. + */ + AccessibilityManager.prototype.addChild = function (displayObject) { + // this.activate(); + var div = this.pool.pop(); + if (!div) { + div = document.createElement('button'); + div.style.width = DIV_TOUCH_SIZE + "px"; + div.style.height = DIV_TOUCH_SIZE + "px"; + div.style.backgroundColor = this.debug ? 'rgba(255,255,255,0.5)' : 'transparent'; + div.style.position = 'absolute'; + div.style.zIndex = DIV_TOUCH_ZINDEX.toString(); + div.style.borderStyle = 'none'; + // ARIA attributes ensure that button title and hint updates are announced properly + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + // Chrome doesn't need aria-live to work as intended; in fact it just gets more confused. + div.setAttribute('aria-live', 'off'); + } + else { + div.setAttribute('aria-live', 'polite'); + } + if (navigator.userAgent.match(/rv:.*Gecko\//)) { + // FireFox needs this to announce only the new button name + div.setAttribute('aria-relevant', 'additions'); + } + else { + // required by IE, other browsers don't much care + div.setAttribute('aria-relevant', 'text'); + } + div.addEventListener('click', this._onClick.bind(this)); + div.addEventListener('focus', this._onFocus.bind(this)); + div.addEventListener('focusout', this._onFocusOut.bind(this)); + } + // set pointer events + div.style.pointerEvents = displayObject.accessiblePointerEvents; + // set the type, this defaults to button! + div.type = displayObject.accessibleType; + if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null) { + div.title = displayObject.accessibleTitle; + } + else if (!displayObject.accessibleHint + || displayObject.accessibleHint === null) { + div.title = "displayObject " + displayObject.tabIndex; + } + if (displayObject.accessibleHint + && displayObject.accessibleHint !== null) { + div.setAttribute('aria-label', displayObject.accessibleHint); + } + if (this.debug) + { this.updateDebugHTML(div); } + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + this.children.push(displayObject); + this.div.appendChild(displayObject._accessibleDiv); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; + }; + /** + * Maps the div button press to pixi's InteractionManager (click) + * @private + * @param {MouseEvent} e - The click event. + */ + AccessibilityManager.prototype._onClick = function (e) { + var interactionManager = this.renderer.plugins.interaction; + var displayObject = e.target.displayObject; + var eventData = interactionManager.eventData; + interactionManager.dispatchEvent(displayObject, 'click', eventData); + interactionManager.dispatchEvent(displayObject, 'pointertap', eventData); + interactionManager.dispatchEvent(displayObject, 'tap', eventData); + }; + /** + * Maps the div focus events to pixi's InteractionManager (mouseover) + * @private + * @param {FocusEvent} e - The focus event. + */ + AccessibilityManager.prototype._onFocus = function (e) { + if (!e.target.getAttribute('aria-live')) { + e.target.setAttribute('aria-live', 'assertive'); + } + var interactionManager = this.renderer.plugins.interaction; + var displayObject = e.target.displayObject; + var eventData = interactionManager.eventData; + interactionManager.dispatchEvent(displayObject, 'mouseover', eventData); + }; + /** + * Maps the div focus events to pixi's InteractionManager (mouseout) + * @private + * @param {FocusEvent} e - The focusout event. + */ + AccessibilityManager.prototype._onFocusOut = function (e) { + if (!e.target.getAttribute('aria-live')) { + e.target.setAttribute('aria-live', 'polite'); + } + var interactionManager = this.renderer.plugins.interaction; + var displayObject = e.target.displayObject; + var eventData = interactionManager.eventData; + interactionManager.dispatchEvent(displayObject, 'mouseout', eventData); + }; + /** + * Is called when a key is pressed + * @private + * @param {KeyboardEvent} e - The keydown event. + */ + AccessibilityManager.prototype._onKeyDown = function (e) { + if (e.keyCode !== KEY_CODE_TAB) { + return; + } + this.activate(); + }; + /** + * Is called when the mouse moves across the renderer element + * @private + * @param {MouseEvent} e - The mouse event. + */ + AccessibilityManager.prototype._onMouseMove = function (e) { + if (e.movementX === 0 && e.movementY === 0) { + return; + } + this.deactivate(); + }; + /** Destroys the accessibility manager */ + AccessibilityManager.prototype.destroy = function () { + this.destroyTouchHook(); + this.div = null; + globalThis.document.removeEventListener('mousemove', this._onMouseMove, true); + globalThis.removeEventListener('keydown', this._onKeyDown); + this.pool = null; + this.children = null; + this.renderer = null; + }; + /** @ignore */ + AccessibilityManager.extension = { + name: 'accessibility', + type: [ + exports.ExtensionType.RendererPlugin, + exports.ExtensionType.CanvasRendererPlugin ], + }; + return AccessibilityManager; + }()); + + /*! + * @pixi/interaction - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/interaction is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ - // If a display object, search for items - // that we could upload - if (item) { - this.add(item); - } + /** + * Holds all information related to an Interaction event + * @memberof PIXI + */ + var InteractionData = /** @class */ (function () { + function InteractionData() { + /** + * Pressure applied by the pointing device during the event. A Touch's force property + * will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure + */ + this.pressure = 0; + /** + * From TouchEvents (not PointerEvents triggered by touches), the rotationAngle of the Touch. + * @see https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle + */ + this.rotationAngle = 0; + /** + * Twist of a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + */ + this.twist = 0; + /** + * Barrel pressure on a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + */ + this.tangentialPressure = 0; + this.global = new Point(); + this.target = null; + this.originalEvent = null; + this.identifier = null; + this.isPrimary = false; + this.button = 0; + this.buttons = 0; + this.width = 0; + this.height = 0; + this.tiltX = 0; + this.tiltY = 0; + this.pointerType = null; + this.pressure = 0; + this.rotationAngle = 0; + this.twist = 0; + this.tangentialPressure = 0; + } + Object.defineProperty(InteractionData.prototype, "pointerId", { + /** + * The unique identifier of the pointer. It will be the same as `identifier`. + * @readonly + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId + */ + get: function () { + return this.identifier; + }, + enumerable: false, + configurable: true + }); + /** + * This will return the local coordinates of the specified displayObject for this InteractionData + * @param displayObject - The DisplayObject that you would like the local + * coords off + * @param point - A Point object in which to store the value, optional (otherwise + * will create a new point) + * @param globalPos - A Point object containing your custom global coords, optional + * (otherwise will use the current global coords) + * @returns - A point containing the coordinates of the InteractionData position relative + * to the DisplayObject + */ + InteractionData.prototype.getLocalPosition = function (displayObject, point, globalPos) { + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); + }; + /** + * Copies properties from normalized event data. + * @param {Touch|MouseEvent|PointerEvent} event - The normalized event data + */ + InteractionData.prototype.copyEvent = function (event) { + // isPrimary should only change on touchstart/pointerdown, so we don't want to overwrite + // it with "false" on later events when our shim for it on touch events might not be + // accurate + if ('isPrimary' in event && event.isPrimary) { + this.isPrimary = true; + } + this.button = 'button' in event && event.button; + // event.buttons is not available in all browsers (ie. Safari), but it does have a non-standard + // event.which property instead, which conveys the same information. + var buttons = 'buttons' in event && event.buttons; + this.buttons = Number.isInteger(buttons) ? buttons : 'which' in event && event.which; + this.width = 'width' in event && event.width; + this.height = 'height' in event && event.height; + this.tiltX = 'tiltX' in event && event.tiltX; + this.tiltY = 'tiltY' in event && event.tiltY; + this.pointerType = 'pointerType' in event && event.pointerType; + this.pressure = 'pressure' in event && event.pressure; + this.rotationAngle = 'rotationAngle' in event && event.rotationAngle; + this.twist = ('twist' in event && event.twist) || 0; + this.tangentialPressure = ('tangentialPressure' in event && event.tangentialPressure) || 0; + }; + /** Resets the data for pooling. */ + InteractionData.prototype.reset = function () { + // isPrimary is the only property that we really need to reset - everything else is + // guaranteed to be overwritten + this.isPrimary = false; + }; + return InteractionData; + }()); + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$h = function(d, b) { + extendStatics$h = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$h(d, b); + }; - // Get the items for upload from the display - if (this.queue.length) { - if (done) { - this.completes.push(done); - } + function __extends$h(d, b) { + extendStatics$h(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } - if (!this.ticking) { - this.ticking = true; - SharedTicker.addOnce(this.tick, this, core.UPDATE_PRIORITY.UTILITY); - } - } else if (done) { - done(); - } - }; + /** + * Event class that mimics native DOM events. + * @memberof PIXI + */ + var InteractionEvent = /** @class */ (function () { + function InteractionEvent() { + this.stopped = false; + this.stopsPropagatingAt = null; + this.stopPropagationHint = false; + this.target = null; + this.currentTarget = null; + this.type = null; + this.data = null; + } + /** Prevents event from reaching any objects other than the current object. */ + InteractionEvent.prototype.stopPropagation = function () { + this.stopped = true; + this.stopPropagationHint = true; + this.stopsPropagatingAt = this.currentTarget; + }; + /** Resets the event. */ + InteractionEvent.prototype.reset = function () { + this.stopped = false; + this.stopsPropagatingAt = null; + this.stopPropagationHint = false; + this.currentTarget = null; + this.target = null; + }; + return InteractionEvent; + }()); - /** - * Handle tick update - * - * @private - */ + /** + * DisplayObjects with the {@link PIXI.interactiveTarget} mixin use this class to track interactions + * @class + * @private + * @memberof PIXI + */ + var InteractionTrackingData = /** @class */ (function () { + /** + * @param {number} pointerId - Unique pointer id of the event + * @private + */ + function InteractionTrackingData(pointerId) { + this._pointerId = pointerId; + this._flags = InteractionTrackingData.FLAGS.NONE; + } + /** + * + * @private + * @param {number} flag - The interaction flag to set + * @param {boolean} yn - Should the flag be set or unset + */ + InteractionTrackingData.prototype._doSet = function (flag, yn) { + if (yn) { + this._flags = this._flags | flag; + } + else { + this._flags = this._flags & (~flag); + } + }; + Object.defineProperty(InteractionTrackingData.prototype, "pointerId", { + /** + * Unique pointer id of the event + * @readonly + * @private + * @member {number} + */ + get: function () { + return this._pointerId; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "flags", { + /** + * State of the tracking data, expressed as bit flags + * @private + * @member {number} + */ + get: function () { + return this._flags; + }, + set: function (flags) { + this._flags = flags; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "none", { + /** + * Is the tracked event inactive (not over or down)? + * @private + * @member {number} + */ + get: function () { + return this._flags === InteractionTrackingData.FLAGS.NONE; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "over", { + /** + * Is the tracked event over the DisplayObject? + * @private + * @member {boolean} + */ + get: function () { + return (this._flags & InteractionTrackingData.FLAGS.OVER) !== 0; + }, + set: function (yn) { + this._doSet(InteractionTrackingData.FLAGS.OVER, yn); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "rightDown", { + /** + * Did the right mouse button come down in the DisplayObject? + * @private + * @member {boolean} + */ + get: function () { + return (this._flags & InteractionTrackingData.FLAGS.RIGHT_DOWN) !== 0; + }, + set: function (yn) { + this._doSet(InteractionTrackingData.FLAGS.RIGHT_DOWN, yn); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "leftDown", { + /** + * Did the left mouse button come down in the DisplayObject? + * @private + * @member {boolean} + */ + get: function () { + return (this._flags & InteractionTrackingData.FLAGS.LEFT_DOWN) !== 0; + }, + set: function (yn) { + this._doSet(InteractionTrackingData.FLAGS.LEFT_DOWN, yn); + }, + enumerable: false, + configurable: true + }); + InteractionTrackingData.FLAGS = Object.freeze({ + NONE: 0, + OVER: 1 << 0, + LEFT_DOWN: 1 << 1, + RIGHT_DOWN: 1 << 2, + }); + return InteractionTrackingData; + }()); + /** + * Strategy how to search through stage tree for interactive objects + * @memberof PIXI + */ + var TreeSearch = /** @class */ (function () { + function TreeSearch() { + this._tempPoint = new Point(); + } + /** + * Recursive implementation for findHit + * @private + * @param interactionEvent - event containing the point that + * is tested for collision + * @param displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param func - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param hitTest - this indicates if the objects inside should be hit test against the point + * @param interactive - Whether the displayObject is interactive + * @returns - Returns true if the displayObject hit the point + */ + TreeSearch.prototype.recursiveFindHit = function (interactionEvent, displayObject, func, hitTest, interactive) { + var _a; + if (!displayObject || !displayObject.visible) { + return false; + } + var point = interactionEvent.data.global; + // Took a little while to rework this function correctly! But now it is done and nice and optimized! ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS + // to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimization once an interactive object has been hit we can carry on + // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimization is that an object is not hit test directly if a child has already been hit. + interactive = displayObject.interactive || interactive; + var hit = false; + var interactiveParent = interactive; + // Flag here can set to false if the event is outside the parents hitArea or mask + var hitTestChildren = true; + // If there is a hitArea, no need to test against anything else if the pointer is not within the hitArea + // There is also no longer a need to hitTest children. + if (displayObject.hitArea) { + if (hitTest) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + if (!displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { + hitTest = false; + hitTestChildren = false; + } + else { + hit = true; + } + } + interactiveParent = false; + } + // If there is a mask, no need to hitTest against anything else if the pointer is not within the mask. + // We still want to hitTestChildren, however, to ensure a mouseout can still be generated. + // https://github.com/pixijs/pixi.js/issues/5135 + else if (displayObject._mask) { + if (hitTest) { + var maskObject = (displayObject._mask.isMaskData + ? displayObject._mask.maskObject : displayObject._mask); + if (maskObject && !((_a = maskObject.containsPoint) === null || _a === void 0 ? void 0 : _a.call(maskObject, point))) { + hitTest = false; + } + } + } + // ** FREE TIP **! If an object is not interactive or has no buttons in it + // (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow PixiJS to completely ignore and bypass checking the displayObjects children. + if (hitTestChildren && displayObject.interactiveChildren && displayObject.children) { + var children = displayObject.children; + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + // time to get recursive.. if this function will return if something is hit.. + var childHit = this.recursiveFindHit(interactionEvent, child, func, hitTest, interactiveParent); + if (childHit) { + // 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 (!child.parent) { + continue; + } + // we no longer need to hit test any more objects in this container as we we + // now know the parent has been hit + interactiveParent = false; + // If the child is interactive , that means that the object hit was actually + // interactive and not just the child of an interactive object. + // This means we no longer need to hit test anything else. We still need to run + // through all objects, but we don't need to perform any hit tests. + if (childHit) { + if (interactionEvent.target) { + hitTest = false; + } + hit = true; + } + } + } + } + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children + // has already been hit - but only if it was interactive, otherwise we need to keep + // looking for an interactive child, just in case we hit one + if (hitTest && !interactionEvent.target) { + // already tested against hitArea if it is defined + if (!displayObject.hitArea && displayObject.containsPoint) { + if (displayObject.containsPoint(point)) { + hit = true; + } + } + } + if (displayObject.interactive) { + if (hit && !interactionEvent.target) { + interactionEvent.target = displayObject; + } + if (func) { + func(interactionEvent, displayObject, !!hit); + } + } + } + return hit; + }; + /** + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. + * @private + * @param interactionEvent - event containing the point that + * is tested for collision + * @param displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param func - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param hitTest - this indicates if the objects inside should be hit test against the point + * @returns - Returns true if the displayObject hit the point + */ + TreeSearch.prototype.findHit = function (interactionEvent, displayObject, func, hitTest) { + this.recursiveFindHit(interactionEvent, displayObject, func, hitTest, false); + }; + return TreeSearch; + }()); - BasePrepare.prototype.tick = function tick() { - setTimeout(this.delayedTick, 0); - }; + /** + * Interface for classes that represent a hit area. + * + * It is implemented by the following classes: + * - {@link PIXI.Circle} + * - {@link PIXI.Ellipse} + * - {@link PIXI.Polygon} + * - {@link PIXI.RoundedRectangle} + * @interface IHitArea + * @memberof PIXI + */ + /** + * Checks whether the x and y coordinates given are contained within this area + * @method + * @name contains + * @memberof PIXI.IHitArea# + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @returns {boolean} Whether the x/y coordinates are within this area + */ + /** + * Default property values of interactive objects + * Used by {@link PIXI.InteractionManager} to automatically give all DisplayObjects these properties + * @private + * @name interactiveTarget + * @type {object} + * @memberof PIXI + * @example + * function MyObject() {} + * + * Object.assign( + * DisplayObject.prototype, + * PIXI.interactiveTarget + * ); + */ + var interactiveTarget = { + interactive: false, + interactiveChildren: true, + hitArea: null, + /** + * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive + * Setting this changes the 'cursor' property to `'pointer'`. + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.buttonMode = true; + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + get buttonMode() { + return this.cursor === 'pointer'; + }, + set buttonMode(value) { + if (value) { + this.cursor = 'pointer'; + } + else if (this.cursor === 'pointer') { + this.cursor = null; + } + }, + /** + * This defines what cursor mode is used when the mouse cursor + * is hovered over the displayObject. + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.cursor = 'wait'; + * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor + * @member {string} + * @memberof PIXI.DisplayObject# + */ + cursor: null, + /** + * Internal set of all active pointers, by identifier + * @member {Map} + * @memberof PIXI.DisplayObject# + * @private + */ + get trackedPointers() { + if (this._trackedPointers === undefined) + { this._trackedPointers = {}; } + return this._trackedPointers; + }, + /** + * Map of all tracked pointers, by identifier. Use trackedPointers to access. + * @private + * @type {Map} + */ + _trackedPointers: undefined, + }; - /** - * Actually prepare items. This is handled outside of the tick because it will take a while - * and we do NOT want to block the current animation frame from rendering. - * - * @private - */ - - - BasePrepare.prototype.prepareItems = function prepareItems() { - this.limiter.beginFrame(); - // Upload the graphics - while (this.queue.length && this.limiter.allowedToUpload()) { - var item = this.queue[0]; - var uploaded = false; - - if (item && !item._destroyed) { - for (var i = 0, len = this.uploadHooks.length; i < len; i++) { - if (this.uploadHooks[i](this.uploadHookHelper, item)) { - this.queue.shift(); - uploaded = true; - break; - } - } - } + // Mix interactiveTarget into DisplayObject.prototype + DisplayObject.mixin(interactiveTarget); + var MOUSE_POINTER_ID = 1; + // helpers for hitTest() - only used inside hitTest() + var hitTestEvent = { + target: null, + data: { + global: null, + }, + }; + /** + * The interaction manager deals with mouse, touch and pointer events. + * + * Any DisplayObject can be interactive if its `interactive` property is set to true. + * + * This manager also supports multitouch. + * + * An instance of this class is automatically created by default, and can be found at `renderer.plugins.interaction` + * @memberof PIXI + */ + var InteractionManager = /** @class */ (function (_super) { + __extends$h(InteractionManager, _super); + /** + * @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer + * @param options - The options for the manager. + * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. + * @param {number} [options.interactionFrequency=10] - Maximum frequency (ms) at pointer over/out states will be checked. + * @param {number} [options.useSystemTicker=true] - Whether to add {@link tickerUpdate} to {@link PIXI.Ticker.system}. + */ + function InteractionManager(renderer, options) { + var _this = _super.call(this) || this; + options = options || {}; + _this.renderer = renderer; + _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; + _this.interactionFrequency = options.interactionFrequency || 10; + _this.mouse = new InteractionData(); + _this.mouse.identifier = MOUSE_POINTER_ID; + // setting the mouse to start off far off screen will mean that mouse over does + // not get called before we even move the mouse. + _this.mouse.global.set(-999999); + _this.activeInteractionData = {}; + _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse; + _this.interactionDataPool = []; + _this.eventData = new InteractionEvent(); + _this.interactionDOMElement = null; + _this.moveWhenInside = false; + _this.eventsAdded = false; + _this.tickerAdded = false; + _this.mouseOverRenderer = !('PointerEvent' in globalThis); + _this.supportsTouchEvents = 'ontouchstart' in globalThis; + _this.supportsPointerEvents = !!globalThis.PointerEvent; + // this will make it so that you don't have to call bind all the time + _this.onPointerUp = _this.onPointerUp.bind(_this); + _this.processPointerUp = _this.processPointerUp.bind(_this); + _this.onPointerCancel = _this.onPointerCancel.bind(_this); + _this.processPointerCancel = _this.processPointerCancel.bind(_this); + _this.onPointerDown = _this.onPointerDown.bind(_this); + _this.processPointerDown = _this.processPointerDown.bind(_this); + _this.onPointerMove = _this.onPointerMove.bind(_this); + _this.processPointerMove = _this.processPointerMove.bind(_this); + _this.onPointerOut = _this.onPointerOut.bind(_this); + _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); + _this.onPointerOver = _this.onPointerOver.bind(_this); + _this.cursorStyles = { + default: 'inherit', + pointer: 'pointer', + }; + _this.currentCursorMode = null; + _this.cursor = null; + _this.resolution = 1; + _this.delayedEvents = []; + _this.search = new TreeSearch(); + _this._tempDisplayObject = new TemporaryDisplayObject(); + _this._eventListenerOptions = { capture: true, passive: false }; + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display + * object. + * @event PIXI.InteractionManager#mousedown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. + * @event PIXI.InteractionManager#rightdown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. + * @event PIXI.InteractionManager#mouseup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. + * @event PIXI.InteractionManager#rightup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. + * @event PIXI.InteractionManager#click + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. + * @event PIXI.InteractionManager#rightclick + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.InteractionManager#event:mousedown}. + * @event PIXI.InteractionManager#mouseupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.InteractionManager#event:rightdown}. + * @event PIXI.InteractionManager#rightupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object + * @event PIXI.InteractionManager#mousemove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object + * @event PIXI.InteractionManager#mouseover + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved off the display object + * @event PIXI.InteractionManager#mouseout + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is pressed on the display object. + * @event PIXI.InteractionManager#pointerdown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is released over the display object. + * Not always fired when some buttons are held down while others are released. In those cases, + * use [mousedown]{@link PIXI.InteractionManager#event:mousedown} and + * [mouseup]{@link PIXI.InteractionManager#event:mouseup} instead. + * @event PIXI.InteractionManager#pointerup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when the operating system cancels a pointer event + * @event PIXI.InteractionManager#pointercancel + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is pressed and released on the display object. + * @event PIXI.InteractionManager#pointertap + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.InteractionManager#event:pointerdown}. + * @event PIXI.InteractionManager#pointerupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved while over the display object + * @event PIXI.InteractionManager#pointermove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved onto the display object + * @event PIXI.InteractionManager#pointerover + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved off the display object + * @event PIXI.InteractionManager#pointerout + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is placed on the display object. + * @event PIXI.InteractionManager#touchstart + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is removed from the display object. + * @event PIXI.InteractionManager#touchend + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when the operating system cancels a touch + * @event PIXI.InteractionManager#touchcancel + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is placed and removed from the display object. + * @event PIXI.InteractionManager#tap + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.InteractionManager#event:touchstart}. + * @event PIXI.InteractionManager#touchendoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is moved along the display object. + * @event PIXI.InteractionManager#touchmove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display. + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#mousedown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#rightdown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#mouseup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#rightup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#click + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#rightclick + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.DisplayObject#event:mousedown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#mouseupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.DisplayObject#event:rightdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#rightupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#mousemove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#mouseover + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#mouseout + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is pressed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointerdown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is released over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointerup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when the operating system cancels a pointer event. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointercancel + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is pressed and released on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointertap + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.DisplayObject#event:pointerdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointerupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointermove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointerover + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointerout + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is placed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#touchstart + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#touchend + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when the operating system cancels a touch. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#touchcancel + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is placed and removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#tap + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.DisplayObject#event:touchstart}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#touchendoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is moved along the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#touchmove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + _this._useSystemTicker = options.useSystemTicker !== undefined ? options.useSystemTicker : true; + _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); + return _this; + } + Object.defineProperty(InteractionManager.prototype, "useSystemTicker", { + /** + * Should the InteractionManager automatically add {@link tickerUpdate} to {@link PIXI.Ticker.system}. + * @default true + */ + get: function () { + return this._useSystemTicker; + }, + set: function (useSystemTicker) { + this._useSystemTicker = useSystemTicker; + if (useSystemTicker) { + this.addTickerListener(); + } + else { + this.removeTickerListener(); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionManager.prototype, "lastObjectRendered", { + /** + * Last rendered object or temp object. + * @readonly + * @protected + */ + get: function () { + return this.renderer._lastObjectRendered || this._tempDisplayObject; + }, + enumerable: false, + configurable: true + }); + /** + * Hit tests a point against the display tree, returning the first interactive object that is hit. + * @param globalPoint - A point to hit test with, in global space. + * @param root - The root display object to start from. If omitted, defaults + * to the last rendered root of the associated renderer. + * @returns - The hit display object, if any. + */ + InteractionManager.prototype.hitTest = function (globalPoint, root) { + // clear the target for our hit test + hitTestEvent.target = null; + // assign the global point + hitTestEvent.data.global = globalPoint; + // ensure safety of the root + if (!root) { + root = this.lastObjectRendered; + } + // run the hit test + this.processInteractive(hitTestEvent, root, null, true); + // return our found object - it'll be null if we didn't hit anything + return hitTestEvent.target; + }; + /** + * Sets the DOM element which will receive mouse/touch events. This is useful for when you have + * other DOM elements on top of the renderers Canvas element. With this you'll be bale to delegate + * another DOM element to receive those events. + * @param element - the DOM element which will receive mouse and touch events. + * @param resolution - The resolution / device pixel ratio of the new element (relative to the canvas). + */ + InteractionManager.prototype.setTargetElement = function (element, resolution) { + if (resolution === void 0) { resolution = 1; } + this.removeTickerListener(); + this.removeEvents(); + this.interactionDOMElement = element; + this.resolution = resolution; + this.addEvents(); + this.addTickerListener(); + }; + /** Adds the ticker listener. */ + InteractionManager.prototype.addTickerListener = function () { + if (this.tickerAdded || !this.interactionDOMElement || !this._useSystemTicker) { + return; + } + Ticker.system.add(this.tickerUpdate, this, exports.UPDATE_PRIORITY.INTERACTION); + this.tickerAdded = true; + }; + /** Removes the ticker listener. */ + InteractionManager.prototype.removeTickerListener = function () { + if (!this.tickerAdded) { + return; + } + Ticker.system.remove(this.tickerUpdate, this); + this.tickerAdded = false; + }; + /** Registers all the DOM events. */ + InteractionManager.prototype.addEvents = function () { + if (this.eventsAdded || !this.interactionDOMElement) { + return; + } + var style = this.interactionDOMElement.style; + if (globalThis.navigator.msPointerEnabled) { + style.msContentZooming = 'none'; + style.msTouchAction = 'none'; + } + else if (this.supportsPointerEvents) { + style.touchAction = 'none'; + } + /* + * These events are added first, so that if pointer events are normalized, they are fired + * in the same order as non-normalized events. ie. pointer event 1st, mouse / touch 2nd + */ + if (this.supportsPointerEvents) { + globalThis.document.addEventListener('pointermove', this.onPointerMove, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, this._eventListenerOptions); + // pointerout is fired in addition to pointerup (for touch events) and pointercancel + // we already handle those, so for the purposes of what we do in onPointerOut, we only + // care about the pointerleave event + this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, this._eventListenerOptions); + globalThis.addEventListener('pointercancel', this.onPointerCancel, this._eventListenerOptions); + globalThis.addEventListener('pointerup', this.onPointerUp, this._eventListenerOptions); + } + else { + globalThis.document.addEventListener('mousemove', this.onPointerMove, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, this._eventListenerOptions); + globalThis.addEventListener('mouseup', this.onPointerUp, this._eventListenerOptions); + } + // always look directly for touch events so that we can provide original data + // In a future version we should change this to being just a fallback and rely solely on + // PointerEvents whenever available + if (this.supportsTouchEvents) { + this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, this._eventListenerOptions); + } + this.eventsAdded = true; + }; + /** Removes all the DOM events that were previously registered. */ + InteractionManager.prototype.removeEvents = function () { + if (!this.eventsAdded || !this.interactionDOMElement) { + return; + } + var style = this.interactionDOMElement.style; + if (globalThis.navigator.msPointerEnabled) { + style.msContentZooming = ''; + style.msTouchAction = ''; + } + else if (this.supportsPointerEvents) { + style.touchAction = ''; + } + if (this.supportsPointerEvents) { + globalThis.document.removeEventListener('pointermove', this.onPointerMove, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, this._eventListenerOptions); + globalThis.removeEventListener('pointercancel', this.onPointerCancel, this._eventListenerOptions); + globalThis.removeEventListener('pointerup', this.onPointerUp, this._eventListenerOptions); + } + else { + globalThis.document.removeEventListener('mousemove', this.onPointerMove, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, this._eventListenerOptions); + globalThis.removeEventListener('mouseup', this.onPointerUp, this._eventListenerOptions); + } + if (this.supportsTouchEvents) { + this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, this._eventListenerOptions); + } + this.interactionDOMElement = null; + this.eventsAdded = false; + }; + /** + * Updates the state of interactive objects if at least {@link interactionFrequency} + * milliseconds have passed since the last invocation. + * + * Invoked by a throttled ticker update from {@link PIXI.Ticker.system}. + * @param deltaTime - time delta since the last call + */ + InteractionManager.prototype.tickerUpdate = function (deltaTime) { + this._deltaTime += deltaTime; + if (this._deltaTime < this.interactionFrequency) { + return; + } + this._deltaTime = 0; + this.update(); + }; + /** Updates the state of interactive objects. */ + InteractionManager.prototype.update = function () { + if (!this.interactionDOMElement) { + return; + } + // if the user move the mouse this check has already been done using the mouse move! + if (this._didMove) { + this._didMove = false; + return; + } + this.cursor = null; + // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, + // but there was a scenario of a display object moving under a static mouse cursor. + // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function + for (var k in this.activeInteractionData) { + // eslint-disable-next-line no-prototype-builtins + if (this.activeInteractionData.hasOwnProperty(k)) { + var interactionData = this.activeInteractionData[k]; + if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData); + this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerOverOut, true); + } + } + } + this.setCursorMode(this.cursor); + }; + /** + * Sets the current cursor mode, handling any callbacks or CSS style changes. + * @param mode - cursor mode, a key from the cursorStyles dictionary + */ + InteractionManager.prototype.setCursorMode = function (mode) { + mode = mode || 'default'; + var applyStyles = true; + // offscreen canvas does not support setting styles, but cursor modes can be functions, + // in order to handle pixi rendered cursors, so we can't bail + if (globalThis.OffscreenCanvas && this.interactionDOMElement instanceof OffscreenCanvas) { + applyStyles = false; + } + // if the mode didn't actually change, bail early + if (this.currentCursorMode === mode) { + return; + } + this.currentCursorMode = mode; + var style = this.cursorStyles[mode]; + // only do things if there is a cursor style for it + if (style) { + switch (typeof style) { + case 'string': + // string styles are handled as cursor CSS + if (applyStyles) { + this.interactionDOMElement.style.cursor = style; + } + break; + case 'function': + // functions are just called, and passed the cursor mode + style(mode); + break; + case 'object': + // if it is an object, assume that it is a dictionary of CSS styles, + // apply it to the interactionDOMElement + if (applyStyles) { + Object.assign(this.interactionDOMElement.style, style); + } + break; + } + } + else if (applyStyles && typeof mode === 'string' && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) { + // if it mode is a string (not a Symbol) and cursorStyles doesn't have any entry + // for the mode, then assume that the dev wants it to be CSS for the cursor. + this.interactionDOMElement.style.cursor = mode; + } + }; + /** + * Dispatches an event on the display object that was interacted with. + * @param displayObject - the display object in question + * @param eventString - the name of the event (e.g, mousedown) + * @param eventData - the event data object + */ + InteractionManager.prototype.dispatchEvent = function (displayObject, eventString, eventData) { + // Even if the event was stopped, at least dispatch any remaining events + // for the same display object. + if (!eventData.stopPropagationHint || displayObject === eventData.stopsPropagatingAt) { + eventData.currentTarget = displayObject; + eventData.type = eventString; + displayObject.emit(eventString, eventData); + if (displayObject[eventString]) { + displayObject[eventString](eventData); + } + } + }; + /** + * Puts a event on a queue to be dispatched later. This is used to guarantee correct + * ordering of over/out events. + * @param displayObject - the display object in question + * @param eventString - the name of the event (e.g, mousedown) + * @param eventData - the event data object + */ + InteractionManager.prototype.delayDispatchEvent = function (displayObject, eventString, eventData) { + this.delayedEvents.push({ displayObject: displayObject, eventString: eventString, eventData: eventData }); + }; + /** + * Maps x and y coords from a DOM object and maps them correctly to the PixiJS view. The + * resulting value is stored in the point. This takes into account the fact that the DOM + * element could be scaled and positioned anywhere on the screen. + * @param point - the point that the result will be stored in + * @param x - the x coord of the position to map + * @param y - the y coord of the position to map + */ + InteractionManager.prototype.mapPositionToPoint = function (point, x, y) { + var rect; + // IE 11 fix + if (!this.interactionDOMElement.parentElement) { + rect = { + x: 0, + y: 0, + width: this.interactionDOMElement.width, + height: this.interactionDOMElement.height, + left: 0, + top: 0 + }; + } + else { + rect = this.interactionDOMElement.getBoundingClientRect(); + } + var resolutionMultiplier = 1.0 / this.resolution; + point.x = ((x - rect.left) * (this.interactionDOMElement.width / rect.width)) * resolutionMultiplier; + point.y = ((y - rect.top) * (this.interactionDOMElement.height / rect.height)) * resolutionMultiplier; + }; + /** + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. + * @protected + * @param interactionEvent - event containing the point that + * is tested for collision + * @param displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param func - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param hitTest - indicates whether we want to calculate hits + * or just iterate through all interactive objects + */ + InteractionManager.prototype.processInteractive = function (interactionEvent, displayObject, func, hitTest) { + var hit = this.search.findHit(interactionEvent, displayObject, func, hitTest); + var delayedEvents = this.delayedEvents; + if (!delayedEvents.length) { + return hit; + } + // Reset the propagation hint, because we start deeper in the tree again. + interactionEvent.stopPropagationHint = false; + var delayedLen = delayedEvents.length; + this.delayedEvents = []; + for (var i = 0; i < delayedLen; i++) { + var _a = delayedEvents[i], displayObject_1 = _a.displayObject, eventString = _a.eventString, eventData = _a.eventData; + // When we reach the object we wanted to stop propagating at, + // set the propagation hint. + if (eventData.stopsPropagatingAt === displayObject_1) { + eventData.stopPropagationHint = true; + } + this.dispatchEvent(displayObject_1, eventString, eventData); + } + return hit; + }; + /** + * Is called when the pointer button is pressed down on the renderer element + * @param originalEvent - The DOM event of a pointer button being pressed down + */ + InteractionManager.prototype.onPointerDown = function (originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') + { return; } + var events = this.normalizeToPointerData(originalEvent); + /* + * No need to prevent default on natural pointer events, as there are no side effects + * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, + * so still need to be prevented. + */ + // Guaranteed that there will be at least one event in events, and all events must have the same pointer type + if (this.autoPreventDefault && events[0].isNormalized) { + var cancelable = originalEvent.cancelable || !('cancelable' in originalEvent); + if (cancelable) { + originalEvent.preventDefault(); + } + } + var eventLen = events.length; + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = originalEvent; + this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerDown, true); + this.emit('pointerdown', interactionEvent); + if (event.pointerType === 'touch') { + this.emit('touchstart', interactionEvent); + } + // emit a mouse event for "pen" pointers, the way a browser would emit a fallback event + else if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); + } + } + }; + /** + * Processes the result of the pointer down check and dispatches the event if need be + * @param interactionEvent - The interaction event wrapping the DOM event + * @param displayObject - The display object that was tested + * @param hit - the result of the hit test on the display object + */ + InteractionManager.prototype.processPointerDown = function (interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + if (hit) { + if (!displayObject.trackedPointers[id]) { + displayObject.trackedPointers[id] = new InteractionTrackingData(id); + } + this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchstart', interactionEvent); + } + else if (data.pointerType === 'mouse' || data.pointerType === 'pen') { + var isRightButton = data.button === 2; + if (isRightButton) { + displayObject.trackedPointers[id].rightDown = true; + } + else { + displayObject.trackedPointers[id].leftDown = true; + } + this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); + } + } + }; + /** + * Is called when the pointer button is released on the renderer element + * @param originalEvent - The DOM event of a pointer button being released + * @param cancelled - true if the pointer is cancelled + * @param func - Function passed to {@link processInteractive} + */ + InteractionManager.prototype.onPointerComplete = function (originalEvent, cancelled, func) { + var events = this.normalizeToPointerData(originalEvent); + var eventLen = events.length; + // if the event wasn't targeting our canvas, then consider it to be pointerupoutside + // in all cases (unless it was a pointercancel) + var target = originalEvent.target; + // if in shadow DOM use composedPath to access target + if (originalEvent.composedPath && originalEvent.composedPath().length > 0) { + target = originalEvent.composedPath()[0]; + } + var eventAppend = target !== this.interactionDOMElement ? 'outside' : ''; + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = originalEvent; + // perform hit testing for events targeting our canvas or cancel events + this.processInteractive(interactionEvent, this.lastObjectRendered, func, cancelled || !eventAppend); + this.emit(cancelled ? 'pointercancel' : "pointerup" + eventAppend, interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + this.emit(isRightButton ? "rightup" + eventAppend : "mouseup" + eventAppend, interactionEvent); + } + else if (event.pointerType === 'touch') { + this.emit(cancelled ? 'touchcancel' : "touchend" + eventAppend, interactionEvent); + this.releaseInteractionDataForPointerId(event.pointerId); + } + } + }; + /** + * Is called when the pointer button is cancelled + * @param event - The DOM event of a pointer button being released + */ + InteractionManager.prototype.onPointerCancel = function (event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') + { return; } + this.onPointerComplete(event, true, this.processPointerCancel); + }; + /** + * Processes the result of the pointer cancel check and dispatches the event if need be + * @param interactionEvent - The interaction event wrapping the DOM event + * @param displayObject - The display object that was tested + */ + InteractionManager.prototype.processPointerCancel = function (interactionEvent, displayObject) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + if (displayObject.trackedPointers[id] !== undefined) { + delete displayObject.trackedPointers[id]; + this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); + } + } + }; + /** + * Is called when the pointer button is released on the renderer element + * @param event - The DOM event of a pointer button being released + */ + InteractionManager.prototype.onPointerUp = function (event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') + { return; } + this.onPointerComplete(event, false, this.processPointerUp); + }; + /** + * Processes the result of the pointer up check and dispatches the event if need be + * @param interactionEvent - The interaction event wrapping the DOM event + * @param displayObject - The display object that was tested + * @param hit - the result of the hit test on the display object + */ + InteractionManager.prototype.processPointerUp = function (interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + var trackingData = displayObject.trackedPointers[id]; + var isTouch = data.pointerType === 'touch'; + var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); + // need to track mouse down status in the mouse block so that we can emit + // event in a later block + var isMouseTap = false; + // Mouse only + if (isMouse) { + var isRightButton = data.button === 2; + var flags = InteractionTrackingData.FLAGS; + var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; + var isDown = trackingData !== undefined && (trackingData.flags & test); + if (hit) { + this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); + if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); + // because we can confirm that the mousedown happened on this object, flag for later emit of pointertap + isMouseTap = true; + } + } + else if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); + } + // update the down state of the tracking data + if (trackingData) { + if (isRightButton) { + trackingData.rightDown = false; + } + else { + trackingData.leftDown = false; + } + } + } + // Pointers and Touches, and Mouse + if (hit) { + this.dispatchEvent(displayObject, 'pointerup', interactionEvent); + if (isTouch) + { this.dispatchEvent(displayObject, 'touchend', interactionEvent); } + if (trackingData) { + // emit pointertap if not a mouse, or if the mouse block decided it was a tap + if (!isMouse || isMouseTap) { + this.dispatchEvent(displayObject, 'pointertap', interactionEvent); + } + if (isTouch) { + this.dispatchEvent(displayObject, 'tap', interactionEvent); + // touches are no longer over (if they ever were) when we get the touchend + // so we should ensure that we don't keep pretending that they are + trackingData.over = false; + } + } + } + else if (trackingData) { + this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); + if (isTouch) + { this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); } + } + // Only remove the tracking data if there is no over/down state still associated with it + if (trackingData && trackingData.none) { + delete displayObject.trackedPointers[id]; + } + }; + /** + * Is called when the pointer moves across the renderer element + * @param originalEvent - The DOM event of a pointer moving + */ + InteractionManager.prototype.onPointerMove = function (originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') + { return; } + var events = this.normalizeToPointerData(originalEvent); + if (events[0].pointerType === 'mouse' || events[0].pointerType === 'pen') { + this._didMove = true; + this.cursor = null; + } + var eventLen = events.length; + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = originalEvent; + this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerMove, true); + this.emit('pointermove', interactionEvent); + if (event.pointerType === 'touch') + { this.emit('touchmove', interactionEvent); } + if (event.pointerType === 'mouse' || event.pointerType === 'pen') + { this.emit('mousemove', interactionEvent); } + } + if (events[0].pointerType === 'mouse') { + this.setCursorMode(this.cursor); + // TODO BUG for parents interactive object (border order issue) + } + }; + /** + * Processes the result of the pointer move check and dispatches the event if need be + * @param interactionEvent - The interaction event wrapping the DOM event + * @param displayObject - The display object that was tested + * @param hit - the result of the hit test on the display object + */ + InteractionManager.prototype.processPointerMove = function (interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var isTouch = data.pointerType === 'touch'; + var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); + if (isMouse) { + this.processPointerOverOut(interactionEvent, displayObject, hit); + } + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'pointermove', interactionEvent); + if (isTouch) + { this.dispatchEvent(displayObject, 'touchmove', interactionEvent); } + if (isMouse) + { this.dispatchEvent(displayObject, 'mousemove', interactionEvent); } + } + }; + /** + * Is called when the pointer is moved out of the renderer element + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out + */ + InteractionManager.prototype.onPointerOut = function (originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') + { return; } + var events = this.normalizeToPointerData(originalEvent); + // Only mouse and pointer can call onPointerOut, so events will always be length 1 + var event = events[0]; + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = false; + this.setCursorMode(null); + } + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = event; + this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerOverOut, false); + this.emit('pointerout', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseout', interactionEvent); + } + else { + // we can get touchleave events after touchend, so we want to make sure we don't + // introduce memory leaks + this.releaseInteractionDataForPointerId(interactionData.identifier); + } + }; + /** + * Processes the result of the pointer over/out check and dispatches the event if need be. + * @param interactionEvent - The interaction event wrapping the DOM event + * @param displayObject - The display object that was tested + * @param hit - the result of the hit test on the display object + */ + InteractionManager.prototype.processPointerOverOut = function (interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); + var trackingData = displayObject.trackedPointers[id]; + // if we just moused over the display object, then we need to track that state + if (hit && !trackingData) { + trackingData = displayObject.trackedPointers[id] = new InteractionTrackingData(id); + } + if (trackingData === undefined) + { return; } + if (hit && this.mouseOverRenderer) { + if (!trackingData.over) { + trackingData.over = true; + this.delayDispatchEvent(displayObject, 'pointerover', interactionEvent); + if (isMouse) { + this.delayDispatchEvent(displayObject, 'mouseover', interactionEvent); + } + } + // only change the cursor if it has not already been changed (by something deeper in the + // display tree) + if (isMouse && this.cursor === null) { + this.cursor = displayObject.cursor; + } + } + else if (trackingData.over) { + trackingData.over = false; + this.dispatchEvent(displayObject, 'pointerout', this.eventData); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseout', interactionEvent); + } + // if there is no mouse down information for the pointer, then it is safe to delete + if (trackingData.none) { + delete displayObject.trackedPointers[id]; + } + } + }; + /** + * Is called when the pointer is moved into the renderer element. + * @param originalEvent - The DOM event of a pointer button being moved into the renderer view. + */ + InteractionManager.prototype.onPointerOver = function (originalEvent) { + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') + { return; } + var events = this.normalizeToPointerData(originalEvent); + // Only mouse and pointer can call onPointerOver, so events will always be length 1 + var event = events[0]; + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = event; + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = true; + } + this.emit('pointerover', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseover', interactionEvent); + } + }; + /** + * Get InteractionData for a given pointerId. Store that data as well. + * @param event - Normalized pointer event, output from normalizeToPointerData. + * @returns - Interaction data for the given pointer identifier. + */ + InteractionManager.prototype.getInteractionDataForPointerId = function (event) { + var pointerId = event.pointerId; + var interactionData; + if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') { + interactionData = this.mouse; + } + else if (this.activeInteractionData[pointerId]) { + interactionData = this.activeInteractionData[pointerId]; + } + else { + interactionData = this.interactionDataPool.pop() || new InteractionData(); + interactionData.identifier = pointerId; + this.activeInteractionData[pointerId] = interactionData; + } + // copy properties from the event, so that we can make sure that touch/pointer specific + // data is available + interactionData.copyEvent(event); + return interactionData; + }; + /** + * Return unused InteractionData to the pool, for a given pointerId + * @param pointerId - Identifier from a pointer event + */ + InteractionManager.prototype.releaseInteractionDataForPointerId = function (pointerId) { + var interactionData = this.activeInteractionData[pointerId]; + if (interactionData) { + delete this.activeInteractionData[pointerId]; + interactionData.reset(); + this.interactionDataPool.push(interactionData); + } + }; + /** + * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData + * @param interactionEvent - The event to be configured + * @param pointerEvent - The DOM event that will be paired with the InteractionEvent + * @param interactionData - The InteractionData that will be paired + * with the InteractionEvent + * @returns - the interaction event that was passed in + */ + InteractionManager.prototype.configureInteractionEventForDOMEvent = function (interactionEvent, pointerEvent, interactionData) { + interactionEvent.data = interactionData; + this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); + // Not really sure why this is happening, but it's how a previous version handled things + if (pointerEvent.pointerType === 'touch') { + pointerEvent.globalX = interactionData.global.x; + pointerEvent.globalY = interactionData.global.y; + } + interactionData.originalEvent = pointerEvent; + interactionEvent.reset(); + return interactionEvent; + }; + /** + * Ensures that the original event object contains all data that a regular pointer event would have + * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event + * @returns - An array containing a single normalized pointer event, in the case of a pointer + * or mouse event, or a multiple normalized pointer events if there are multiple changed touches + */ + InteractionManager.prototype.normalizeToPointerData = function (event) { + var normalizedEvents = []; + if (this.supportsTouchEvents && event instanceof TouchEvent) { + for (var i = 0, li = event.changedTouches.length; i < li; i++) { + var touch = event.changedTouches[i]; + if (typeof touch.button === 'undefined') + { touch.button = event.touches.length ? 1 : 0; } + if (typeof touch.buttons === 'undefined') + { touch.buttons = event.touches.length ? 1 : 0; } + if (typeof touch.isPrimary === 'undefined') { + touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart'; + } + if (typeof touch.width === 'undefined') + { touch.width = touch.radiusX || 1; } + if (typeof touch.height === 'undefined') + { touch.height = touch.radiusY || 1; } + if (typeof touch.tiltX === 'undefined') + { touch.tiltX = 0; } + if (typeof touch.tiltY === 'undefined') + { touch.tiltY = 0; } + if (typeof touch.pointerType === 'undefined') + { touch.pointerType = 'touch'; } + if (typeof touch.pointerId === 'undefined') + { touch.pointerId = touch.identifier || 0; } + if (typeof touch.pressure === 'undefined') + { touch.pressure = touch.force || 0.5; } + if (typeof touch.twist === 'undefined') + { touch.twist = 0; } + if (typeof touch.tangentialPressure === 'undefined') + { touch.tangentialPressure = 0; } + // TODO: Remove these, as layerX/Y is not a standard, is deprecated, has uneven + // support, and the fill ins are not quite the same + // offsetX/Y might be okay, but is not the same as clientX/Y when the canvas's top + // left is not 0,0 on the page + if (typeof touch.layerX === 'undefined') + { touch.layerX = touch.offsetX = touch.clientX; } + if (typeof touch.layerY === 'undefined') + { touch.layerY = touch.offsetY = touch.clientY; } + // mark the touch as normalized, just so that we know we did it + touch.isNormalized = true; + normalizedEvents.push(touch); + } + } + // apparently PointerEvent subclasses MouseEvent, so yay + else if (!globalThis.MouseEvent + || (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof globalThis.PointerEvent)))) { + var tempEvent = event; + if (typeof tempEvent.isPrimary === 'undefined') + { tempEvent.isPrimary = true; } + if (typeof tempEvent.width === 'undefined') + { tempEvent.width = 1; } + if (typeof tempEvent.height === 'undefined') + { tempEvent.height = 1; } + if (typeof tempEvent.tiltX === 'undefined') + { tempEvent.tiltX = 0; } + if (typeof tempEvent.tiltY === 'undefined') + { tempEvent.tiltY = 0; } + if (typeof tempEvent.pointerType === 'undefined') + { tempEvent.pointerType = 'mouse'; } + if (typeof tempEvent.pointerId === 'undefined') + { tempEvent.pointerId = MOUSE_POINTER_ID; } + if (typeof tempEvent.pressure === 'undefined') + { tempEvent.pressure = 0.5; } + if (typeof tempEvent.twist === 'undefined') + { tempEvent.twist = 0; } + if (typeof tempEvent.tangentialPressure === 'undefined') + { tempEvent.tangentialPressure = 0; } + // mark the mouse event as normalized, just so that we know we did it + tempEvent.isNormalized = true; + normalizedEvents.push(tempEvent); + } + else { + normalizedEvents.push(event); + } + return normalizedEvents; + }; + /** Destroys the interaction manager. */ + InteractionManager.prototype.destroy = function () { + this.removeEvents(); + this.removeTickerListener(); + this.removeAllListeners(); + this.renderer = null; + this.mouse = null; + this.eventData = null; + this.interactionDOMElement = null; + this.onPointerDown = null; + this.processPointerDown = null; + this.onPointerUp = null; + this.processPointerUp = null; + this.onPointerCancel = null; + this.processPointerCancel = null; + this.onPointerMove = null; + this.processPointerMove = null; + this.onPointerOut = null; + this.processPointerOverOut = null; + this.onPointerOver = null; + this.search = null; + }; + /** @ignore */ + InteractionManager.extension = { + name: 'interaction', + type: [ + exports.ExtensionType.RendererPlugin, + exports.ExtensionType.CanvasRendererPlugin ], + }; + return InteractionManager; + }(eventemitter3)); + + /*! + * @pixi/extract - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/extract is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ - if (!uploaded) { - this.queue.shift(); - } - } + var TEMP_RECT = new Rectangle(); + var BYTES_PER_PIXEL = 4; + /** + * This class provides renderer-specific plugins for exporting content from a renderer. + * For instance, these plugins can be used for saving an Image, Canvas element or for exporting the raw image data (pixels). + * + * Do not instantiate these plugins directly. It is available from the `renderer.plugins` property. + * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. + * @example + * // Create a new app (will auto-add extract plugin to renderer) + * const app = new PIXI.Application(); + * + * // Draw a red circle + * const graphics = new PIXI.Graphics() + * .beginFill(0xFF0000) + * .drawCircle(0, 0, 50); + * + * // Render the graphics as an HTMLImageElement + * const image = app.renderer.plugins.extract.image(graphics); + * document.body.appendChild(image); + * @memberof PIXI + */ + var Extract = /** @class */ (function () { + /** + * @param renderer - A reference to the current renderer + */ + function Extract(renderer) { + this.renderer = renderer; + } + /** + * Will return a HTML Image of the target + * @param target - A displayObject or renderTexture + * to convert. If left empty will use the main renderer + * @param format - Image format, e.g. "image/jpeg" or "image/webp". + * @param quality - JPEG or Webp compression from 0 to 1. Default is 0.92. + * @returns - HTML Image of the target + */ + Extract.prototype.image = function (target, format, quality) { + var image = new Image(); + image.src = this.base64(target, format, quality); + return image; + }; + /** + * Will return a base64 encoded string of this target. It works by calling + * `Extract.getCanvas` and then running toDataURL on that. + * @param target - A displayObject or renderTexture + * to convert. If left empty will use the main renderer + * @param format - Image format, e.g. "image/jpeg" or "image/webp". + * @param quality - JPEG or Webp compression from 0 to 1. Default is 0.92. + * @returns - A base64 encoded string of the texture. + */ + Extract.prototype.base64 = function (target, format, quality) { + return this.canvas(target).toDataURL(format, quality); + }; + /** + * Creates a Canvas element, renders this target to it and then returns it. + * @param target - A displayObject or renderTexture + * to convert. If left empty will use the main renderer + * @param frame - The frame the extraction is restricted to. + * @returns - A Canvas element with the texture rendered on. + */ + Extract.prototype.canvas = function (target, frame) { + var _a = this._rawPixels(target, frame), pixels = _a.pixels, width = _a.width, height = _a.height, flipY = _a.flipY; + var canvasBuffer = new CanvasRenderTarget(width, height, 1); + // Add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + Extract.arrayPostDivide(pixels, canvasData.data); + canvasBuffer.context.putImageData(canvasData, 0, 0); + // Flipping pixels + if (flipY) { + var target_1 = new CanvasRenderTarget(canvasBuffer.width, canvasBuffer.height, 1); + target_1.context.scale(1, -1); + // We can't render to itself because we should be empty before render. + target_1.context.drawImage(canvasBuffer.canvas, 0, -height); + canvasBuffer.destroy(); + canvasBuffer = target_1; + } + // Send the canvas back + return canvasBuffer.canvas; + }; + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * @param target - A displayObject or renderTexture + * to convert. If left empty will use the main renderer + * @param frame - The frame the extraction is restricted to. + * @returns - One-dimensional array containing the pixel data of the entire texture + */ + Extract.prototype.pixels = function (target, frame) { + var pixels = this._rawPixels(target, frame).pixels; + Extract.arrayPostDivide(pixels, pixels); + return pixels; + }; + Extract.prototype._rawPixels = function (target, frame) { + var renderer = this.renderer; + var resolution; + var flipY = false; + var renderTexture; + var generated = false; + if (target) { + if (target instanceof RenderTexture) { + renderTexture = target; + } + else { + var multisample = renderer.context.webGLVersion >= 2 ? renderer.multisample : exports.MSAA_QUALITY.NONE; + renderTexture = this.renderer.generateTexture(target, { multisample: multisample }); + if (multisample !== exports.MSAA_QUALITY.NONE) { + // Resolve the multisampled texture to a non-multisampled texture + var resolvedTexture = RenderTexture.create({ + width: renderTexture.width, + height: renderTexture.height, + }); + renderer.framebuffer.bind(renderTexture.framebuffer); + renderer.framebuffer.blit(resolvedTexture.framebuffer); + renderer.framebuffer.bind(null); + renderTexture.destroy(true); + renderTexture = resolvedTexture; + } + generated = true; + } + } + if (renderTexture) { + resolution = renderTexture.baseTexture.resolution; + frame = frame !== null && frame !== void 0 ? frame : renderTexture.frame; + flipY = false; + renderer.renderTexture.bind(renderTexture); + } + else { + resolution = renderer.resolution; + if (!frame) { + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + } + flipY = true; + renderer.renderTexture.bind(null); + } + var width = Math.round(frame.width * resolution); + var height = Math.round(frame.height * resolution); + var pixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + // Read pixels to the array + var gl = renderer.gl; + gl.readPixels(Math.round(frame.x * resolution), Math.round(frame.y * resolution), width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels); + if (generated) { + renderTexture.destroy(true); + } + return { pixels: pixels, width: width, height: height, flipY: flipY }; + }; + /** Destroys the extract. */ + Extract.prototype.destroy = function () { + this.renderer = null; + }; + /** + * Takes premultiplied pixel data and produces regular pixel data + * @private + * @param pixels - array of pixel data + * @param out - output array + */ + Extract.arrayPostDivide = function (pixels, out) { + for (var i = 0; i < pixels.length; i += 4) { + var alpha = out[i + 3] = pixels[i + 3]; + if (alpha !== 0) { + out[i] = Math.round(Math.min(pixels[i] * 255.0 / alpha, 255.0)); + out[i + 1] = Math.round(Math.min(pixels[i + 1] * 255.0 / alpha, 255.0)); + out[i + 2] = Math.round(Math.min(pixels[i + 2] * 255.0 / alpha, 255.0)); + } + else { + out[i] = pixels[i]; + out[i + 1] = pixels[i + 1]; + out[i + 2] = pixels[i + 2]; + } + } + }; + /** @ignore */ + Extract.extension = { + name: 'extract', + type: exports.ExtensionType.RendererPlugin, + }; + return Extract; + }()); + + /*! + * @pixi/loaders - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/loaders is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ - // We're finished - if (!this.queue.length) { - this.ticking = false; + /* jshint -W097 */ + /** + * @memberof PIXI + */ + var SignalBinding = /** @class */ (function () { + /** + * SignalBinding constructor. + * @constructs SignalBinding + * @param {Function} fn - Event handler to be called. + * @param {boolean} [once=false] - Should this listener be removed after dispatch + * @param {object} [thisArg] - The context of the callback function. + * @api private + */ + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + function SignalBinding(fn, once, thisArg) { + if (once === void 0) { once = false; } + this._fn = fn; + this._once = once; + this._thisArg = thisArg; + this._next = this._prev = this._owner = null; + } + SignalBinding.prototype.detach = function () { + if (this._owner === null) + { return false; } + this._owner.detach(this); + return true; + }; + return SignalBinding; + }()); + /** + * @param self + * @param node + * @private + */ + function _addSignalBinding(self, node) { + if (!self._head) { + self._head = node; + self._tail = node; + } + else { + self._tail._next = node; + node._prev = self._tail; + self._tail = node; + } + node._owner = self; + return node; + } + /** + * @memberof PIXI + */ + var Signal = /** @class */ (function () { + /** + * MiniSignal constructor. + * @example + * let mySignal = new Signal(); + * let binding = mySignal.add(onSignal); + * mySignal.dispatch('foo', 'bar'); + * mySignal.detach(binding); + */ + function Signal() { + this._head = this._tail = undefined; + } + /** + * Return an array of attached SignalBinding. + * @param {boolean} [exists=false] - We only need to know if there are handlers. + * @returns {PIXI.SignalBinding[] | boolean} Array of attached SignalBinding or Boolean if called with exists = true + * @api public + */ + Signal.prototype.handlers = function (exists) { + if (exists === void 0) { exists = false; } + var node = this._head; + if (exists) + { return !!node; } + var ee = []; + while (node) { + ee.push(node); + node = node._next; + } + return ee; + }; + /** + * Return true if node is a SignalBinding attached to this MiniSignal + * @param {PIXI.SignalBinding} node - Node to check. + * @returns {boolean} True if node is attache to mini-signal + */ + Signal.prototype.has = function (node) { + if (!(node instanceof SignalBinding)) { + throw new Error('MiniSignal#has(): First arg must be a SignalBinding object.'); + } + return node._owner === this; + }; + /** + * Dispaches a signal to all registered listeners. + * @param {...any} args + * @returns {boolean} Indication if we've emitted an event. + */ + Signal.prototype.dispatch = function () { + var arguments$1 = arguments; - var completes = this.completes.slice(0); + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments$1[_i]; + } + var node = this._head; + if (!node) + { return false; } + while (node) { + if (node._once) + { this.detach(node); } + node._fn.apply(node._thisArg, args); + node = node._next; + } + return true; + }; + /** + * Register a new listener. + * @param {Function} fn - Callback function. + * @param {object} [thisArg] - The context of the callback function. + * @returns {PIXI.SignalBinding} The SignalBinding node that was added. + */ + Signal.prototype.add = function (fn, thisArg) { + if (thisArg === void 0) { thisArg = null; } + if (typeof fn !== 'function') { + throw new Error('MiniSignal#add(): First arg must be a Function.'); + } + return _addSignalBinding(this, new SignalBinding(fn, false, thisArg)); + }; + /** + * Register a new listener that will be executed only once. + * @param {Function} fn - Callback function. + * @param {object} [thisArg] - The context of the callback function. + * @returns {PIXI.SignalBinding} The SignalBinding node that was added. + */ + Signal.prototype.once = function (fn, thisArg) { + if (thisArg === void 0) { thisArg = null; } + if (typeof fn !== 'function') { + throw new Error('MiniSignal#once(): First arg must be a Function.'); + } + return _addSignalBinding(this, new SignalBinding(fn, true, thisArg)); + }; + /** + * Remove binding object. + * @param {PIXI.SignalBinding} node - The binding node that will be removed. + * @returns {Signal} The instance on which this method was called. + @api public */ + Signal.prototype.detach = function (node) { + if (!(node instanceof SignalBinding)) { + throw new Error('MiniSignal#detach(): First arg must be a SignalBinding object.'); + } + if (node._owner !== this) + { return this; } // todo: or error? + if (node._prev) + { node._prev._next = node._next; } + if (node._next) + { node._next._prev = node._prev; } + if (node === this._head) { // first node + this._head = node._next; + if (node._next === null) { + this._tail = null; + } + } + else if (node === this._tail) { // last node + this._tail = node._prev; + this._tail._next = null; + } + node._owner = null; + return this; + }; + /** + * Detach all listeners. + * @returns {Signal} The instance on which this method was called. + */ + Signal.prototype.detachAll = function () { + var node = this._head; + if (!node) + { return this; } + this._head = this._tail = null; + while (node) { + node._owner = null; + node = node._next; + } + return this; + }; + return Signal; + }()); - this.completes.length = 0; + /** + * function from npm package `parseUri`, converted to TS to avoid leftpad incident + * @param {string} str + * @param [opts] - options + * @param {boolean} [opts.strictMode] - type of parser + */ + function parseUri(str, opts) { + opts = opts || {}; + var o = { + // eslint-disable-next-line max-len + key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], + q: { + name: 'queryKey', + parser: /(?:^|&)([^&=]*)=?([^&]*)/g + }, + parser: { + // eslint-disable-next-line max-len + strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, + // eslint-disable-next-line max-len + loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ + } + }; + var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str); + var uri = {}; + var i = 14; + while (i--) + { uri[o.key[i]] = m[i] || ''; } + uri[o.q.name] = {}; + uri[o.key[12]].replace(o.q.parser, function (_t0, t1, t2) { + if (t1) + { uri[o.q.name][t1] = t2; } + }); + return uri; + } - for (var _i = 0, _len = completes.length; _i < _len; _i++) { - completes[_i](); - } - } else { - // if we are not finished, on the next rAF do this again - SharedTicker.addOnce(this.tick, this, core.UPDATE_PRIORITY.UTILITY); - } - }; + // tests if CORS is supported in XHR, if not we need to use XDR + var useXdr; + var tempAnchor = null; + // some status constants + var STATUS_NONE = 0; + var STATUS_OK = 200; + var STATUS_EMPTY = 204; + var STATUS_IE_BUG_EMPTY = 1223; + var STATUS_TYPE_OK = 2; + // noop + function _noop$1() { } + /** + * Quick helper to set a value on one of the extension maps. Ensures there is no + * dot at the start of the extension. + * @ignore + * @param map - The map to set on. + * @param extname - The extension (or key) to set. + * @param val - The value to set. + */ + function setExtMap(map, extname, val) { + if (extname && extname.indexOf('.') === 0) { + extname = extname.substring(1); + } + if (!extname) { + return; + } + map[extname] = val; + } + /** + * Quick helper to get string xhr type. + * @ignore + * @param xhr - The request to check. + * @returns The type. + */ + function reqType(xhr) { + return xhr.toString().replace('object ', ''); + } + /** + * Manages the state and loading of a resource and all child resources. + * + * Can be extended in `GlobalMixins.LoaderResource`. + * @memberof PIXI + */ + exports.LoaderResource = /** @class */ (function () { + /** + * @param {string} name - The name of the resource to load. + * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass + * an array of sources. + * @param {object} [options] - The options for the load. + * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to + * determine automatically. + * @param {number} [options.timeout=0] - A timeout in milliseconds for the load. If the load takes + * longer than this time it is cancelled and the load is considered a failure. If this value is + * set to `0` then there is no explicit timeout. + * @param {PIXI.LoaderResource.LOAD_TYPE} [options.loadType=LOAD_TYPE.XHR] - How should this resource + * be loaded? + * @param {PIXI.LoaderResource.XHR_RESPONSE_TYPE} [options.xhrType=XHR_RESPONSE_TYPE.DEFAULT] - How + * should the data being loaded be interpreted when using XHR? + * @param {PIXI.LoaderResource.IMetadata} [options.metadata] - Extra configuration for middleware + * and the Resource object. + */ + function LoaderResource(name, url, options) { + /** + * The `dequeue` method that will be used a storage place for the async queue dequeue method + * used privately by the loader. + * @private + * @member {Function} + */ + this._dequeue = _noop$1; + /** + * Used a storage place for the on load binding used privately by the loader. + * @private + * @member {Function} + */ + this._onLoadBinding = null; + /** + * The timer for element loads to check if they timeout. + * @private + */ + this._elementTimer = 0; + /** + * The `complete` function bound to this resource's context. + * @private + * @type {Function} + */ + this._boundComplete = null; + /** + * The `_onError` function bound to this resource's context. + * @private + * @type {Function} + */ + this._boundOnError = null; + /** + * The `_onProgress` function bound to this resource's context. + * @private + * @type {Function} + */ + this._boundOnProgress = null; + /** + * The `_onTimeout` function bound to this resource's context. + * @private + * @type {Function} + */ + this._boundOnTimeout = null; + this._boundXhrOnError = null; + this._boundXhrOnTimeout = null; + this._boundXhrOnAbort = null; + this._boundXhrOnLoad = null; + if (typeof name !== 'string' || typeof url !== 'string') { + throw new Error('Both name and url are required for constructing a resource.'); + } + options = options || {}; + this._flags = 0; + // set data url flag, needs to be set early for some _determineX checks to work. + this._setFlag(LoaderResource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0); + this.name = name; + this.url = url; + this.extension = this._getExtension(); + this.data = null; + this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + this.timeout = options.timeout || 0; + this.loadType = options.loadType || this._determineLoadType(); + // The type used to load the resource via XHR. If unset, determined automatically. + this.xhrType = options.xhrType; + // Extra info for middleware, and controlling specifics about how the resource loads. + // Note that if you pass in a `loadElement`, the Resource class takes ownership of it. + // Meaning it will modify it as it sees fit. + this.metadata = options.metadata || {}; + // The error that occurred while loading (if any). + this.error = null; + // The XHR object that was used to load this resource. This is only set + // when `loadType` is `LoaderResource.LOAD_TYPE.XHR`. + this.xhr = null; + // The child resources this resource owns. + this.children = []; + // The resource type. + this.type = LoaderResource.TYPE.UNKNOWN; + // The progress chunk owned by this resource. + this.progressChunk = 0; + // The `dequeue` method that will be used a storage place for the async queue dequeue method + // used privately by the loader. + this._dequeue = _noop$1; + // Used a storage place for the on load binding used privately by the loader. + this._onLoadBinding = null; + // The timer for element loads to check if they timeout. + this._elementTimer = 0; + this._boundComplete = this.complete.bind(this); + this._boundOnError = this._onError.bind(this); + this._boundOnProgress = this._onProgress.bind(this); + this._boundOnTimeout = this._onTimeout.bind(this); + // xhr callbacks + this._boundXhrOnError = this._xhrOnError.bind(this); + this._boundXhrOnTimeout = this._xhrOnTimeout.bind(this); + this._boundXhrOnAbort = this._xhrOnAbort.bind(this); + this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + // Dispatched when the resource beings to load. + this.onStart = new Signal(); + // Dispatched each time progress of this resource load updates. + // Not all resources types and loader systems can support this event + // so sometimes it may not be available. If the resource + // is being loaded on a modern browser, using XHR, and the remote server + // properly sets Content-Length headers, then this will be available. + this.onProgress = new Signal(); + // Dispatched once this resource has loaded, if there was an error it will + // be in the `error` property. + this.onComplete = new Signal(); + // Dispatched after this resource has had all the *after* middleware run on it. + this.onAfterMiddleware = new Signal(); + } + /** + * Sets the load type to be used for a specific extension. + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {PIXI.LoaderResource.LOAD_TYPE} loadType - The load type to set it to. + */ + LoaderResource.setExtensionLoadType = function (extname, loadType) { + setExtMap(LoaderResource._loadTypeMap, extname, loadType); + }; + /** + * Sets the load type to be used for a specific extension. + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {PIXI.LoaderResource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. + */ + LoaderResource.setExtensionXhrType = function (extname, xhrType) { + setExtMap(LoaderResource._xhrTypeMap, extname, xhrType); + }; + Object.defineProperty(LoaderResource.prototype, "isDataUrl", { + /** + * When the resource starts to load. + * @memberof PIXI.LoaderResource + * @callback OnStartSignal + * @param {PIXI.Resource} resource - The resource that the event happened on. + */ + /** + * When the resource reports loading progress. + * @memberof PIXI.LoaderResource + * @callback OnProgressSignal + * @param {PIXI.Resource} resource - The resource that the event happened on. + * @param {number} percentage - The progress of the load in the range [0, 1]. + */ + /** + * When the resource finishes loading. + * @memberof PIXI.LoaderResource + * @callback OnCompleteSignal + * @param {PIXI.Resource} resource - The resource that the event happened on. + */ + /** + * @memberof PIXI.LoaderResource + * @typedef {object} IMetadata + * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The + * element to use for loading, instead of creating one. + * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @property {string|string[]} [mimeType] - The mime type to use for the source element + * of a video/audio elment. If the urls are an array, you can pass this as an array as well + * where each index is the mime type to use for the corresponding url index. + */ + /** + * Stores whether or not this url is a data url. + * @readonly + * @member {boolean} + */ + get: function () { + return this._hasFlag(LoaderResource.STATUS_FLAGS.DATA_URL); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(LoaderResource.prototype, "isComplete", { + /** + * Describes if this resource has finished loading. Is true when the resource has completely + * loaded. + * @readonly + * @member {boolean} + */ + get: function () { + return this._hasFlag(LoaderResource.STATUS_FLAGS.COMPLETE); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(LoaderResource.prototype, "isLoading", { + /** + * Describes if this resource is currently loading. Is true when the resource starts loading, + * and is false again when complete. + * @readonly + * @member {boolean} + */ + get: function () { + return this._hasFlag(LoaderResource.STATUS_FLAGS.LOADING); + }, + enumerable: false, + configurable: true + }); + /** Marks the resource as complete. */ + LoaderResource.prototype.complete = function () { + this._clearEvents(); + this._finish(); + }; + /** + * Aborts the loading of this resource, with an optional message. + * @param {string} message - The message to use for the error + */ + LoaderResource.prototype.abort = function (message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } + // store error + this.error = new Error(message); + // clear events before calling aborts + this._clearEvents(); + // abort the actual loading + if (this.xhr) { + this.xhr.abort(); + } + else if (this.xdr) { + this.xdr.abort(); + } + else if (this.data) { + // single source + if (this.data.src) { + this.data.src = LoaderResource.EMPTY_GIF; + } + // multi-source + else { + while (this.data.firstChild) { + this.data.removeChild(this.data.firstChild); + } + } + } + // done now. + this._finish(); + }; + /** + * Kicks off loading of this resource. This method is asynchronous. + * @param {PIXI.LoaderResource.OnCompleteSignal} [cb] - Optional callback to call once the resource is loaded. + */ + LoaderResource.prototype.load = function (cb) { + var _this = this; + if (this.isLoading) { + return; + } + if (this.isComplete) { + if (cb) { + setTimeout(function () { return cb(_this); }, 1); + } + return; + } + else if (cb) { + this.onComplete.once(cb); + } + this._setFlag(LoaderResource.STATUS_FLAGS.LOADING, true); + this.onStart.dispatch(this); + // if unset, determine the value + if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { + this.crossOrigin = this._determineCrossOrigin(this.url); + } + switch (this.loadType) { + case LoaderResource.LOAD_TYPE.IMAGE: + this.type = LoaderResource.TYPE.IMAGE; + this._loadElement('image'); + break; + case LoaderResource.LOAD_TYPE.AUDIO: + this.type = LoaderResource.TYPE.AUDIO; + this._loadSourceElement('audio'); + break; + case LoaderResource.LOAD_TYPE.VIDEO: + this.type = LoaderResource.TYPE.VIDEO; + this._loadSourceElement('video'); + break; + case LoaderResource.LOAD_TYPE.XHR: + /* falls through */ + default: + if (typeof useXdr === 'undefined') { + useXdr = !!(globalThis.XDomainRequest && !('withCredentials' in (new XMLHttpRequest()))); + } + if (useXdr && this.crossOrigin) { + this._loadXdr(); + } + else { + this._loadXhr(); + } + break; + } + }; + /** + * Checks if the flag is set. + * @param flag - The flag to check. + * @returns True if the flag is set. + */ + LoaderResource.prototype._hasFlag = function (flag) { + return (this._flags & flag) !== 0; + }; + /** + * (Un)Sets the flag. + * @param flag - The flag to (un)set. + * @param value - Whether to set or (un)set the flag. + */ + LoaderResource.prototype._setFlag = function (flag, value) { + this._flags = value ? (this._flags | flag) : (this._flags & ~flag); + }; + /** Clears all the events from the underlying loading source. */ + LoaderResource.prototype._clearEvents = function () { + clearTimeout(this._elementTimer); + if (this.data && this.data.removeEventListener) { + this.data.removeEventListener('error', this._boundOnError, false); + this.data.removeEventListener('load', this._boundComplete, false); + this.data.removeEventListener('progress', this._boundOnProgress, false); + this.data.removeEventListener('canplaythrough', this._boundComplete, false); + } + if (this.xhr) { + if (this.xhr.removeEventListener) { + this.xhr.removeEventListener('error', this._boundXhrOnError, false); + this.xhr.removeEventListener('timeout', this._boundXhrOnTimeout, false); + this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); + this.xhr.removeEventListener('progress', this._boundOnProgress, false); + this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); + } + else { + this.xhr.onerror = null; + this.xhr.ontimeout = null; + this.xhr.onprogress = null; + this.xhr.onload = null; + } + } + }; + /** Finalizes the load. */ + LoaderResource.prototype._finish = function () { + if (this.isComplete) { + throw new Error('Complete called again for an already completed resource.'); + } + this._setFlag(LoaderResource.STATUS_FLAGS.COMPLETE, true); + this._setFlag(LoaderResource.STATUS_FLAGS.LOADING, false); + this.onComplete.dispatch(this); + }; + /** + * Loads this resources using an element that has a single source, + * like an HTMLImageElement. + * @private + * @param type - The type of element to use. + */ + LoaderResource.prototype._loadElement = function (type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } + else if (type === 'image' && typeof globalThis.Image !== 'undefined') { + this.data = new Image(); + } + else { + this.data = document.createElement(type); + } + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + if (!this.metadata.skipSource) { + this.data.src = this.url; + } + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + if (this.timeout) { + this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout); + } + }; + /** + * Loads this resources using an element that has multiple sources, + * like an HTMLAudioElement or HTMLVideoElement. + * @param type - The type of element to use. + */ + LoaderResource.prototype._loadSourceElement = function (type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } + else if (type === 'audio' && typeof globalThis.Audio !== 'undefined') { + this.data = new Audio(); + } + else { + this.data = document.createElement(type); + } + if (this.data === null) { + this.abort("Unsupported element: " + type); + return; + } + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + if (!this.metadata.skipSource) { + // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') + if (navigator.isCocoonJS) { + this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; + } + else if (Array.isArray(this.url)) { + var mimeTypes = this.metadata.mimeType; + for (var i = 0; i < this.url.length; ++i) { + this.data.appendChild(this._createSource(type, this.url[i], Array.isArray(mimeTypes) ? mimeTypes[i] : mimeTypes)); + } + } + else { + var mimeTypes = this.metadata.mimeType; + this.data.appendChild(this._createSource(type, this.url, Array.isArray(mimeTypes) ? mimeTypes[0] : mimeTypes)); + } + } + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + this.data.addEventListener('canplaythrough', this._boundComplete, false); + this.data.load(); + if (this.timeout) { + this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout); + } + }; + /** Loads this resources using an XMLHttpRequest. */ + LoaderResource.prototype._loadXhr = function () { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + var xhr = this.xhr = new XMLHttpRequest(); + // send credentials when crossOrigin with credentials requested + if (this.crossOrigin === 'use-credentials') { + xhr.withCredentials = true; + } + // set the request type and url + xhr.open('GET', this.url, true); + xhr.timeout = this.timeout; + // load json as text and parse it ourselves. We do this because some browsers + // *cough* safari *cough* can't deal with it. + if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.JSON + || this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT) { + xhr.responseType = LoaderResource.XHR_RESPONSE_TYPE.TEXT; + } + else { + xhr.responseType = this.xhrType; + } + xhr.addEventListener('error', this._boundXhrOnError, false); + xhr.addEventListener('timeout', this._boundXhrOnTimeout, false); + xhr.addEventListener('abort', this._boundXhrOnAbort, false); + xhr.addEventListener('progress', this._boundOnProgress, false); + xhr.addEventListener('load', this._boundXhrOnLoad, false); + xhr.send(); + }; + /** Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). */ + LoaderResource.prototype._loadXdr = function () { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + var xdr = this.xhr = new globalThis.XDomainRequest(); // eslint-disable-line no-undef + // XDomainRequest has a few quirks. Occasionally it will abort requests + // A way to avoid this is to make sure ALL callbacks are set even if not used + // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 + xdr.timeout = this.timeout || 5000; // XDR needs a timeout value or it breaks in IE9 + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXhrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; + xdr.open('GET', this.url, true); + // Note: The xdr.send() call is wrapped in a timeout to prevent an + // issue with the interface where some requests are lost if multiple + // XDomainRequests are being sent at the same time. + // Some info here: https://github.com/photonstorm/phaser/issues/1248 + setTimeout(function () { return xdr.send(); }, 1); + }; + /** + * Creates a source used in loading via an element. + * @param type - The element type (video or audio). + * @param url - The source URL to load from. + * @param [mime] - The mime type of the video + * @returns The source element. + */ + LoaderResource.prototype._createSource = function (type, url, mime) { + if (!mime) { + mime = type + "/" + this._getExtension(url); + } + var source = document.createElement('source'); + source.src = url; + source.type = mime; + return source; + }; + /** + * Called if a load errors out. + * @param event - The error event from the element that emits it. + */ + LoaderResource.prototype._onError = function (event) { + this.abort("Failed to load element using: " + event.target.nodeName); + }; + /** + * Called if a load progress event fires for an element or xhr/xdr. + * @param event - Progress event. + */ + LoaderResource.prototype._onProgress = function (event) { + if (event && event.lengthComputable) { + this.onProgress.dispatch(this, event.loaded / event.total); + } + }; + /** Called if a timeout event fires for an element. */ + LoaderResource.prototype._onTimeout = function () { + this.abort("Load timed out."); + }; + /** Called if an error event fires for xhr/xdr. */ + LoaderResource.prototype._xhrOnError = function () { + var xhr = this.xhr; + this.abort(reqType(xhr) + " Request failed. Status: " + xhr.status + ", text: \"" + xhr.statusText + "\""); + }; + /** Called if an error event fires for xhr/xdr. */ + LoaderResource.prototype._xhrOnTimeout = function () { + var xhr = this.xhr; + this.abort(reqType(xhr) + " Request timed out."); + }; + /** Called if an abort event fires for xhr/xdr. */ + LoaderResource.prototype._xhrOnAbort = function () { + var xhr = this.xhr; + this.abort(reqType(xhr) + " Request was aborted by the user."); + }; + /** Called when data successfully loads from an xhr/xdr request. */ + LoaderResource.prototype._xhrOnLoad = function () { + var xhr = this.xhr; + var text = ''; + var status = typeof xhr.status === 'undefined' ? STATUS_OK : xhr.status; // XDR has no `.status`, assume 200. + // responseText is accessible only if responseType is '' or 'text' and on older browsers + if (xhr.responseType === '' || xhr.responseType === 'text' || typeof xhr.responseType === 'undefined') { + text = xhr.responseText; + } + // status can be 0 when using the `file://` protocol so we also check if a response is set. + // If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request. + if (status === STATUS_NONE && (text.length > 0 || xhr.responseType === LoaderResource.XHR_RESPONSE_TYPE.BUFFER)) { + status = STATUS_OK; + } + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + else if (status === STATUS_IE_BUG_EMPTY) { + status = STATUS_EMPTY; + } + var statusType = (status / 100) | 0; + if (statusType === STATUS_TYPE_OK) { + // if text, just return it + if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.TEXT) { + this.data = text; + this.type = LoaderResource.TYPE.TEXT; + } + // if json, parse into json object + else if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.JSON) { + try { + this.data = JSON.parse(text); + this.type = LoaderResource.TYPE.JSON; + } + catch (e) { + this.abort("Error trying to parse loaded json: " + e); + return; + } + } + // if xml, parse into an xml document or div element + else if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT) { + try { + if (globalThis.DOMParser) { + var domparser = new DOMParser(); + this.data = domparser.parseFromString(text, 'text/xml'); + } + else { + var div = document.createElement('div'); + div.innerHTML = text; + this.data = div; + } + this.type = LoaderResource.TYPE.XML; + } + catch (e$1) { + this.abort("Error trying to parse loaded xml: " + e$1); + return; + } + } + // other types just return the response + else { + this.data = xhr.response || text; + } + } + else { + this.abort("[" + xhr.status + "] " + xhr.statusText + ": " + xhr.responseURL); + return; + } + this.complete(); + }; + /** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * @private + * @param url - The url to test. + * @param [loc=globalThis.location] - The location object to test against. + * @returns The crossOrigin value to use (or empty string for none). + */ + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + LoaderResource.prototype._determineCrossOrigin = function (url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + // A sandboxed iframe without the 'allow-same-origin' attribute will have a special + // origin designed not to match globalThis.location.origin, and will always require + // crossOrigin requests regardless of whether the location matches. + if (globalThis.origin !== globalThis.location.origin) { + return 'anonymous'; + } + // default is globalThis.location + loc = loc || globalThis.location; + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + var parsedUrl = parseUri(tempAnchor.href, { strictMode: true }); + var samePort = (!parsedUrl.port && loc.port === '') || (parsedUrl.port === loc.port); + var protocol = parsedUrl.protocol ? parsedUrl.protocol + ":" : ''; + // if cross origin + if (parsedUrl.host !== loc.hostname || !samePort || protocol !== loc.protocol) { + return 'anonymous'; + } + return ''; + }; + /** + * Determines the responseType of an XHR request based on the extension of the + * resource being loaded. + * @private + * @returns {PIXI.LoaderResource.XHR_RESPONSE_TYPE} The responseType to use. + */ + LoaderResource.prototype._determineXhrType = function () { + return LoaderResource._xhrTypeMap[this.extension] || LoaderResource.XHR_RESPONSE_TYPE.TEXT; + }; + /** + * Determines the loadType of a resource based on the extension of the + * resource being loaded. + * @private + * @returns {PIXI.LoaderResource.LOAD_TYPE} The loadType to use. + */ + LoaderResource.prototype._determineLoadType = function () { + return LoaderResource._loadTypeMap[this.extension] || LoaderResource.LOAD_TYPE.XHR; + }; + /** + * Extracts the extension (sans '.') of the file being loaded by the resource. + * @param [url] - url to parse, `this.url` by default. + * @returns The extension. + */ + LoaderResource.prototype._getExtension = function (url) { + if (url === void 0) { url = this.url; } + var ext = ''; + if (this.isDataUrl) { + var slashIndex = url.indexOf('/'); + ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); + } + else { + var queryStart = url.indexOf('?'); + var hashStart = url.indexOf('#'); + var index = Math.min(queryStart > -1 ? queryStart : url.length, hashStart > -1 ? hashStart : url.length); + url = url.substring(0, index); + ext = url.substring(url.lastIndexOf('.') + 1); + } + return ext.toLowerCase(); + }; + /** + * Determines the mime type of an XHR request based on the responseType of + * resource being loaded. + * @param type - The type to get a mime type for. + * @private + * @returns The mime type to use. + */ + LoaderResource.prototype._getMimeFromXhrType = function (type) { + switch (type) { + case LoaderResource.XHR_RESPONSE_TYPE.BUFFER: + return 'application/octet-binary'; + case LoaderResource.XHR_RESPONSE_TYPE.BLOB: + return 'application/blob'; + case LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT: + return 'application/xml'; + case LoaderResource.XHR_RESPONSE_TYPE.JSON: + return 'application/json'; + case LoaderResource.XHR_RESPONSE_TYPE.DEFAULT: + case LoaderResource.XHR_RESPONSE_TYPE.TEXT: + /* falls through */ + default: + return 'text/plain'; + } + }; + return LoaderResource; + }()); + // eslint-disable-next-line @typescript-eslint/no-namespace + (function (LoaderResource) { + (function (STATUS_FLAGS) { + /** None */ + STATUS_FLAGS[STATUS_FLAGS["NONE"] = 0] = "NONE"; + /** Data URL */ + STATUS_FLAGS[STATUS_FLAGS["DATA_URL"] = 1] = "DATA_URL"; + /** Complete */ + STATUS_FLAGS[STATUS_FLAGS["COMPLETE"] = 2] = "COMPLETE"; + /** Loading */ + STATUS_FLAGS[STATUS_FLAGS["LOADING"] = 4] = "LOADING"; + })(LoaderResource.STATUS_FLAGS || (LoaderResource.STATUS_FLAGS = {})); + (function (TYPE) { + /** Unknown */ + TYPE[TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + /** JSON */ + TYPE[TYPE["JSON"] = 1] = "JSON"; + /** XML */ + TYPE[TYPE["XML"] = 2] = "XML"; + /** Image */ + TYPE[TYPE["IMAGE"] = 3] = "IMAGE"; + /** Audio */ + TYPE[TYPE["AUDIO"] = 4] = "AUDIO"; + /** Video */ + TYPE[TYPE["VIDEO"] = 5] = "VIDEO"; + /** Plain text */ + TYPE[TYPE["TEXT"] = 6] = "TEXT"; + })(LoaderResource.TYPE || (LoaderResource.TYPE = {})); + (function (LOAD_TYPE) { + /** Uses XMLHttpRequest to load the resource. */ + LOAD_TYPE[LOAD_TYPE["XHR"] = 1] = "XHR"; + /** Uses an `Image` object to load the resource. */ + LOAD_TYPE[LOAD_TYPE["IMAGE"] = 2] = "IMAGE"; + /** Uses an `Audio` object to load the resource. */ + LOAD_TYPE[LOAD_TYPE["AUDIO"] = 3] = "AUDIO"; + /** Uses a `Video` object to load the resource. */ + LOAD_TYPE[LOAD_TYPE["VIDEO"] = 4] = "VIDEO"; + })(LoaderResource.LOAD_TYPE || (LoaderResource.LOAD_TYPE = {})); + (function (XHR_RESPONSE_TYPE) { + /** string */ + XHR_RESPONSE_TYPE["DEFAULT"] = "text"; + /** ArrayBuffer */ + XHR_RESPONSE_TYPE["BUFFER"] = "arraybuffer"; + /** Blob */ + XHR_RESPONSE_TYPE["BLOB"] = "blob"; + /** Document */ + XHR_RESPONSE_TYPE["DOCUMENT"] = "document"; + /** Object */ + XHR_RESPONSE_TYPE["JSON"] = "json"; + /** String */ + XHR_RESPONSE_TYPE["TEXT"] = "text"; + })(LoaderResource.XHR_RESPONSE_TYPE || (LoaderResource.XHR_RESPONSE_TYPE = {})); + LoaderResource._loadTypeMap = { + // images + gif: LoaderResource.LOAD_TYPE.IMAGE, + png: LoaderResource.LOAD_TYPE.IMAGE, + bmp: LoaderResource.LOAD_TYPE.IMAGE, + jpg: LoaderResource.LOAD_TYPE.IMAGE, + jpeg: LoaderResource.LOAD_TYPE.IMAGE, + tif: LoaderResource.LOAD_TYPE.IMAGE, + tiff: LoaderResource.LOAD_TYPE.IMAGE, + webp: LoaderResource.LOAD_TYPE.IMAGE, + tga: LoaderResource.LOAD_TYPE.IMAGE, + avif: LoaderResource.LOAD_TYPE.IMAGE, + svg: LoaderResource.LOAD_TYPE.IMAGE, + 'svg+xml': LoaderResource.LOAD_TYPE.IMAGE, + // audio + mp3: LoaderResource.LOAD_TYPE.AUDIO, + ogg: LoaderResource.LOAD_TYPE.AUDIO, + wav: LoaderResource.LOAD_TYPE.AUDIO, + // videos + mp4: LoaderResource.LOAD_TYPE.VIDEO, + webm: LoaderResource.LOAD_TYPE.VIDEO, + }; + LoaderResource._xhrTypeMap = { + // xml + xhtml: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + html: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + htm: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + xml: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + tmx: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + svg: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. + // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, + // this should probably be fine. + tsx: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + // images + gif: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + png: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + bmp: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + jpg: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + jpeg: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + tif: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + tiff: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + webp: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + tga: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + avif: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + // json + json: LoaderResource.XHR_RESPONSE_TYPE.JSON, + // text + text: LoaderResource.XHR_RESPONSE_TYPE.TEXT, + txt: LoaderResource.XHR_RESPONSE_TYPE.TEXT, + // fonts + ttf: LoaderResource.XHR_RESPONSE_TYPE.BUFFER, + otf: LoaderResource.XHR_RESPONSE_TYPE.BUFFER, + }; + // We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif + LoaderResource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; + })(exports.LoaderResource || (exports.LoaderResource = {})); - /** - * Adds hooks for finding items. - * - * @param {Function} addHook - Function call that takes two parameters: `item:*, queue:Array` - * function must return `true` if it was able to add item to the queue. - * @return {PIXI.BasePrepare} Instance of plugin for chaining. - */ + /** + * Smaller version of the async library constructs. + * @ignore + */ + function _noop() { + } + /** + * Ensures a function is only called once. + * @ignore + * @param {Function} fn - The function to wrap. + * @returns {Function} The wrapping function. + */ + function onlyOnce(fn) { + return function onceWrapper() { + var arguments$1 = arguments; + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments$1[_i]; + } + if (fn === null) { + throw new Error('Callback was already called.'); + } + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; + } + /** + * @private + * @memberof PIXI + */ + var AsyncQueueItem = /** @class */ (function () { + /** + * @param data + * @param callback + * @private + */ + function AsyncQueueItem(data, callback) { + this.data = data; + this.callback = callback; + } + return AsyncQueueItem; + }()); + /** + * @private + * @memberof PIXI + */ + var AsyncQueue = /** @class */ (function () { + /** + * @param worker + * @param concurrency + * @private + */ + function AsyncQueue(worker, concurrency) { + var _this = this; + if (concurrency === void 0) { concurrency = 1; } + this.workers = 0; + this.saturated = _noop; + this.unsaturated = _noop; + this.empty = _noop; + this.drain = _noop; + this.error = _noop; + this.started = false; + this.paused = false; + this._tasks = []; + this._insert = function (data, insertAtFront, callback) { + if (callback && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + _this.started = true; + // eslint-disable-next-line no-eq-null,eqeqeq + if (data == null && _this.idle()) { + // call drain immediately if there are no tasks + setTimeout(function () { return _this.drain(); }, 1); + return; + } + var item = new AsyncQueueItem(data, typeof callback === 'function' ? callback : _noop); + if (insertAtFront) { + _this._tasks.unshift(item); + } + else { + _this._tasks.push(item); + } + setTimeout(_this.process, 1); + }; + this.process = function () { + while (!_this.paused && _this.workers < _this.concurrency && _this._tasks.length) { + var task = _this._tasks.shift(); + if (_this._tasks.length === 0) { + _this.empty(); + } + _this.workers += 1; + if (_this.workers === _this.concurrency) { + _this.saturated(); + } + _this._worker(task.data, onlyOnce(_this._next(task))); + } + }; + this._worker = worker; + if (concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + this.concurrency = concurrency; + this.buffer = concurrency / 4.0; + } + /** + * @param task + * @private + */ + AsyncQueue.prototype._next = function (task) { + var _this = this; + return function () { + var arguments$1 = arguments; + + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments$1[_i]; + } + _this.workers -= 1; + task.callback.apply(task, args); + // eslint-disable-next-line no-eq-null,eqeqeq + if (args[0] != null) { + _this.error(args[0], task.data); + } + if (_this.workers <= (_this.concurrency - _this.buffer)) { + _this.unsaturated(); + } + if (_this.idle()) { + _this.drain(); + } + _this.process(); + }; + }; + // That was in object + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + AsyncQueue.prototype.push = function (data, callback) { + this._insert(data, false, callback); + }; + AsyncQueue.prototype.kill = function () { + this.workers = 0; + this.drain = _noop; + this.started = false; + this._tasks = []; + }; + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + AsyncQueue.prototype.unshift = function (data, callback) { + this._insert(data, true, callback); + }; + AsyncQueue.prototype.length = function () { + return this._tasks.length; + }; + AsyncQueue.prototype.running = function () { + return this.workers; + }; + AsyncQueue.prototype.idle = function () { + return this._tasks.length + this.workers === 0; + }; + AsyncQueue.prototype.pause = function () { + if (this.paused === true) { + return; + } + this.paused = true; + }; + AsyncQueue.prototype.resume = function () { + if (this.paused === false) { + return; + } + this.paused = false; + // Need to call this.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= this.concurrency; w++) { + this.process(); + } + }; + /** + * Iterates an array in series. + * @param {Array.<*>} array - Array to iterate. + * @param {Function} iterator - Function to call for each element. + * @param {Function} callback - Function to call when done, or on error. + * @param {boolean} [deferNext=false] - Break synchronous each loop by calling next with a setTimeout of 1. + */ + AsyncQueue.eachSeries = function (array, iterator, callback, deferNext) { + var i = 0; + var len = array.length; + function next(err) { + if (err || i === len) { + if (callback) { + callback(err); + } + return; + } + if (deferNext) { + setTimeout(function () { + iterator(array[i++], next); + }, 1); + } + else { + iterator(array[i++], next); + } + } + next(); + }; + /** + * Async queue implementation, + * @param {Function} worker - The worker function to call for each task. + * @param {number} concurrency - How many workers to run in parrallel. + * @returns {*} The async queue object. + */ + AsyncQueue.queue = function (worker, concurrency) { + return new AsyncQueue(worker, concurrency); + }; + return AsyncQueue; + }()); + + // some constants + var MAX_PROGRESS = 100; + var rgxExtractUrlHash = /(#[\w-]+)?$/; + /** + * The new loader, forked from Resource Loader by Chad Engler: https://github.com/englercj/resource-loader + * + * ```js + * const loader = PIXI.Loader.shared; // PixiJS exposes a premade instance for you to use. + * // or + * const loader = new PIXI.Loader(); // You can also create your own if you want + * + * const sprites = {}; + * + * // Chainable `add` to enqueue a resource + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.add('scoreFont', 'assets/score.fnt'); + * + * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource. + * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc). + * loader.pre(cachingMiddleware); + * + * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource. + * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc). + * loader.use(parsingMiddleware); + * + * // The `load` method loads the queue of resources, and calls the passed in callback called once all + * // resources have loaded. + * loader.load((loader, resources) => { + * // resources is an object where the key is the name of the resource loaded and the value is the resource object. + * // They have a couple default properties: + * // - `url`: The URL that the resource was loaded from + * // - `error`: The error that happened when trying to load (if any) + * // - `data`: The raw data that was loaded + * // also may contain other properties based on the middleware that runs. + * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture); + * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture); + * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture); + * }); + * + * // throughout the process multiple signals can be dispatched. + * loader.onProgress.add(() => {}); // called once per loaded/errored file + * loader.onError.add(() => {}); // called once per errored file + * loader.onLoad.add(() => {}); // called once per loaded file + * loader.onComplete.add(() => {}); // called once when the queued resources all load. + * ``` + * @memberof PIXI + */ + var Loader = /** @class */ (function () { + /** + * @param baseUrl - The base url for all resources loaded by this loader. + * @param concurrency - The number of resources to load concurrently. + */ + function Loader(baseUrl, concurrency) { + var _this = this; + if (baseUrl === void 0) { baseUrl = ''; } + if (concurrency === void 0) { concurrency = 10; } + /** The progress percent of the loader going through the queue. */ + this.progress = 0; + /** Loading state of the loader, true if it is currently loading resources. */ + this.loading = false; + /** + * A querystring to append to every URL added to the loader. + * + * This should be a valid query string *without* the question-mark (`?`). The loader will + * also *not* escape values for you. Make sure to escape your parameters with + * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. + * @example + * const loader = new Loader(); + * + * loader.defaultQueryString = 'user=me&password=secret'; + * + * // This will request 'image.png?user=me&password=secret' + * loader.add('image.png').load(); + * + * loader.reset(); + * + * // This will request 'image.png?v=1&user=me&password=secret' + * loader.add('iamge.png?v=1').load(); + */ + this.defaultQueryString = ''; + /** The middleware to run before loading each resource. */ + this._beforeMiddleware = []; + /** The middleware to run after loading each resource. */ + this._afterMiddleware = []; + /** The tracks the resources we are currently completing parsing for. */ + this._resourcesParsing = []; + /** + * The `_loadResource` function bound with this object context. + * @param r - The resource to load + * @param d - The dequeue function + */ + this._boundLoadResource = function (r, d) { return _this._loadResource(r, d); }; + /** All the resources for this loader keyed by name. */ + this.resources = {}; + this.baseUrl = baseUrl; + this._beforeMiddleware = []; + this._afterMiddleware = []; + this._resourcesParsing = []; + this._boundLoadResource = function (r, d) { return _this._loadResource(r, d); }; + this._queue = AsyncQueue.queue(this._boundLoadResource, concurrency); + this._queue.pause(); + this.resources = {}; + this.onProgress = new Signal(); + this.onError = new Signal(); + this.onLoad = new Signal(); + this.onStart = new Signal(); + this.onComplete = new Signal(); + for (var i = 0; i < Loader._plugins.length; ++i) { + var plugin = Loader._plugins[i]; + var pre = plugin.pre, use = plugin.use; + if (pre) { + this.pre(pre); + } + if (use) { + this.use(use); + } + } + this._protected = false; + } + /** + * Same as add, params have strict order + * @private + * @param name - The name of the resource to load. + * @param url - The url for this resource, relative to the baseUrl of this loader. + * @param options - The options for the load. + * @param callback - Function to call when this specific resource completes loading. + * @returns The loader itself. + */ + Loader.prototype._add = function (name, url, options, callback) { + // if loading already you can only add resources that have a parent. + if (this.loading && (!options || !options.parentResource)) { + throw new Error('Cannot add resources while the loader is running.'); + } + // check if resource already exists. + if (this.resources[name]) { + throw new Error("Resource named \"" + name + "\" already exists."); + } + // add base url if this isn't an absolute url + url = this._prepareUrl(url); + // create the store the resource + this.resources[name] = new exports.LoaderResource(name, url, options); + if (typeof callback === 'function') { + this.resources[name].onAfterMiddleware.once(callback); + } + // if actively loading, make sure to adjust progress chunks for that parent and its children + if (this.loading) { + var parent = options.parentResource; + var incompleteChildren = []; + for (var i = 0; i < parent.children.length; ++i) { + if (!parent.children[i].isComplete) { + incompleteChildren.push(parent.children[i]); + } + } + var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent + var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child + parent.children.push(this.resources[name]); + parent.progressChunk = eachChunk; + for (var i = 0; i < incompleteChildren.length; ++i) { + incompleteChildren[i].progressChunk = eachChunk; + } + this.resources[name].progressChunk = eachChunk; + } + // add the resource to the queue + this._queue.push(this.resources[name]); + return this; + }; + /* eslint-enable require-jsdoc,valid-jsdoc */ + /** + * Sets up a middleware function that will run *before* the + * resource is loaded. + * @param fn - The middleware function to register. + * @returns The loader itself. + */ + Loader.prototype.pre = function (fn) { + this._beforeMiddleware.push(fn); + return this; + }; + /** + * Sets up a middleware function that will run *after* the + * resource is loaded. + * @param fn - The middleware function to register. + * @returns The loader itself. + */ + Loader.prototype.use = function (fn) { + this._afterMiddleware.push(fn); + return this; + }; + /** + * Resets the queue of the loader to prepare for a new load. + * @returns The loader itself. + */ + Loader.prototype.reset = function () { + this.progress = 0; + this.loading = false; + this._queue.kill(); + this._queue.pause(); + // abort all resource loads + for (var k in this.resources) { + var res = this.resources[k]; + if (res._onLoadBinding) { + res._onLoadBinding.detach(); + } + if (res.isLoading) { + res.abort('loader reset'); + } + } + this.resources = {}; + return this; + }; + /** + * Starts loading the queued resources. + * @param cb - Optional callback that will be bound to the `complete` event. + * @returns The loader itself. + */ + Loader.prototype.load = function (cb) { + deprecation('6.5.0', '@pixi/loaders is being replaced with @pixi/assets in the next major release.'); + // register complete callback if they pass one + if (typeof cb === 'function') { + this.onComplete.once(cb); + } + // if the queue has already started we are done here + if (this.loading) { + return this; + } + if (this._queue.idle()) { + this._onStart(); + this._onComplete(); + } + else { + // distribute progress chunks + var numTasks = this._queue._tasks.length; + var chunk = MAX_PROGRESS / numTasks; + for (var i = 0; i < this._queue._tasks.length; ++i) { + this._queue._tasks[i].data.progressChunk = chunk; + } + // notify we are starting + this._onStart(); + // start loading + this._queue.resume(); + } + return this; + }; + Object.defineProperty(Loader.prototype, "concurrency", { + /** + * The number of resources to load concurrently. + * @default 10 + */ + get: function () { + return this._queue.concurrency; + }, + set: function (concurrency) { + this._queue.concurrency = concurrency; + }, + enumerable: false, + configurable: true + }); + /** + * Prepares a url for usage based on the configuration of this object + * @param url - The url to prepare. + * @returns The prepared url. + */ + Loader.prototype._prepareUrl = function (url) { + var parsedUrl = parseUri(url, { strictMode: true }); + var result; + // absolute url, just use it as is. + if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) { + result = url; + } + // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween + else if (this.baseUrl.length + && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 + && url.charAt(0) !== '/') { + result = this.baseUrl + "/" + url; + } + else { + result = this.baseUrl + url; + } + // if we need to add a default querystring, there is a bit more work + if (this.defaultQueryString) { + var hash = rgxExtractUrlHash.exec(result)[0]; + result = result.slice(0, result.length - hash.length); + if (result.indexOf('?') !== -1) { + result += "&" + this.defaultQueryString; + } + else { + result += "?" + this.defaultQueryString; + } + result += hash; + } + return result; + }; + /** + * Loads a single resource. + * @param resource - The resource to load. + * @param dequeue - The function to call when we need to dequeue this item. + */ + Loader.prototype._loadResource = function (resource, dequeue) { + var _this = this; + resource._dequeue = dequeue; + // run before middleware + AsyncQueue.eachSeries(this._beforeMiddleware, function (fn, next) { + fn.call(_this, resource, function () { + // if the before middleware marks the resource as complete, + // break and don't process any more before middleware + next(resource.isComplete ? {} : null); + }); + }, function () { + if (resource.isComplete) { + _this._onLoad(resource); + } + else { + resource._onLoadBinding = resource.onComplete.once(_this._onLoad, _this); + resource.load(); + } + }, true); + }; + /** Called once loading has started. */ + Loader.prototype._onStart = function () { + this.progress = 0; + this.loading = true; + this.onStart.dispatch(this); + }; + /** Called once each resource has loaded. */ + Loader.prototype._onComplete = function () { + this.progress = MAX_PROGRESS; + this.loading = false; + this.onComplete.dispatch(this, this.resources); + }; + /** + * Called each time a resources is loaded. + * @param resource - The resource that was loaded + */ + Loader.prototype._onLoad = function (resource) { + var _this = this; + resource._onLoadBinding = null; + // remove this resource from the async queue, and add it to our list of resources that are being parsed + this._resourcesParsing.push(resource); + resource._dequeue(); + // run all the after middleware for this resource + AsyncQueue.eachSeries(this._afterMiddleware, function (fn, next) { + fn.call(_this, resource, next); + }, function () { + resource.onAfterMiddleware.dispatch(resource); + _this.progress = Math.min(MAX_PROGRESS, _this.progress + resource.progressChunk); + _this.onProgress.dispatch(_this, resource); + if (resource.error) { + _this.onError.dispatch(resource.error, _this, resource); + } + else { + _this.onLoad.dispatch(_this, resource); + } + _this._resourcesParsing.splice(_this._resourcesParsing.indexOf(resource), 1); + // do completion check + if (_this._queue.idle() && _this._resourcesParsing.length === 0) { + _this._onComplete(); + } + }, true); + }; + /** Destroy the loader, removes references. */ + Loader.prototype.destroy = function () { + if (!this._protected) { + this.reset(); + } + }; + Object.defineProperty(Loader, "shared", { + /** A premade instance of the loader that can be used to load resources. */ + get: function () { + var shared = Loader._shared; + if (!shared) { + shared = new Loader(); + shared._protected = true; + Loader._shared = shared; + } + return shared; + }, + enumerable: false, + configurable: true + }); + /** + * Use the {@link PIXI.extensions.add} API to register plugins. + * @deprecated since 6.5.0 + * @param plugin - The plugin to add + * @returns Reference to PIXI.Loader for chaining + */ + Loader.registerPlugin = function (plugin) { + deprecation('6.5.0', 'Loader.registerPlugin() is deprecated, use extensions.add() instead.'); + extensions.add({ + type: exports.ExtensionType.Loader, + ref: plugin, + }); + return Loader; + }; + Loader._plugins = []; + return Loader; + }()); + extensions.handleByList(exports.ExtensionType.Loader, Loader._plugins); + Loader.prototype.add = function add(name, url, options, callback) { + // special case of an array of objects or urls + if (Array.isArray(name)) { + for (var i = 0; i < name.length; ++i) { + this.add(name[i]); + } + return this; + } + // if an object is passed instead of params + if (typeof name === 'object') { + options = name; + callback = url || options.callback || options.onComplete; + url = options.url; + name = options.name || options.key || options.url; + } + // case where no name is passed shift all args over by one. + if (typeof url !== 'string') { + callback = options; + options = url; + url = name; + } + // now that we shifted make sure we have a proper url. + if (typeof url !== 'string') { + throw new Error('No url passed to add resource to loader.'); + } + // options are optional so people might pass a function and no options + if (typeof options === 'function') { + callback = options; + options = null; + } + return this._add(name, url, options, callback); + }; - BasePrepare.prototype.registerFindHook = function registerFindHook(addHook) { - if (addHook) { - this.addHooks.push(addHook); - } + /** + * Application plugin for supporting loader option. Installing the LoaderPlugin + * is not necessary if using **pixi.js** or **pixi.js-legacy**. + * @example + * import {AppLoaderPlugin} from '@pixi/loaders'; + * import {extensions} from '@pixi/core'; + * extensions.add(AppLoaderPlugin); + * @memberof PIXI + */ + var AppLoaderPlugin = /** @class */ (function () { + function AppLoaderPlugin() { + } + /** + * Called on application constructor + * @param options + * @private + */ + AppLoaderPlugin.init = function (options) { + options = Object.assign({ + sharedLoader: false, + }, options); + this.loader = options.sharedLoader ? Loader.shared : new Loader(); + }; + /** + * Called when application destroyed + * @private + */ + AppLoaderPlugin.destroy = function () { + if (this.loader) { + this.loader.destroy(); + this.loader = null; + } + }; + /** @ignore */ + AppLoaderPlugin.extension = exports.ExtensionType.Application; + return AppLoaderPlugin; + }()); - return this; - }; + /** + * Loader plugin for handling Texture resources. + * @memberof PIXI + */ + var TextureLoader = /** @class */ (function () { + function TextureLoader() { + } + /** Handle SVG elements a text, render with SVGResource. */ + TextureLoader.add = function () { + exports.LoaderResource.setExtensionLoadType('svg', exports.LoaderResource.LOAD_TYPE.XHR); + exports.LoaderResource.setExtensionXhrType('svg', exports.LoaderResource.XHR_RESPONSE_TYPE.TEXT); + }; + /** + * Called after a resource is loaded. + * @see PIXI.Loader.loaderMiddleware + * @param resource + * @param {Function} next + */ + TextureLoader.use = function (resource, next) { + // create a new texture if the data is an Image object + if (resource.data && (resource.type === exports.LoaderResource.TYPE.IMAGE || resource.extension === 'svg')) { + var data = resource.data, url = resource.url, name = resource.name, metadata = resource.metadata; + Texture.fromLoader(data, url, name, metadata).then(function (texture) { + resource.texture = texture; + next(); + }) + // TODO: handle errors in Texture.fromLoader + // so we can pass them to the Loader + .catch(next); + } + else { + next(); + } + }; + /** @ignore */ + TextureLoader.extension = exports.ExtensionType.Loader; + return TextureLoader; + }()); - /** - * Adds hooks for uploading items. - * - * @param {Function} uploadHook - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and - * function must return `true` if it was able to handle upload of item. - * @return {PIXI.BasePrepare} Instance of plugin for chaining. - */ + var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + /** + * Encodes binary into base64. + * @function encodeBinary + * @param {string} input - The input data to encode. + * @returns {string} The encoded base64 string + */ + function encodeBinary(input) { + var output = ''; + var inx = 0; + while (inx < input.length) { + // Fill byte buffer array + var bytebuffer = [0, 0, 0]; + var encodedCharIndexes = [0, 0, 0, 0]; + for (var jnx = 0; jnx < bytebuffer.length; ++jnx) { + if (inx < input.length) { + // throw away high-order byte, as documented at: + // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data + bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; + } + else { + bytebuffer[jnx] = 0; + } + } + // Get each encoded character, 6 bits at a time + // index 1: first 6 bits + encodedCharIndexes[0] = bytebuffer[0] >> 2; + // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) + encodedCharIndexes[1] = ((bytebuffer[0] & 0x3) << 4) | (bytebuffer[1] >> 4); + // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) + encodedCharIndexes[2] = ((bytebuffer[1] & 0x0f) << 2) | (bytebuffer[2] >> 6); + // index 3: forth 6 bits (6 least significant bits from input byte 3) + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; + // Determine whether padding happened, and adjust accordingly + var paddingBytes = inx - (input.length - 1); + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; + } + // Now we will grab each appropriate character out of our keystring + // based on our index array and append it to the output string + for (var jnx = 0; jnx < encodedCharIndexes.length; ++jnx) { + output += _keyStr.charAt(encodedCharIndexes[jnx]); + } + } + return output; + } + /** + * A middleware for transforming XHR loaded Blobs into more useful objects + * @ignore + * @function parsing + * @example + * import { Loader, middleware } from 'resource-loader'; + * const loader = new Loader(); + * loader.use(middleware.parsing); + * @param resource - Current Resource + * @param next - Callback when complete + */ + function parsing(resource, next) { + if (!resource.data) { + next(); + return; + } + // if this was an XHR load of a blob + if (resource.xhr && resource.xhrType === exports.LoaderResource.XHR_RESPONSE_TYPE.BLOB) { + // if there is no blob support we probably got a binary string back + if (!self.Blob || typeof resource.data === 'string') { + var type = resource.xhr.getResponseHeader('content-type'); + // this is an image, convert the binary string into a data url + if (type && type.indexOf('image') === 0) { + resource.data = new Image(); + resource.data.src = "data:" + type + ";base64," + encodeBinary(resource.xhr.responseText); + resource.type = exports.LoaderResource.TYPE.IMAGE; + // wait until the image loads and then callback + resource.data.onload = function () { + resource.data.onload = null; + next(); + }; + // next will be called on load + return; + } + } + // if content type says this is an image, then we should transform the blob into an Image object + else if (resource.data.type.indexOf('image') === 0) { + var Url_1 = globalThis.URL || globalThis.webkitURL; + var src_1 = Url_1.createObjectURL(resource.data); + resource.blob = resource.data; + resource.data = new Image(); + resource.data.src = src_1; + resource.type = exports.LoaderResource.TYPE.IMAGE; + // cleanup the no longer used blob after the image loads + // TODO: Is this correct? Will the image be invalid after revoking? + resource.data.onload = function () { + Url_1.revokeObjectURL(src_1); + resource.data.onload = null; + next(); + }; + // next will be called on load. + return; + } + } + next(); + } - BasePrepare.prototype.registerUploadHook = function registerUploadHook(uploadHook) { - if (uploadHook) { - this.uploadHooks.push(uploadHook); - } + /** + * Parse any blob into more usable objects (e.g. Image). + * @memberof PIXI + */ + var ParsingLoader = /** @class */ (function () { + function ParsingLoader() { + } + /** @ignore */ + ParsingLoader.extension = exports.ExtensionType.Loader; + ParsingLoader.use = parsing; + return ParsingLoader; + }()); - return this; - }; + extensions.add(TextureLoader, ParsingLoader); - /** - * Manually add an item to the uploading queue. - * - * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to - * add to the queue - * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. - */ - - - BasePrepare.prototype.add = function add(item) { - // Add additional hooks for finding elements on special - // types of objects that - for (var i = 0, len = this.addHooks.length; i < len; i++) { - if (this.addHooks[i](item, this.queue)) { - break; - } - } + /*! + * @pixi/compressed-textures - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/compressed-textures is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ - // Get childen recursively - if (item instanceof core.Container) { - for (var _i2 = item.children.length - 1; _i2 >= 0; _i2--) { - this.add(item.children[_i2]); - } - } + var _a$2; + /** + * WebGL internal formats, including compressed texture formats provided by extensions + * @memberof PIXI + * @static + * @name INTERNAL_FORMATS + * @enum {number} + * @property {number} [COMPRESSED_RGB_S3TC_DXT1_EXT=0x83F0] - + * @property {number} [COMPRESSED_RGBA_S3TC_DXT1_EXT=0x83F1] - + * @property {number} [COMPRESSED_RGBA_S3TC_DXT3_EXT=0x83F2] - + * @property {number} [COMPRESSED_RGBA_S3TC_DXT5_EXT=0x83F3] - + * @property {number} [COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917] - + * @property {number} [COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918] - + * @property {number} [COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919] - + * @property {number} [COMPRESSED_SRGB_S3TC_DXT1_EXT=35916] - + * @property {number} [COMPRESSED_R11_EAC=0x9270] - + * @property {number} [COMPRESSED_SIGNED_R11_EAC=0x9271] - + * @property {number} [COMPRESSED_RG11_EAC=0x9272] - + * @property {number} [COMPRESSED_SIGNED_RG11_EAC=0x9273] - + * @property {number} [COMPRESSED_RGB8_ETC2=0x9274] - + * @property {number} [COMPRESSED_RGBA8_ETC2_EAC=0x9278] - + * @property {number} [COMPRESSED_SRGB8_ETC2=0x9275] - + * @property {number} [COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=0x9279] - + * @property {number} [COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=0x9276] - + * @property {number} [COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=0x9277] - + * @property {number} [COMPRESSED_RGB_PVRTC_4BPPV1_IMG=0x8C00] - + * @property {number} [COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=0x8C02] - + * @property {number} [COMPRESSED_RGB_PVRTC_2BPPV1_IMG=0x8C01] - + * @property {number} [COMPRESSED_RGBA_PVRTC_2BPPV1_IMG=0x8C03] - + * @property {number} [COMPRESSED_RGB_ETC1_WEBGL=0x8D64] - + * @property {number} [COMPRESSED_RGB_ATC_WEBGL=0x8C92] - + * @property {number} [COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL=0x8C92] - + * @property {number} [COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL=0x87EE] - + * @property {number} [COMPRESSED_RGBA_ASTC_4x4_KHR=0x93B0] - + */ + exports.INTERNAL_FORMATS = void 0; + (function (INTERNAL_FORMATS) { + // WEBGL_compressed_texture_s3tc + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_S3TC_DXT1_EXT"] = 33776] = "COMPRESSED_RGB_S3TC_DXT1_EXT"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT1_EXT"] = 33777] = "COMPRESSED_RGBA_S3TC_DXT1_EXT"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT3_EXT"] = 33778] = "COMPRESSED_RGBA_S3TC_DXT3_EXT"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT5_EXT"] = 33779] = "COMPRESSED_RGBA_S3TC_DXT5_EXT"; + // WEBGL_compressed_texture_s3tc_srgb + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"] = 35917] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"] = 35918] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"] = 35919] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_S3TC_DXT1_EXT"] = 35916] = "COMPRESSED_SRGB_S3TC_DXT1_EXT"; + // WEBGL_compressed_texture_etc + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_R11_EAC"] = 37488] = "COMPRESSED_R11_EAC"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SIGNED_R11_EAC"] = 37489] = "COMPRESSED_SIGNED_R11_EAC"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RG11_EAC"] = 37490] = "COMPRESSED_RG11_EAC"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SIGNED_RG11_EAC"] = 37491] = "COMPRESSED_SIGNED_RG11_EAC"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB8_ETC2"] = 37492] = "COMPRESSED_RGB8_ETC2"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA8_ETC2_EAC"] = 37496] = "COMPRESSED_RGBA8_ETC2_EAC"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_ETC2"] = 37493] = "COMPRESSED_SRGB8_ETC2"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"] = 37497] = "COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37494] = "COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37495] = "COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"; + // WEBGL_compressed_texture_pvrtc + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_PVRTC_4BPPV1_IMG"] = 35840] = "COMPRESSED_RGB_PVRTC_4BPPV1_IMG"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"] = 35842] = "COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_PVRTC_2BPPV1_IMG"] = 35841] = "COMPRESSED_RGB_PVRTC_2BPPV1_IMG"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"] = 35843] = "COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"; + // WEBGL_compressed_texture_etc1 + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_ETC1_WEBGL"] = 36196] = "COMPRESSED_RGB_ETC1_WEBGL"; + // WEBGL_compressed_texture_atc + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_ATC_WEBGL"] = 35986] = "COMPRESSED_RGB_ATC_WEBGL"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL"] = 35986] = "COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL"] = 34798] = "COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL"; + // WEBGL_compressed_texture_astc + /* eslint-disable-next-line camelcase */ + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_ASTC_4x4_KHR"] = 37808] = "COMPRESSED_RGBA_ASTC_4x4_KHR"; + })(exports.INTERNAL_FORMATS || (exports.INTERNAL_FORMATS = {})); + /** + * Maps the compressed texture formats in {@link PIXI.INTERNAL_FORMATS} to the number of bytes taken by + * each texel. + * @memberof PIXI + * @static + * @ignore + */ + var INTERNAL_FORMAT_TO_BYTES_PER_PIXEL = (_a$2 = {}, + // WEBGL_compressed_texture_s3tc + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_S3TC_DXT1_EXT] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT] = 1, + // WEBGL_compressed_texture_s3tc + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_S3TC_DXT1_EXT] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT] = 1, + // WEBGL_compressed_texture_etc + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_R11_EAC] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SIGNED_R11_EAC] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RG11_EAC] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SIGNED_RG11_EAC] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB8_ETC2] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA8_ETC2_EAC] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB8_ETC2] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2] = 0.5, + // WEBGL_compressed_texture_pvrtc + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_PVRTC_4BPPV1_IMG] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_PVRTC_2BPPV1_IMG] = 0.25, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG] = 0.25, + // WEBGL_compressed_texture_etc1 + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_ETC1_WEBGL] = 0.5, + // @see https://www.khronos.org/registry/OpenGL/extensions/AMD/AMD_compressed_ATC_texture.txt + // WEBGL_compressed_texture_atc + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_ATC_WEBGL] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL] = 1, + // @see https://registry.khronos.org/OpenGL/extensions/KHR/KHR_texture_compression_astc_hdr.txt + // WEBGL_compressed_texture_astc + /* eslint-disable-next-line camelcase */ + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_ASTC_4x4_KHR] = 1, + _a$2); + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$g = function(d, b) { + extendStatics$g = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$g(d, b); + }; - return this; - }; + function __extends$g(d, b) { + extendStatics$g(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } - /** - * Destroys the plugin, don't use after this. - * - */ + function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + } + function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) { throw t[1]; } return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) { throw new TypeError("Generator is already executing."); } + while (_) { try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) { return t; } + if (y = 0, t) { op = [op[0] & 2, t.value]; } + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) { _.ops.pop(); } + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } } + if (op[0] & 5) { throw op[1]; } return { value: op[0] ? op[1] : void 0, done: true }; + } + } - BasePrepare.prototype.destroy = function destroy() { - if (this.ticking) { - SharedTicker.remove(this.tick, this); - } - this.ticking = false; - this.addHooks = null; - this.uploadHooks = null; - this.renderer = null; - this.completes = null; - this.queue = null; - this.limiter = null; - this.uploadHookHelper = null; - }; + /** + * Resource that fetches texture data over the network and stores it in a buffer. + * @class + * @extends PIXI.Resource + * @memberof PIXI + */ + var BlobResource = /** @class */ (function (_super) { + __extends$g(BlobResource, _super); + /** + * @param {string} source - the URL of the texture file + * @param {PIXI.IBlobOptions} options + * @param {boolean}[options.autoLoad] - whether to fetch the data immediately; + * you can fetch it later via {@link BlobResource#load} + * @param {boolean}[options.width] - the width in pixels. + * @param {boolean}[options.height] - the height in pixels. + */ + function BlobResource(source, options) { + if (options === void 0) { options = { width: 1, height: 1, autoLoad: true }; } + var _this = this; + var origin; + var data; + if (typeof source === 'string') { + origin = source; + data = new Uint8Array(); + } + else { + origin = null; + data = source; + } + _this = _super.call(this, data, options) || this; + /** + * The URL of the texture file + * @member {string} + */ + _this.origin = origin; + /** + * The viewable buffer on the data + * @member {ViewableBuffer} + */ + // HINT: BlobResource allows "null" sources, assuming the child class provides an alternative + _this.buffer = data ? new ViewableBuffer(data) : null; + // Allow autoLoad = "undefined" still load the resource by default + if (_this.origin && options.autoLoad !== false) { + _this.load(); + } + if (data && data.length) { + _this.loaded = true; + _this.onBlobLoaded(_this.buffer.rawBinaryData); + } + return _this; + } + BlobResource.prototype.onBlobLoaded = function (_data) { + // TODO: Override this method + }; + /** Loads the blob */ + BlobResource.prototype.load = function () { + return __awaiter(this, void 0, Promise, function () { + var response, blob, arrayBuffer; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, fetch(this.origin)]; + case 1: + response = _a.sent(); + return [4 /*yield*/, response.blob()]; + case 2: + blob = _a.sent(); + return [4 /*yield*/, blob.arrayBuffer()]; + case 3: + arrayBuffer = _a.sent(); + this.data = new Uint32Array(arrayBuffer); + this.buffer = new ViewableBuffer(arrayBuffer); + this.loaded = true; + this.onBlobLoaded(arrayBuffer); + this.update(); + return [2 /*return*/, this]; + } + }); + }); + }; + return BlobResource; + }(BufferResource)); - return BasePrepare; -}(); + /** + * Resource for compressed texture formats, as follows: S3TC/DXTn (& their sRGB formats), ATC, ASTC, ETC 1/2, PVRTC. + * + * Compressed textures improve performance when rendering is texture-bound. The texture data stays compressed in + * graphics memory, increasing memory locality and speeding up texture fetches. These formats can also be used to store + * more detail in the same amount of memory. + * + * For most developers, container file formats are a better abstraction instead of directly handling raw texture + * data. PixiJS provides native support for the following texture file formats (via {@link PIXI.Loader}): + * + * **.dds** - the DirectDraw Surface file format stores DXTn (DXT-1,3,5) data. See {@link PIXI.DDSLoader} + * **.ktx** - the Khronos Texture Container file format supports storing all the supported WebGL compression formats. + * See {@link PIXI.KTXLoader}. + * **.basis** - the BASIS supercompressed file format stores texture data in an internal format that is transcoded + * to the compression format supported on the device at _runtime_. It also supports transcoding into a uncompressed + * format as a fallback; you must install the `@pixi/basis-loader`, `@pixi/basis-transcoder` packages separately to + * use these files. See {@link PIXI.BasisLoader}. + * + * The loaders for the aforementioned formats use `CompressedTextureResource` internally. It is strongly suggested that + * they be used instead. + * + * ## Working directly with CompressedTextureResource + * + * Since `CompressedTextureResource` inherits `BlobResource`, you can provide it a URL pointing to a file containing + * the raw texture data (with no file headers!): + * + * ```js + * // The resource backing the texture data for your textures. + * // NOTE: You can also provide a ArrayBufferView instead of a URL. This is used when loading data from a container file + * // format such as KTX, DDS, or BASIS. + * const compressedResource = new PIXI.CompressedTextureResource("bunny.dxt5", { + * format: PIXI.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT, + * width: 256, + * height: 256 + * }); + * + * // You can create a base-texture to the cache, so that future `Texture`s can be created using the `Texture.from` API. + * const baseTexture = new PIXI.BaseTexture(compressedResource, { pmaMode: PIXI.ALPHA_MODES.NPM }); + * + * // Create a Texture to add to the TextureCache + * const texture = new PIXI.Texture(baseTexture); + * + * // Add baseTexture & texture to the global texture cache + * PIXI.BaseTexture.addToCache(baseTexture, "bunny.dxt5"); + * PIXI.Texture.addToCache(texture, "bunny.dxt5"); + * ``` + * @memberof PIXI + */ + var CompressedTextureResource = /** @class */ (function (_super) { + __extends$g(CompressedTextureResource, _super); + /** + * @param source - the buffer/URL holding the compressed texture data + * @param options + * @param {PIXI.INTERNAL_FORMATS} options.format - the compression format + * @param {number} options.width - the image width in pixels. + * @param {number} options.height - the image height in pixels. + * @param {number} [options.level=1] - the mipmap levels stored in the compressed texture, including level 0. + * @param {number} [options.levelBuffers] - the buffers for each mipmap level. `CompressedTextureResource` can allows you + * to pass `null` for `source`, for cases where each level is stored in non-contiguous memory. + */ + function CompressedTextureResource(source, options) { + var _this = _super.call(this, source, options) || this; + _this.format = options.format; + _this.levels = options.levels || 1; + _this._width = options.width; + _this._height = options.height; + _this._extension = CompressedTextureResource._formatToExtension(_this.format); + if (options.levelBuffers || _this.buffer) { + // ViewableBuffer doesn't support byteOffset :-( so allow source to be Uint8Array + _this._levelBuffers = options.levelBuffers + || CompressedTextureResource._createLevelBuffers(source instanceof Uint8Array ? source : _this.buffer.uint8View, _this.format, _this.levels, 4, 4, // PVRTC has 8x4 blocks in 2bpp mode + _this.width, _this.height); + } + return _this; + } + /** + * @override + * @param renderer - A reference to the current renderer + * @param _texture - the texture + * @param _glTexture - texture instance for this webgl context + */ + CompressedTextureResource.prototype.upload = function (renderer, _texture, _glTexture) { + var gl = renderer.gl; + var extension = renderer.context.extensions[this._extension]; + if (!extension) { + throw new Error(this._extension + " textures are not supported on the current machine"); + } + if (!this._levelBuffers) { + // Do not try to upload data before BlobResource loads, unless the levelBuffers were provided directly! + return false; + } + for (var i = 0, j = this.levels; i < j; i++) { + var _a = this._levelBuffers[i], levelID = _a.levelID, levelWidth = _a.levelWidth, levelHeight = _a.levelHeight, levelBuffer = _a.levelBuffer; + gl.compressedTexImage2D(gl.TEXTURE_2D, levelID, this.format, levelWidth, levelHeight, 0, levelBuffer); + } + return true; + }; + /** @protected */ + CompressedTextureResource.prototype.onBlobLoaded = function () { + this._levelBuffers = CompressedTextureResource._createLevelBuffers(this.buffer.uint8View, this.format, this.levels, 4, 4, // PVRTC has 8x4 blocks in 2bpp mode + this.width, this.height); + }; + /** + * Returns the key (to ContextSystem#extensions) for the WebGL extension supporting the compression format + * @private + * @param format - the compression format to get the extension for. + */ + CompressedTextureResource._formatToExtension = function (format) { + if (format >= 0x83F0 && format <= 0x83F3) { + return 's3tc'; + } + else if (format >= 0x9270 && format <= 0x9279) { + return 'etc'; + } + else if (format >= 0x8C00 && format <= 0x8C03) { + return 'pvrtc'; + } + else if (format >= 0x8D64) { + return 'etc1'; + } + else if (format >= 0x8C92 && format <= 0x87EE) { + return 'atc'; + } + throw new Error('Invalid (compressed) texture format given!'); + }; + /** + * Pre-creates buffer views for each mipmap level + * @private + * @param buffer - + * @param format - compression formats + * @param levels - mipmap levels + * @param blockWidth - + * @param blockHeight - + * @param imageWidth - width of the image in pixels + * @param imageHeight - height of the image in pixels + */ + CompressedTextureResource._createLevelBuffers = function (buffer, format, levels, blockWidth, blockHeight, imageWidth, imageHeight) { + // The byte-size of the first level buffer + var buffers = new Array(levels); + var offset = buffer.byteOffset; + var levelWidth = imageWidth; + var levelHeight = imageHeight; + var alignedLevelWidth = (levelWidth + blockWidth - 1) & ~(blockWidth - 1); + var alignedLevelHeight = (levelHeight + blockHeight - 1) & ~(blockHeight - 1); + var levelSize = alignedLevelWidth * alignedLevelHeight * INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[format]; + for (var i = 0; i < levels; i++) { + buffers[i] = { + levelID: i, + levelWidth: levels > 1 ? levelWidth : alignedLevelWidth, + levelHeight: levels > 1 ? levelHeight : alignedLevelHeight, + levelBuffer: new Uint8Array(buffer.buffer, offset, levelSize) + }; + offset += levelSize; + // Calculate levelBuffer dimensions for next iteration + levelWidth = (levelWidth >> 1) || 1; + levelHeight = (levelHeight >> 1) || 1; + alignedLevelWidth = (levelWidth + blockWidth - 1) & ~(blockWidth - 1); + alignedLevelHeight = (levelHeight + blockHeight - 1) & ~(blockHeight - 1); + levelSize = alignedLevelWidth * alignedLevelHeight * INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[format]; + } + return buffers; + }; + return CompressedTextureResource; + }(BlobResource)); -/** - * Built-in hook to find multiple textures from objects like AnimatedSprites. - * - * @private - * @param {PIXI.DisplayObject} item - Display object to check - * @param {Array<*>} queue - Collection of items to upload - * @return {boolean} if a PIXI.Texture object was found. - */ + /* eslint-enable camelcase */ + /** + * Loader plugin for handling compressed textures for all platforms. + * @class + * @memberof PIXI + * @implements {PIXI.ILoaderPlugin} + */ + var CompressedTextureLoader = /** @class */ (function () { + function CompressedTextureLoader() { + } + /** + * Called after a compressed-textures manifest is loaded. + * + * This will then load the correct compression format for the device. Your manifest should adhere + * to the following schema: + * + * ```js + * import { INTERNAL_FORMATS } from '@pixi/constants'; + * + * type CompressedTextureManifest = { + * textures: Array<{ src: string, format?: keyof INTERNAL_FORMATS}>, + * cacheID: string; + * }; + * ``` + * + * This is an example of a .json manifest file + * + * ```json + * { + * "cacheID":"asset", + * "textures":[ + * { "src":"asset.fallback.png" }, + * { "format":"COMPRESSED_RGBA_S3TC_DXT5_EXT", "src":"asset.s3tc.ktx" }, + * { "format":"COMPRESSED_RGBA8_ETC2_EAC", "src":"asset.etc.ktx" }, + * { "format":"RGBA_PVRTC_4BPPV1_IMG", "src":"asset.pvrtc.ktx" } + * ] + * } + * ``` + */ + CompressedTextureLoader.use = function (resource, next) { + var data = resource.data; + var loader = this; + if (resource.type === exports.LoaderResource.TYPE.JSON + && data + && data.cacheID + && data.textures) { + var textures = data.textures; + var textureURL = void 0; + var fallbackURL = void 0; + // Search for an extension that holds one the formats + for (var i = 0, j = textures.length; i < j; i++) { + var texture = textures[i]; + var url_1 = texture.src; + var format = texture.format; + if (!format) { + fallbackURL = url_1; + } + if (CompressedTextureLoader.textureFormats[format]) { + textureURL = url_1; + break; + } + } + textureURL = textureURL || fallbackURL; + // Make sure we have a URL + if (!textureURL) { + next(new Error("Cannot load compressed-textures in " + resource.url + ", make sure you provide a fallback")); + return; + } + if (textureURL === resource.url) { + // Prevent infinite loops + next(new Error('URL of compressed texture cannot be the same as the manifest\'s URL')); + return; + } + var loadOptions = { + crossOrigin: resource.crossOrigin, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + var resourcePath = url.resolve(resource.url.replace(loader.baseUrl, ''), textureURL); + var resourceName = data.cacheID; + // The appropriate loader should register the texture + loader.add(resourceName, resourcePath, loadOptions, function (res) { + if (res.error) { + next(res.error); + return; + } + var _a = res.texture, texture = _a === void 0 ? null : _a, _b = res.textures, textures = _b === void 0 ? {} : _b; + // Make sure texture/textures is assigned to parent resource + Object.assign(resource, { texture: texture, textures: textures }); + // Pass along any error + next(); + }); + } + else { + next(); + } + }; + Object.defineProperty(CompressedTextureLoader, "textureExtensions", { + /** Map of available texture extensions. */ + get: function () { + if (!CompressedTextureLoader._textureExtensions) { + // Auto-detect WebGL compressed-texture extensions + var canvas = settings.ADAPTER.createCanvas(); + var gl = canvas.getContext('webgl'); + if (!gl) { + console.warn('WebGL not available for compressed textures. Silently failing.'); + return {}; + } + var extensions = { + s3tc: gl.getExtension('WEBGL_compressed_texture_s3tc'), + s3tc_sRGB: gl.getExtension('WEBGL_compressed_texture_s3tc_srgb'), + etc: gl.getExtension('WEBGL_compressed_texture_etc'), + etc1: gl.getExtension('WEBGL_compressed_texture_etc1'), + pvrtc: gl.getExtension('WEBGL_compressed_texture_pvrtc') + || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'), + atc: gl.getExtension('WEBGL_compressed_texture_atc'), + astc: gl.getExtension('WEBGL_compressed_texture_astc') + }; + CompressedTextureLoader._textureExtensions = extensions; + } + return CompressedTextureLoader._textureExtensions; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CompressedTextureLoader, "textureFormats", { + /** Map of available texture formats. */ + get: function () { + if (!CompressedTextureLoader._textureFormats) { + var extensions = CompressedTextureLoader.textureExtensions; + CompressedTextureLoader._textureFormats = {}; + // Assign all available compressed-texture formats + for (var extensionName in extensions) { + var extension = extensions[extensionName]; + if (!extension) { + continue; + } + Object.assign(CompressedTextureLoader._textureFormats, Object.getPrototypeOf(extension)); + } + } + return CompressedTextureLoader._textureFormats; + }, + enumerable: false, + configurable: true + }); + /** @ignore */ + CompressedTextureLoader.extension = exports.ExtensionType.Loader; + return CompressedTextureLoader; + }()); + /** + * Creates base-textures and textures for each compressed-texture resource and adds them into the global + * texture cache. The first texture has two IDs - `${url}`, `${url}-1`; while the rest have an ID of the + * form `${url}-i`. + * @param url - the original address of the resources + * @param resources - the resources backing texture data + * @ignore + */ + function registerCompressedTextures(url, resources, metadata) { + var result = { + textures: {}, + texture: null, + }; + if (!resources) { + return result; + } + var textures = resources.map(function (resource) { + return (new Texture(new BaseTexture(resource, Object.assign({ + mipmap: exports.MIPMAP_MODES.OFF, + alphaMode: exports.ALPHA_MODES.NO_PREMULTIPLIED_ALPHA + }, metadata)))); + }); + textures.forEach(function (texture, i) { + var baseTexture = texture.baseTexture; + var cacheID = url + "-" + (i + 1); + BaseTexture.addToCache(baseTexture, cacheID); + Texture.addToCache(texture, cacheID); + if (i === 0) { + BaseTexture.addToCache(baseTexture, url); + Texture.addToCache(texture, url); + result.texture = texture; + } + result.textures[cacheID] = texture; + }); + return result; + } -exports.default = BasePrepare; -function findMultipleBaseTextures(item, queue) { - var result = false; + var _a$1, _b$1; + var DDS_MAGIC_SIZE = 4; + var DDS_HEADER_SIZE = 124; + var DDS_HEADER_PF_SIZE = 32; + var DDS_HEADER_DX10_SIZE = 20; + // DDS file format magic word + var DDS_MAGIC = 0x20534444; + /** + * DWORD offsets of the DDS file header fields (relative to file start). + * @ignore + */ + var DDS_FIELDS = { + SIZE: 1, + FLAGS: 2, + HEIGHT: 3, + WIDTH: 4, + MIPMAP_COUNT: 7, + PIXEL_FORMAT: 19, + }; + /** + * DWORD offsets of the DDS PIXEL_FORMAT fields. + * @ignore + */ + var DDS_PF_FIELDS = { + SIZE: 0, + FLAGS: 1, + FOURCC: 2, + RGB_BITCOUNT: 3, + R_BIT_MASK: 4, + G_BIT_MASK: 5, + B_BIT_MASK: 6, + A_BIT_MASK: 7 + }; + /** + * DWORD offsets of the DDS_HEADER_DX10 fields. + * @ignore + */ + var DDS_DX10_FIELDS = { + DXGI_FORMAT: 0, + RESOURCE_DIMENSION: 1, + MISC_FLAG: 2, + ARRAY_SIZE: 3, + MISC_FLAGS2: 4 + }; + /** + * @see https://docs.microsoft.com/en-us/windows/win32/api/dxgiformat/ne-dxgiformat-dxgi_format + * @ignore + */ + // This is way over-blown for us! Lend us a hand, and remove the ones that aren't used (but set the remaining + // ones to their correct value) + var DXGI_FORMAT; + (function (DXGI_FORMAT) { + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_UNKNOWN"] = 0] = "DXGI_FORMAT_UNKNOWN"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_TYPELESS"] = 1] = "DXGI_FORMAT_R32G32B32A32_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_FLOAT"] = 2] = "DXGI_FORMAT_R32G32B32A32_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_UINT"] = 3] = "DXGI_FORMAT_R32G32B32A32_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_SINT"] = 4] = "DXGI_FORMAT_R32G32B32A32_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_TYPELESS"] = 5] = "DXGI_FORMAT_R32G32B32_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_FLOAT"] = 6] = "DXGI_FORMAT_R32G32B32_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_UINT"] = 7] = "DXGI_FORMAT_R32G32B32_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_SINT"] = 8] = "DXGI_FORMAT_R32G32B32_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_TYPELESS"] = 9] = "DXGI_FORMAT_R16G16B16A16_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_FLOAT"] = 10] = "DXGI_FORMAT_R16G16B16A16_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_UNORM"] = 11] = "DXGI_FORMAT_R16G16B16A16_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_UINT"] = 12] = "DXGI_FORMAT_R16G16B16A16_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_SNORM"] = 13] = "DXGI_FORMAT_R16G16B16A16_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_SINT"] = 14] = "DXGI_FORMAT_R16G16B16A16_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_TYPELESS"] = 15] = "DXGI_FORMAT_R32G32_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_FLOAT"] = 16] = "DXGI_FORMAT_R32G32_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_UINT"] = 17] = "DXGI_FORMAT_R32G32_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_SINT"] = 18] = "DXGI_FORMAT_R32G32_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G8X24_TYPELESS"] = 19] = "DXGI_FORMAT_R32G8X24_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D32_FLOAT_S8X24_UINT"] = 20] = "DXGI_FORMAT_D32_FLOAT_S8X24_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS"] = 21] = "DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_X32_TYPELESS_G8X24_UINT"] = 22] = "DXGI_FORMAT_X32_TYPELESS_G8X24_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_TYPELESS"] = 23] = "DXGI_FORMAT_R10G10B10A2_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_UNORM"] = 24] = "DXGI_FORMAT_R10G10B10A2_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_UINT"] = 25] = "DXGI_FORMAT_R10G10B10A2_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R11G11B10_FLOAT"] = 26] = "DXGI_FORMAT_R11G11B10_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_TYPELESS"] = 27] = "DXGI_FORMAT_R8G8B8A8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UNORM"] = 28] = "DXGI_FORMAT_R8G8B8A8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UNORM_SRGB"] = 29] = "DXGI_FORMAT_R8G8B8A8_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UINT"] = 30] = "DXGI_FORMAT_R8G8B8A8_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_SNORM"] = 31] = "DXGI_FORMAT_R8G8B8A8_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_SINT"] = 32] = "DXGI_FORMAT_R8G8B8A8_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_TYPELESS"] = 33] = "DXGI_FORMAT_R16G16_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_FLOAT"] = 34] = "DXGI_FORMAT_R16G16_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_UNORM"] = 35] = "DXGI_FORMAT_R16G16_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_UINT"] = 36] = "DXGI_FORMAT_R16G16_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_SNORM"] = 37] = "DXGI_FORMAT_R16G16_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_SINT"] = 38] = "DXGI_FORMAT_R16G16_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_TYPELESS"] = 39] = "DXGI_FORMAT_R32_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D32_FLOAT"] = 40] = "DXGI_FORMAT_D32_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_FLOAT"] = 41] = "DXGI_FORMAT_R32_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_UINT"] = 42] = "DXGI_FORMAT_R32_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_SINT"] = 43] = "DXGI_FORMAT_R32_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R24G8_TYPELESS"] = 44] = "DXGI_FORMAT_R24G8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D24_UNORM_S8_UINT"] = 45] = "DXGI_FORMAT_D24_UNORM_S8_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R24_UNORM_X8_TYPELESS"] = 46] = "DXGI_FORMAT_R24_UNORM_X8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_X24_TYPELESS_G8_UINT"] = 47] = "DXGI_FORMAT_X24_TYPELESS_G8_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_TYPELESS"] = 48] = "DXGI_FORMAT_R8G8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_UNORM"] = 49] = "DXGI_FORMAT_R8G8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_UINT"] = 50] = "DXGI_FORMAT_R8G8_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_SNORM"] = 51] = "DXGI_FORMAT_R8G8_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_SINT"] = 52] = "DXGI_FORMAT_R8G8_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_TYPELESS"] = 53] = "DXGI_FORMAT_R16_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_FLOAT"] = 54] = "DXGI_FORMAT_R16_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D16_UNORM"] = 55] = "DXGI_FORMAT_D16_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_UNORM"] = 56] = "DXGI_FORMAT_R16_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_UINT"] = 57] = "DXGI_FORMAT_R16_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_SNORM"] = 58] = "DXGI_FORMAT_R16_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_SINT"] = 59] = "DXGI_FORMAT_R16_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_TYPELESS"] = 60] = "DXGI_FORMAT_R8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_UNORM"] = 61] = "DXGI_FORMAT_R8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_UINT"] = 62] = "DXGI_FORMAT_R8_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_SNORM"] = 63] = "DXGI_FORMAT_R8_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_SINT"] = 64] = "DXGI_FORMAT_R8_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_A8_UNORM"] = 65] = "DXGI_FORMAT_A8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R1_UNORM"] = 66] = "DXGI_FORMAT_R1_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R9G9B9E5_SHAREDEXP"] = 67] = "DXGI_FORMAT_R9G9B9E5_SHAREDEXP"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_B8G8_UNORM"] = 68] = "DXGI_FORMAT_R8G8_B8G8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_G8R8_G8B8_UNORM"] = 69] = "DXGI_FORMAT_G8R8_G8B8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_TYPELESS"] = 70] = "DXGI_FORMAT_BC1_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_UNORM"] = 71] = "DXGI_FORMAT_BC1_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_UNORM_SRGB"] = 72] = "DXGI_FORMAT_BC1_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_TYPELESS"] = 73] = "DXGI_FORMAT_BC2_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_UNORM"] = 74] = "DXGI_FORMAT_BC2_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_UNORM_SRGB"] = 75] = "DXGI_FORMAT_BC2_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_TYPELESS"] = 76] = "DXGI_FORMAT_BC3_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_UNORM"] = 77] = "DXGI_FORMAT_BC3_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_UNORM_SRGB"] = 78] = "DXGI_FORMAT_BC3_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_TYPELESS"] = 79] = "DXGI_FORMAT_BC4_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_UNORM"] = 80] = "DXGI_FORMAT_BC4_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_SNORM"] = 81] = "DXGI_FORMAT_BC4_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_TYPELESS"] = 82] = "DXGI_FORMAT_BC5_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_UNORM"] = 83] = "DXGI_FORMAT_BC5_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_SNORM"] = 84] = "DXGI_FORMAT_BC5_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B5G6R5_UNORM"] = 85] = "DXGI_FORMAT_B5G6R5_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B5G5R5A1_UNORM"] = 86] = "DXGI_FORMAT_B5G5R5A1_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_UNORM"] = 87] = "DXGI_FORMAT_B8G8R8A8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_UNORM"] = 88] = "DXGI_FORMAT_B8G8R8X8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM"] = 89] = "DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_TYPELESS"] = 90] = "DXGI_FORMAT_B8G8R8A8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_UNORM_SRGB"] = 91] = "DXGI_FORMAT_B8G8R8A8_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_TYPELESS"] = 92] = "DXGI_FORMAT_B8G8R8X8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_UNORM_SRGB"] = 93] = "DXGI_FORMAT_B8G8R8X8_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_TYPELESS"] = 94] = "DXGI_FORMAT_BC6H_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_UF16"] = 95] = "DXGI_FORMAT_BC6H_UF16"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_SF16"] = 96] = "DXGI_FORMAT_BC6H_SF16"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_TYPELESS"] = 97] = "DXGI_FORMAT_BC7_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_UNORM"] = 98] = "DXGI_FORMAT_BC7_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_UNORM_SRGB"] = 99] = "DXGI_FORMAT_BC7_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_AYUV"] = 100] = "DXGI_FORMAT_AYUV"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y410"] = 101] = "DXGI_FORMAT_Y410"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y416"] = 102] = "DXGI_FORMAT_Y416"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_NV12"] = 103] = "DXGI_FORMAT_NV12"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P010"] = 104] = "DXGI_FORMAT_P010"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P016"] = 105] = "DXGI_FORMAT_P016"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_420_OPAQUE"] = 106] = "DXGI_FORMAT_420_OPAQUE"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_YUY2"] = 107] = "DXGI_FORMAT_YUY2"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y210"] = 108] = "DXGI_FORMAT_Y210"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y216"] = 109] = "DXGI_FORMAT_Y216"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_NV11"] = 110] = "DXGI_FORMAT_NV11"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_AI44"] = 111] = "DXGI_FORMAT_AI44"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_IA44"] = 112] = "DXGI_FORMAT_IA44"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P8"] = 113] = "DXGI_FORMAT_P8"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_A8P8"] = 114] = "DXGI_FORMAT_A8P8"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B4G4R4A4_UNORM"] = 115] = "DXGI_FORMAT_B4G4R4A4_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P208"] = 116] = "DXGI_FORMAT_P208"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_V208"] = 117] = "DXGI_FORMAT_V208"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_V408"] = 118] = "DXGI_FORMAT_V408"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE"] = 119] = "DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE"] = 120] = "DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_FORCE_UINT"] = 121] = "DXGI_FORMAT_FORCE_UINT"; + })(DXGI_FORMAT || (DXGI_FORMAT = {})); + /** + * Possible values of the field {@link DDS_DX10_FIELDS.RESOURCE_DIMENSION} + * @ignore + */ + var D3D10_RESOURCE_DIMENSION; + (function (D3D10_RESOURCE_DIMENSION) { + D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE1D"] = 2] = "DDS_DIMENSION_TEXTURE1D"; + D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE2D"] = 3] = "DDS_DIMENSION_TEXTURE2D"; + D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE3D"] = 6] = "DDS_DIMENSION_TEXTURE3D"; + })(D3D10_RESOURCE_DIMENSION || (D3D10_RESOURCE_DIMENSION = {})); + var PF_FLAGS = 1; + // PIXEL_FORMAT flags + var DDPF_ALPHA = 0x2; + var DDPF_FOURCC = 0x4; + var DDPF_RGB = 0x40; + var DDPF_YUV = 0x200; + var DDPF_LUMINANCE = 0x20000; + // Four character codes for DXTn formats + var FOURCC_DXT1 = 0x31545844; + var FOURCC_DXT3 = 0x33545844; + var FOURCC_DXT5 = 0x35545844; + var FOURCC_DX10 = 0x30315844; + // Cubemap texture flag (for DDS_DX10_FIELDS.MISC_FLAG) + var DDS_RESOURCE_MISC_TEXTURECUBE = 0x4; + /** + * Maps `FOURCC_*` formats to internal formats (see {@link PIXI.INTERNAL_FORMATS}). + * @ignore + */ + var FOURCC_TO_FORMAT = (_a$1 = {}, + _a$1[FOURCC_DXT1] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT, + _a$1[FOURCC_DXT3] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT, + _a$1[FOURCC_DXT5] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT, + _a$1); + /** + * Maps {@link DXGI_FORMAT} to types/internal-formats (see {@link PIXI.TYPES}, {@link PIXI.INTERNAL_FORMATS}) + * @ignore + */ + var DXGI_TO_FORMAT = (_b$1 = {}, + // WEBGL_compressed_texture_s3tc + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC1_TYPELESS] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC1_UNORM] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC2_TYPELESS] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC2_UNORM] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC3_TYPELESS] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC3_UNORM] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT, + // WEBGL_compressed_texture_s3tc_srgb + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC1_UNORM_SRGB] = exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC2_UNORM_SRGB] = exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC3_UNORM_SRGB] = exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, + _b$1); + /** + * @class + * @memberof PIXI + * @implements {PIXI.ILoaderPlugin} + * @see https://docs.microsoft.com/en-us/windows/win32/direct3ddds/dx-graphics-dds-pguide + */ + /** + * Parses the DDS file header, generates base-textures, and puts them into the texture cache. + * @param arrayBuffer + */ + function parseDDS(arrayBuffer) { + var data = new Uint32Array(arrayBuffer); + var magicWord = data[0]; + if (magicWord !== DDS_MAGIC) { + throw new Error('Invalid DDS file magic word'); + } + var header = new Uint32Array(arrayBuffer, 0, DDS_HEADER_SIZE / Uint32Array.BYTES_PER_ELEMENT); + // DDS header fields + var height = header[DDS_FIELDS.HEIGHT]; + var width = header[DDS_FIELDS.WIDTH]; + var mipmapCount = header[DDS_FIELDS.MIPMAP_COUNT]; + // PIXEL_FORMAT fields + var pixelFormat = new Uint32Array(arrayBuffer, DDS_FIELDS.PIXEL_FORMAT * Uint32Array.BYTES_PER_ELEMENT, DDS_HEADER_PF_SIZE / Uint32Array.BYTES_PER_ELEMENT); + var formatFlags = pixelFormat[PF_FLAGS]; + // File contains compressed texture(s) + if (formatFlags & DDPF_FOURCC) { + var fourCC = pixelFormat[DDS_PF_FIELDS.FOURCC]; + // File contains one DXTn compressed texture + if (fourCC !== FOURCC_DX10) { + var internalFormat_1 = FOURCC_TO_FORMAT[fourCC]; + var dataOffset_1 = DDS_MAGIC_SIZE + DDS_HEADER_SIZE; + var texData = new Uint8Array(arrayBuffer, dataOffset_1); + var resource = new CompressedTextureResource(texData, { + format: internalFormat_1, + width: width, + height: height, + levels: mipmapCount // CompressedTextureResource will separate the levelBuffers for us! + }); + return [resource]; + } + // FOURCC_DX10 indicates there is a 20-byte DDS_HEADER_DX10 after DDS_HEADER + var dx10Offset = DDS_MAGIC_SIZE + DDS_HEADER_SIZE; + var dx10Header = new Uint32Array(data.buffer, dx10Offset, DDS_HEADER_DX10_SIZE / Uint32Array.BYTES_PER_ELEMENT); + var dxgiFormat = dx10Header[DDS_DX10_FIELDS.DXGI_FORMAT]; + var resourceDimension = dx10Header[DDS_DX10_FIELDS.RESOURCE_DIMENSION]; + var miscFlag = dx10Header[DDS_DX10_FIELDS.MISC_FLAG]; + var arraySize = dx10Header[DDS_DX10_FIELDS.ARRAY_SIZE]; + // Map dxgiFormat to PIXI.INTERNAL_FORMATS + var internalFormat_2 = DXGI_TO_FORMAT[dxgiFormat]; + if (internalFormat_2 === undefined) { + throw new Error("DDSParser cannot parse texture data with DXGI format " + dxgiFormat); + } + if (miscFlag === DDS_RESOURCE_MISC_TEXTURECUBE) { + // FIXME: Anybody excited about cubemap compressed textures? + throw new Error('DDSParser does not support cubemap textures'); + } + if (resourceDimension === D3D10_RESOURCE_DIMENSION.DDS_DIMENSION_TEXTURE3D) { + // FIXME: Anybody excited about 3D compressed textures? + throw new Error('DDSParser does not supported 3D texture data'); + } + // Uint8Array buffers of image data, including all mipmap levels in each image + var imageBuffers = new Array(); + var dataOffset = DDS_MAGIC_SIZE + + DDS_HEADER_SIZE + + DDS_HEADER_DX10_SIZE; + if (arraySize === 1) { + // No need bothering with the imageSize calculation! + imageBuffers.push(new Uint8Array(arrayBuffer, dataOffset)); + } + else { + // Calculate imageSize for each texture, and then locate each image's texture data + var pixelSize = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[internalFormat_2]; + var imageSize = 0; + var levelWidth = width; + var levelHeight = height; + for (var i = 0; i < mipmapCount; i++) { + var alignedLevelWidth = Math.max(1, (levelWidth + 3) & ~3); + var alignedLevelHeight = Math.max(1, (levelHeight + 3) & ~3); + var levelSize = alignedLevelWidth * alignedLevelHeight * pixelSize; + imageSize += levelSize; + levelWidth = levelWidth >>> 1; + levelHeight = levelHeight >>> 1; + } + var imageOffset = dataOffset; + // NOTE: Cubemaps have 6-images per texture (but they aren't supported so ^_^) + for (var i = 0; i < arraySize; i++) { + imageBuffers.push(new Uint8Array(arrayBuffer, imageOffset, imageSize)); + imageOffset += imageSize; + } + } + // Uint8Array -> CompressedTextureResource, and we're done! + return imageBuffers.map(function (buffer) { return new CompressedTextureResource(buffer, { + format: internalFormat_2, + width: width, + height: height, + levels: mipmapCount + }); }); + } + if (formatFlags & DDPF_RGB) { + // FIXME: We might want to allow uncompressed *.dds files? + throw new Error('DDSParser does not support uncompressed texture data.'); + } + if (formatFlags & DDPF_YUV) { + // FIXME: Does anybody need this feature? + throw new Error('DDSParser does not supported YUV uncompressed texture data.'); + } + if (formatFlags & DDPF_LUMINANCE) { + // FIXME: Microsoft says older DDS filers use this feature! Probably not worth the effort! + throw new Error('DDSParser does not support single-channel (lumninance) texture data!'); + } + if (formatFlags & DDPF_ALPHA) { + // FIXME: I'm tired! See above =) + throw new Error('DDSParser does not support single-channel (alpha) texture data!'); + } + throw new Error('DDSParser failed to load a texture file due to an unknown reason!'); + } - // Objects with mutliple textures - if (item && item._textures && item._textures.length) { - for (var i = 0; i < item._textures.length; i++) { - if (item._textures[i] instanceof core.Texture) { - var baseTexture = item._textures[i].baseTexture; + var _a$3, _b, _c; + /** + * The 12-byte KTX file identifier + * @see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/#2.1 + * @ignore + */ + var FILE_IDENTIFIER = [0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A]; + /** + * The value stored in the "endianness" field. + * @see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/#2.2 + * @ignore + */ + var ENDIANNESS = 0x04030201; + /** + * Byte offsets of the KTX file header fields + * @ignore + */ + var KTX_FIELDS = { + FILE_IDENTIFIER: 0, + ENDIANNESS: 12, + GL_TYPE: 16, + GL_TYPE_SIZE: 20, + GL_FORMAT: 24, + GL_INTERNAL_FORMAT: 28, + GL_BASE_INTERNAL_FORMAT: 32, + PIXEL_WIDTH: 36, + PIXEL_HEIGHT: 40, + PIXEL_DEPTH: 44, + NUMBER_OF_ARRAY_ELEMENTS: 48, + NUMBER_OF_FACES: 52, + NUMBER_OF_MIPMAP_LEVELS: 56, + BYTES_OF_KEY_VALUE_DATA: 60 + }; + /** + * Byte size of the file header fields in {@code KTX_FIELDS} + * @ignore + */ + var FILE_HEADER_SIZE = 64; + /** + * Maps {@link PIXI.TYPES} to the bytes taken per component, excluding those ones that are bit-fields. + * @ignore + */ + var TYPES_TO_BYTES_PER_COMPONENT = (_a$3 = {}, + _a$3[exports.TYPES.UNSIGNED_BYTE] = 1, + _a$3[exports.TYPES.UNSIGNED_SHORT] = 2, + _a$3[exports.TYPES.INT] = 4, + _a$3[exports.TYPES.UNSIGNED_INT] = 4, + _a$3[exports.TYPES.FLOAT] = 4, + _a$3[exports.TYPES.HALF_FLOAT] = 8, + _a$3); + /** + * Number of components in each {@link PIXI.FORMATS} + * @ignore + */ + var FORMATS_TO_COMPONENTS = (_b = {}, + _b[exports.FORMATS.RGBA] = 4, + _b[exports.FORMATS.RGB] = 3, + _b[exports.FORMATS.RG] = 2, + _b[exports.FORMATS.RED] = 1, + _b[exports.FORMATS.LUMINANCE] = 1, + _b[exports.FORMATS.LUMINANCE_ALPHA] = 2, + _b[exports.FORMATS.ALPHA] = 1, + _b); + /** + * Number of bytes per pixel in bit-field types in {@link PIXI.TYPES} + * @ignore + */ + var TYPES_TO_BYTES_PER_PIXEL = (_c = {}, + _c[exports.TYPES.UNSIGNED_SHORT_4_4_4_4] = 2, + _c[exports.TYPES.UNSIGNED_SHORT_5_5_5_1] = 2, + _c[exports.TYPES.UNSIGNED_SHORT_5_6_5] = 2, + _c); + function parseKTX(url, arrayBuffer, loadKeyValueData) { + if (loadKeyValueData === void 0) { loadKeyValueData = false; } + var dataView = new DataView(arrayBuffer); + if (!validate(url, dataView)) { + return null; + } + var littleEndian = dataView.getUint32(KTX_FIELDS.ENDIANNESS, true) === ENDIANNESS; + var glType = dataView.getUint32(KTX_FIELDS.GL_TYPE, littleEndian); + // const glTypeSize = dataView.getUint32(KTX_FIELDS.GL_TYPE_SIZE, littleEndian); + var glFormat = dataView.getUint32(KTX_FIELDS.GL_FORMAT, littleEndian); + var glInternalFormat = dataView.getUint32(KTX_FIELDS.GL_INTERNAL_FORMAT, littleEndian); + var pixelWidth = dataView.getUint32(KTX_FIELDS.PIXEL_WIDTH, littleEndian); + var pixelHeight = dataView.getUint32(KTX_FIELDS.PIXEL_HEIGHT, littleEndian) || 1; // "pixelHeight = 0" -> "1" + var pixelDepth = dataView.getUint32(KTX_FIELDS.PIXEL_DEPTH, littleEndian) || 1; // ^^ + var numberOfArrayElements = dataView.getUint32(KTX_FIELDS.NUMBER_OF_ARRAY_ELEMENTS, littleEndian) || 1; // ^^ + var numberOfFaces = dataView.getUint32(KTX_FIELDS.NUMBER_OF_FACES, littleEndian); + var numberOfMipmapLevels = dataView.getUint32(KTX_FIELDS.NUMBER_OF_MIPMAP_LEVELS, littleEndian); + var bytesOfKeyValueData = dataView.getUint32(KTX_FIELDS.BYTES_OF_KEY_VALUE_DATA, littleEndian); + // Whether the platform architecture is little endian. If littleEndian !== platformLittleEndian, then the + // file contents must be endian-converted! + // TODO: Endianness conversion + // const platformLittleEndian = new Uint8Array((new Uint32Array([ENDIANNESS])).buffer)[0] === 0x01; + if (pixelHeight === 0 || pixelDepth !== 1) { + throw new Error('Only 2D textures are supported'); + } + if (numberOfFaces !== 1) { + throw new Error('CubeTextures are not supported by KTXLoader yet!'); + } + if (numberOfArrayElements !== 1) { + // TODO: Support splitting array-textures into multiple BaseTextures + throw new Error('WebGL does not support array textures'); + } + // TODO: 8x4 blocks for 2bpp pvrtc + var blockWidth = 4; + var blockHeight = 4; + var alignedWidth = (pixelWidth + 3) & ~3; + var alignedHeight = (pixelHeight + 3) & ~3; + var imageBuffers = new Array(numberOfArrayElements); + var imagePixels = pixelWidth * pixelHeight; + if (glType === 0) { + // Align to 16 pixels (4x4 blocks) + imagePixels = alignedWidth * alignedHeight; + } + var imagePixelByteSize; + if (glType !== 0) { + // Uncompressed texture format + if (TYPES_TO_BYTES_PER_COMPONENT[glType]) { + imagePixelByteSize = TYPES_TO_BYTES_PER_COMPONENT[glType] * FORMATS_TO_COMPONENTS[glFormat]; + } + else { + imagePixelByteSize = TYPES_TO_BYTES_PER_PIXEL[glType]; + } + } + else { + imagePixelByteSize = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[glInternalFormat]; + } + if (imagePixelByteSize === undefined) { + throw new Error('Unable to resolve the pixel format stored in the *.ktx file!'); + } + var kvData = loadKeyValueData + ? parseKvData(dataView, bytesOfKeyValueData, littleEndian) + : null; + var imageByteSize = imagePixels * imagePixelByteSize; + var mipByteSize = imageByteSize; + var mipWidth = pixelWidth; + var mipHeight = pixelHeight; + var alignedMipWidth = alignedWidth; + var alignedMipHeight = alignedHeight; + var imageOffset = FILE_HEADER_SIZE + bytesOfKeyValueData; + for (var mipmapLevel = 0; mipmapLevel < numberOfMipmapLevels; mipmapLevel++) { + var imageSize = dataView.getUint32(imageOffset, littleEndian); + var elementOffset = imageOffset + 4; + for (var arrayElement = 0; arrayElement < numberOfArrayElements; arrayElement++) { + // TODO: Maybe support 3D textures? :-) + // for (let zSlice = 0; zSlice < pixelDepth; zSlice) + var mips = imageBuffers[arrayElement]; + if (!mips) { + mips = imageBuffers[arrayElement] = new Array(numberOfMipmapLevels); + } + mips[mipmapLevel] = { + levelID: mipmapLevel, + // don't align mipWidth when texture not compressed! (glType not zero) + levelWidth: numberOfMipmapLevels > 1 || glType !== 0 ? mipWidth : alignedMipWidth, + levelHeight: numberOfMipmapLevels > 1 || glType !== 0 ? mipHeight : alignedMipHeight, + levelBuffer: new Uint8Array(arrayBuffer, elementOffset, mipByteSize) + }; + elementOffset += mipByteSize; + } + // HINT: Aligns to 4-byte boundary after jumping imageSize (in lieu of mipPadding) + imageOffset += imageSize + 4; // (+4 to jump the imageSize field itself) + imageOffset = imageOffset % 4 !== 0 ? imageOffset + 4 - (imageOffset % 4) : imageOffset; + // Calculate mipWidth, mipHeight for _next_ iteration + mipWidth = (mipWidth >> 1) || 1; + mipHeight = (mipHeight >> 1) || 1; + alignedMipWidth = (mipWidth + blockWidth - 1) & ~(blockWidth - 1); + alignedMipHeight = (mipHeight + blockHeight - 1) & ~(blockHeight - 1); + // Each mipmap level is 4-times smaller? + mipByteSize = alignedMipWidth * alignedMipHeight * imagePixelByteSize; + } + // We use the levelBuffers feature of CompressedTextureResource b/c texture data is image-major, not level-major. + if (glType !== 0) { + return { + uncompressed: imageBuffers.map(function (levelBuffers) { + var buffer = levelBuffers[0].levelBuffer; + var convertToInt = false; + if (glType === exports.TYPES.FLOAT) { + buffer = new Float32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4); + } + else if (glType === exports.TYPES.UNSIGNED_INT) { + convertToInt = true; + buffer = new Uint32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4); + } + else if (glType === exports.TYPES.INT) { + convertToInt = true; + buffer = new Int32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4); + } + return { + resource: new BufferResource(buffer, { + width: levelBuffers[0].levelWidth, + height: levelBuffers[0].levelHeight, + }), + type: glType, + format: convertToInt ? convertFormatToInteger(glFormat) : glFormat, + }; + }), + kvData: kvData + }; + } + return { + compressed: imageBuffers.map(function (levelBuffers) { return new CompressedTextureResource(null, { + format: glInternalFormat, + width: pixelWidth, + height: pixelHeight, + levels: numberOfMipmapLevels, + levelBuffers: levelBuffers, + }); }), + kvData: kvData + }; + } + /** + * Checks whether the arrayBuffer contains a valid *.ktx file. + * @param url + * @param dataView + */ + function validate(url, dataView) { + // NOTE: Do not optimize this into 3 32-bit integer comparison because the endianness + // of the data is not specified. + for (var i = 0; i < FILE_IDENTIFIER.length; i++) { + if (dataView.getUint8(i) !== FILE_IDENTIFIER[i]) { + console.error(url + " is not a valid *.ktx file!"); + return false; + } + } + return true; + } + function convertFormatToInteger(format) { + switch (format) { + case exports.FORMATS.RGBA: return exports.FORMATS.RGBA_INTEGER; + case exports.FORMATS.RGB: return exports.FORMATS.RGB_INTEGER; + case exports.FORMATS.RG: return exports.FORMATS.RG_INTEGER; + case exports.FORMATS.RED: return exports.FORMATS.RED_INTEGER; + default: return format; + } + } + function parseKvData(dataView, bytesOfKeyValueData, littleEndian) { + var kvData = new Map(); + var bytesIntoKeyValueData = 0; + while (bytesIntoKeyValueData < bytesOfKeyValueData) { + var keyAndValueByteSize = dataView.getUint32(FILE_HEADER_SIZE + bytesIntoKeyValueData, littleEndian); + var keyAndValueByteOffset = FILE_HEADER_SIZE + bytesIntoKeyValueData + 4; + var valuePadding = 3 - ((keyAndValueByteSize + 3) % 4); + // Bounds check + if (keyAndValueByteSize === 0 || keyAndValueByteSize > bytesOfKeyValueData - bytesIntoKeyValueData) { + console.error('KTXLoader: keyAndValueByteSize out of bounds'); + break; + } + // Note: keyNulByte can't be 0 otherwise the key is an empty string. + var keyNulByte = 0; + for (; keyNulByte < keyAndValueByteSize; keyNulByte++) { + if (dataView.getUint8(keyAndValueByteOffset + keyNulByte) === 0x00) { + break; + } + } + if (keyNulByte === -1) { + console.error('KTXLoader: Failed to find null byte terminating kvData key'); + break; + } + var key = new TextDecoder().decode(new Uint8Array(dataView.buffer, keyAndValueByteOffset, keyNulByte)); + var value = new DataView(dataView.buffer, keyAndValueByteOffset + keyNulByte + 1, keyAndValueByteSize - keyNulByte - 1); + kvData.set(key, value); + // 4 = the keyAndValueByteSize field itself + // keyAndValueByteSize = the bytes taken by the key and value + // valuePadding = extra padding to align with 4 bytes + bytesIntoKeyValueData += 4 + keyAndValueByteSize + valuePadding; + } + return kvData; + } - if (queue.indexOf(baseTexture) === -1) { - queue.push(baseTexture); - result = true; - } - } - } - } + // Set DDS files to be loaded as an ArrayBuffer + exports.LoaderResource.setExtensionXhrType('dds', exports.LoaderResource.XHR_RESPONSE_TYPE.BUFFER); + /** + * @class + * @memberof PIXI + * @implements {PIXI.ILoaderPlugin} + * @see https://docs.microsoft.com/en-us/windows/win32/direct3ddds/dx-graphics-dds-pguide + */ + var DDSLoader = /** @class */ (function () { + function DDSLoader() { + } + /** + * Registers a DDS compressed texture + * @see PIXI.Loader.loaderMiddleware + * @param resource - loader resource that is checked to see if it is a DDS file + * @param next - callback Function to call when done + */ + DDSLoader.use = function (resource, next) { + if (resource.extension === 'dds' && resource.data) { + try { + Object.assign(resource, registerCompressedTextures(resource.name || resource.url, parseDDS(resource.data), resource.metadata)); + } + catch (err) { + next(err); + return; + } + } + next(); + }; + /** @ignore */ + DDSLoader.extension = exports.ExtensionType.Loader; + return DDSLoader; + }()); + + // Set KTX files to be loaded as an ArrayBuffer + exports.LoaderResource.setExtensionXhrType('ktx', exports.LoaderResource.XHR_RESPONSE_TYPE.BUFFER); + /** + * Loader plugin for handling KTX texture container files. + * + * This KTX loader does not currently support the following features: + * * cube textures + * * 3D textures + * * endianness conversion for big-endian machines + * * embedded *.basis files + * + * It does supports the following features: + * * multiple textures per file + * * mipmapping (only for compressed formats) + * * vendor-specific key/value data parsing (enable {@link PIXI.KTXLoader.loadKeyValueData}) + * @class + * @memberof PIXI + * @implements {PIXI.ILoaderPlugin} + */ + var KTXLoader = /** @class */ (function () { + function KTXLoader() { + } + /** + * Called after a KTX file is loaded. + * + * This will parse the KTX file header and add a {@code BaseTexture} to the texture + * cache. + * @see PIXI.Loader.loaderMiddleware + * @param resource - loader resource that is checked to see if it is a KTX file + * @param next - callback Function to call when done + */ + KTXLoader.use = function (resource, next) { + if (resource.extension === 'ktx' && resource.data) { + try { + var url_1 = resource.name || resource.url; + var _a = parseKTX(url_1, resource.data, this.loadKeyValueData), compressed = _a.compressed, uncompressed = _a.uncompressed, kvData_1 = _a.kvData; + if (compressed) { + var result = registerCompressedTextures(url_1, compressed, resource.metadata); + if (kvData_1 && result.textures) { + for (var textureId in result.textures) { + result.textures[textureId].baseTexture.ktxKeyValueData = kvData_1; + } + } + Object.assign(resource, result); + } + else if (uncompressed) { + var textures_1 = {}; + uncompressed.forEach(function (image, i) { + var texture = new Texture(new BaseTexture(image.resource, { + mipmap: exports.MIPMAP_MODES.OFF, + alphaMode: exports.ALPHA_MODES.NO_PREMULTIPLIED_ALPHA, + type: image.type, + format: image.format, + })); + var cacheID = url_1 + "-" + (i + 1); + if (kvData_1) + { texture.baseTexture.ktxKeyValueData = kvData_1; } + BaseTexture.addToCache(texture.baseTexture, cacheID); + Texture.addToCache(texture, cacheID); + if (i === 0) { + textures_1[url_1] = texture; + BaseTexture.addToCache(texture.baseTexture, url_1); + Texture.addToCache(texture, url_1); + } + textures_1[cacheID] = texture; + }); + Object.assign(resource, { textures: textures_1 }); + } + } + catch (err) { + next(err); + return; + } + } + next(); + }; + /** @ignore */ + KTXLoader.extension = exports.ExtensionType.Loader; + /** + * If set to `true`, {@link PIXI.KTXLoader} will parse key-value data in KTX textures. This feature relies + * on the [Encoding Standard]{@link https://encoding.spec.whatwg.org}. + * + * The key-value data will be available on the base-textures as {@code PIXI.BaseTexture.ktxKeyValueData}. They + * will hold a reference to the texture data buffer, so make sure to delete key-value data once you are done + * using it. + */ + KTXLoader.loadKeyValueData = false; + return KTXLoader; + }()); - return result; -} + /*! + * @pixi/particle-container - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/particle-container is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ -/** - * Built-in hook to find BaseTextures from Sprites. - * - * @private - * @param {PIXI.DisplayObject} item - Display object to check - * @param {Array<*>} queue - Collection of items to upload - * @return {boolean} if a PIXI.Texture object was found. - */ -function findBaseTexture(item, queue) { - // Objects with textures, like Sprites/Text - if (item instanceof core.BaseTexture) { - if (queue.indexOf(item) === -1) { - queue.push(item); - } + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$f = function(d, b) { + extendStatics$f = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$f(d, b); + }; - return true; - } + function __extends$f(d, b) { + extendStatics$f(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } - return false; -} + /** + * The ParticleContainer class is a really fast version of the Container built solely for speed, + * so use when you need a lot of sprites or particles. + * + * The tradeoff of the ParticleContainer is that most advanced functionality will not work. + * ParticleContainer implements the basic object transform (position, scale, rotation) + * and some advanced functionality like tint (as of v4.5.6). + * + * Other more advanced functionality like masking, children, filters, etc will not work on sprites in this batch. + * + * It's extremely easy to use: + * ```js + * let container = new ParticleContainer(); + * + * for (let i = 0; i < 100; ++i) + * { + * let sprite = PIXI.Sprite.from("myImage.png"); + * container.addChild(sprite); + * } + * ``` + * + * And here you have a hundred sprites that will be rendered at the speed of light. + * @memberof PIXI + */ + var ParticleContainer = /** @class */ (function (_super) { + __extends$f(ParticleContainer, _super); + /** + * @param maxSize - The maximum number of particles that can be rendered by the container. + * Affects size of allocated buffers. + * @param properties - The properties of children that should be uploaded to the gpu and applied. + * @param {boolean} [properties.vertices=false] - When true, vertices be uploaded and applied. + * if sprite's ` scale/anchor/trim/frame/orig` is dynamic, please set `true`. + * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. + * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. + * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. + * @param {boolean} [properties.tint=false] - When true, alpha and tint be uploaded and applied. + * @param {number} [batchSize=16384] - Number of particles per batch. If less than maxSize, it uses maxSize instead. + * @param {boolean} [autoResize=false] - If true, container allocates more batches in case + * there are more than `maxSize` particles. + */ + function ParticleContainer(maxSize, properties, batchSize, autoResize) { + if (maxSize === void 0) { maxSize = 1500; } + if (batchSize === void 0) { batchSize = 16384; } + if (autoResize === void 0) { autoResize = false; } + var _this = _super.call(this) || this; + // Making sure the batch size is valid + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + var maxBatchSize = 16384; + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } + _this._properties = [false, true, false, false, false]; + _this._maxSize = maxSize; + _this._batchSize = batchSize; + _this._buffers = null; + _this._bufferUpdateIDs = []; + _this._updateID = 0; + _this.interactiveChildren = false; + _this.blendMode = exports.BLEND_MODES.NORMAL; + _this.autoResize = autoResize; + _this.roundPixels = true; + _this.baseTexture = null; + _this.setProperties(properties); + _this._tint = 0; + _this.tintRgb = new Float32Array(4); + _this.tint = 0xFFFFFF; + return _this; + } + /** + * Sets the private properties array to dynamic / static based on the passed properties object + * @param properties - The properties to be uploaded + */ + ParticleContainer.prototype.setProperties = function (properties) { + if (properties) { + this._properties[0] = 'vertices' in properties || 'scale' in properties + ? !!properties.vertices || !!properties.scale : this._properties[0]; + this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; + this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = 'tint' in properties || 'alpha' in properties + ? !!properties.tint || !!properties.alpha : this._properties[4]; + } + }; + ParticleContainer.prototype.updateTransform = function () { + // TODO don't need to! + this.displayObjectUpdateTransform(); + }; + Object.defineProperty(ParticleContainer.prototype, "tint", { + /** + * The tint applied to the container. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + * IMPORTANT: This is a WebGL only feature and will be ignored by the canvas renderer. + * @default 0xFFFFFF + */ + get: function () { + return this._tint; + }, + set: function (value) { + this._tint = value; + hex2rgb(value, this.tintRgb); + }, + enumerable: false, + configurable: true + }); + /** + * Renders the container using the WebGL renderer. + * @param renderer - The WebGL renderer. + */ + ParticleContainer.prototype.render = function (renderer) { + var _this = this; + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + if (!this.baseTexture) { + this.baseTexture = this.children[0]._texture.baseTexture; + if (!this.baseTexture.valid) { + this.baseTexture.once('update', function () { return _this.onChildrenChange(0); }); + } + } + renderer.batch.setObjectRenderer(renderer.plugins.particle); + renderer.plugins.particle.render(this); + }; + /** + * Set the flag that static data should be updated to true + * @param smallestChildIndex - The smallest child index. + */ + ParticleContainer.prototype.onChildrenChange = function (smallestChildIndex) { + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + while (this._bufferUpdateIDs.length < bufferIndex) { + this._bufferUpdateIDs.push(0); + } + this._bufferUpdateIDs[bufferIndex] = ++this._updateID; + }; + ParticleContainer.prototype.dispose = function () { + if (this._buffers) { + for (var i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + this._buffers = null; + } + }; + /** + * Destroys the container + * @param options - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + ParticleContainer.prototype.destroy = function (options) { + _super.prototype.destroy.call(this, options); + this.dispose(); + this._properties = null; + this._buffers = null; + this._bufferUpdateIDs = null; + }; + return ParticleContainer; + }(Container)); + + /* + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that + * they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleBuffer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + */ + /** + * The particle buffer manages the static and dynamic buffers for a particle container. + * @private + * @memberof PIXI + */ + var ParticleBuffer = /** @class */ (function () { + /** + * @param {object} properties - The properties to upload. + * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. + * @param {number} size - The size of the batch. + */ + function ParticleBuffer(properties, dynamicPropertyFlags, size) { + this.geometry = new Geometry(); + this.indexBuffer = null; + this.size = size; + this.dynamicProperties = []; + this.staticProperties = []; + for (var i = 0; i < properties.length; ++i) { + var property = properties[i]; + // Make copy of properties object so that when we edit the offset it doesn't + // change all other instances of the object literal + property = { + attributeName: property.attributeName, + size: property.size, + uploadFunction: property.uploadFunction, + type: property.type || exports.TYPES.FLOAT, + offset: property.offset, + }; + if (dynamicPropertyFlags[i]) { + this.dynamicProperties.push(property); + } + else { + this.staticProperties.push(property); + } + } + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + this._updateID = 0; + this.initBuffers(); + } + /** Sets up the renderer context and necessary buffers. */ + ParticleBuffer.prototype.initBuffers = function () { + var geometry = this.geometry; + var dynamicOffset = 0; + this.indexBuffer = new Buffer(createIndicesForQuads(this.size), true, true); + geometry.addIndex(this.indexBuffer); + this.dynamicStride = 0; + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + var dynBuffer = new ArrayBuffer(this.size * this.dynamicStride * 4 * 4); + this.dynamicData = new Float32Array(dynBuffer); + this.dynamicDataUint32 = new Uint32Array(dynBuffer); + this.dynamicBuffer = new Buffer(this.dynamicData, false, false); + // static // + var staticOffset = 0; + this.staticStride = 0; + for (var i = 0; i < this.staticProperties.length; ++i) { + var property = this.staticProperties[i]; + property.offset = staticOffset; + staticOffset += property.size; + this.staticStride += property.size; + } + var statBuffer = new ArrayBuffer(this.size * this.staticStride * 4 * 4); + this.staticData = new Float32Array(statBuffer); + this.staticDataUint32 = new Uint32Array(statBuffer); + this.staticBuffer = new Buffer(this.staticData, true, false); + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + geometry.addAttribute(property.attributeName, this.dynamicBuffer, 0, property.type === exports.TYPES.UNSIGNED_BYTE, property.type, this.dynamicStride * 4, property.offset * 4); + } + for (var i = 0; i < this.staticProperties.length; ++i) { + var property = this.staticProperties[i]; + geometry.addAttribute(property.attributeName, this.staticBuffer, 0, property.type === exports.TYPES.UNSIGNED_BYTE, property.type, this.staticStride * 4, property.offset * 4); + } + }; + /** + * Uploads the dynamic properties. + * @param children - The children to upload. + * @param startIndex - The index to start at. + * @param amount - The number to upload. + */ + ParticleBuffer.prototype.uploadDynamic = function (children, startIndex, amount) { + for (var i = 0; i < this.dynamicProperties.length; i++) { + var property = this.dynamicProperties[i]; + property.uploadFunction(children, startIndex, amount, property.type === exports.TYPES.UNSIGNED_BYTE ? this.dynamicDataUint32 : this.dynamicData, this.dynamicStride, property.offset); + } + this.dynamicBuffer._updateID++; + }; + /** + * Uploads the static properties. + * @param children - The children to upload. + * @param startIndex - The index to start at. + * @param amount - The number to upload. + */ + ParticleBuffer.prototype.uploadStatic = function (children, startIndex, amount) { + for (var i = 0; i < this.staticProperties.length; i++) { + var property = this.staticProperties[i]; + property.uploadFunction(children, startIndex, amount, property.type === exports.TYPES.UNSIGNED_BYTE ? this.staticDataUint32 : this.staticData, this.staticStride, property.offset); + } + this.staticBuffer._updateID++; + }; + /** Destroys the ParticleBuffer. */ + ParticleBuffer.prototype.destroy = function () { + this.indexBuffer = null; + this.dynamicProperties = null; + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + this.staticProperties = null; + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + // all buffers are destroyed inside geometry + this.geometry.destroy(); + }; + return ParticleBuffer; + }()); + + var fragment$6 = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n vec4 color = texture2D(uSampler, vTextureCoord) * vColor;\n gl_FragColor = color;\n}"; + + var vertex$3 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\n\nattribute vec2 aPositionCoord;\nattribute float aRotation;\n\nuniform mat3 translationMatrix;\nuniform vec4 uColor;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nvoid main(void){\n float x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);\n float y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);\n\n vec2 v = vec2(x, y);\n v = v + aPositionCoord;\n\n gl_Position = vec4((translationMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vColor = aColor * uColor;\n}\n"; + + /* + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java + */ + /** + * Renderer for Particles that is designer for speed over feature set. + * @memberof PIXI + */ + var ParticleRenderer = /** @class */ (function (_super) { + __extends$f(ParticleRenderer, _super); + /** + * @param renderer - The renderer this sprite batch works for. + */ + function ParticleRenderer(renderer) { + var _this = _super.call(this, renderer) || this; + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + // and max number of element in the index buffer is 16384 * 6 = 98304 + // Creating a full index buffer, overhead is 98304 * 2 = 196Ko + // let numIndices = 98304; + _this.shader = null; + _this.properties = null; + _this.tempMatrix = new Matrix(); + _this.properties = [ + // verticesData + { + attributeName: 'aVertexPosition', + size: 2, + uploadFunction: _this.uploadVertices, + offset: 0, + }, + // positionData + { + attributeName: 'aPositionCoord', + size: 2, + uploadFunction: _this.uploadPosition, + offset: 0, + }, + // rotationData + { + attributeName: 'aRotation', + size: 1, + uploadFunction: _this.uploadRotation, + offset: 0, + }, + // uvsData + { + attributeName: 'aTextureCoord', + size: 2, + uploadFunction: _this.uploadUvs, + offset: 0, + }, + // tintData + { + attributeName: 'aColor', + size: 1, + type: exports.TYPES.UNSIGNED_BYTE, + uploadFunction: _this.uploadTint, + offset: 0, + } ]; + _this.shader = Shader.from(vertex$3, fragment$6, {}); + _this.state = State.for2d(); + return _this; + } + /** + * Renders the particle container object. + * @param container - The container to render using this ParticleRenderer. + */ + ParticleRenderer.prototype.render = function (container) { + var children = container.children; + var maxSize = container._maxSize; + var batchSize = container._batchSize; + var renderer = this.renderer; + var totalChildren = children.length; + if (totalChildren === 0) { + return; + } + else if (totalChildren > maxSize && !container.autoResize) { + totalChildren = maxSize; + } + var buffers = container._buffers; + if (!buffers) { + buffers = container._buffers = this.generateBuffers(container); + } + var baseTexture = children[0]._texture.baseTexture; + var premultiplied = baseTexture.alphaMode > 0; + // if the uvs have not updated then no point rendering just yet! + this.state.blendMode = correctBlendMode(container.blendMode, premultiplied); + renderer.state.set(this.state); + var gl = renderer.gl; + var m = container.worldTransform.copyTo(this.tempMatrix); + m.prepend(renderer.globalUniforms.uniforms.projectionMatrix); + this.shader.uniforms.translationMatrix = m.toArray(true); + this.shader.uniforms.uColor = premultiplyRgba(container.tintRgb, container.worldAlpha, this.shader.uniforms.uColor, premultiplied); + this.shader.uniforms.uSampler = baseTexture; + this.renderer.shader.bind(this.shader); + var updateStatic = false; + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { + var amount = (totalChildren - i); + if (amount > batchSize) { + amount = batchSize; + } + if (j >= buffers.length) { + buffers.push(this._generateOneMoreBuffer(container)); + } + var buffer = buffers[j]; + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); + var bid = container._bufferUpdateIDs[j] || 0; + updateStatic = updateStatic || (buffer._updateID < bid); + // we only upload the static content when we have to! + if (updateStatic) { + buffer._updateID = container._updateID; + buffer.uploadStatic(children, i, amount); + } + // bind the buffer + renderer.geometry.bind(buffer.geometry); + gl.drawElements(gl.TRIANGLES, amount * 6, gl.UNSIGNED_SHORT, 0); + } + }; + /** + * Creates one particle buffer for each child in the container we want to render and updates internal properties. + * @param container - The container to render using this ParticleRenderer + * @returns - The buffers + */ + ParticleRenderer.prototype.generateBuffers = function (container) { + var buffers = []; + var size = container._maxSize; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + for (var i = 0; i < size; i += batchSize) { + buffers.push(new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize)); + } + return buffers; + }; + /** + * Creates one more particle buffer, because container has autoResize feature. + * @param container - The container to render using this ParticleRenderer + * @returns - The generated buffer + */ + ParticleRenderer.prototype._generateOneMoreBuffer = function (container) { + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + return new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize); + }; + /** + * Uploads the vertices. + * @param children - the array of sprites to render + * @param startIndex - the index to start from in the children array + * @param amount - the amount of children that will have their vertices uploaded + * @param array - The vertices to upload. + * @param stride - Stride to use for iteration. + * @param offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadVertices = function (children, startIndex, amount, array, stride, offset) { + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var texture = sprite._texture; + var sx = sprite.scale.x; + var sy = sprite.scale.y; + var trim = texture.trim; + var orig = texture.orig; + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the + // extra space before transforming the sprite coords.. + w1 = trim.x - (sprite.anchor.x * orig.width); + w0 = w1 + trim.width; + h1 = trim.y - (sprite.anchor.y * orig.height); + h0 = h1 + trim.height; + } + else { + w0 = (orig.width) * (1 - sprite.anchor.x); + w1 = (orig.width) * -sprite.anchor.x; + h0 = orig.height * (1 - sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + array[offset + (stride * 2)] = w0 * sx; + array[offset + (stride * 2) + 1] = h0 * sy; + array[offset + (stride * 3)] = w1 * sx; + array[offset + (stride * 3) + 1] = h0 * sy; + offset += stride * 4; + } + }; + /** + * Uploads the position. + * @param children - the array of sprites to render + * @param startIndex - the index to start from in the children array + * @param amount - the amount of children that will have their positions uploaded + * @param array - The vertices to upload. + * @param stride - Stride to use for iteration. + * @param offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadPosition = function (children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spritePosition = children[startIndex + i].position; + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + array[offset + (stride * 2)] = spritePosition.x; + array[offset + (stride * 2) + 1] = spritePosition.y; + array[offset + (stride * 3)] = spritePosition.x; + array[offset + (stride * 3) + 1] = spritePosition.y; + offset += stride * 4; + } + }; + /** + * Uploads the rotation. + * @param children - the array of sprites to render + * @param startIndex - the index to start from in the children array + * @param amount - the amount of children that will have their rotation uploaded + * @param array - The vertices to upload. + * @param stride - Stride to use for iteration. + * @param offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadRotation = function (children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteRotation = children[startIndex + i].rotation; + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + (stride * 2)] = spriteRotation; + array[offset + (stride * 3)] = spriteRotation; + offset += stride * 4; + } + }; + /** + * Uploads the UVs. + * @param children - the array of sprites to render + * @param startIndex - the index to start from in the children array + * @param amount - the amount of children that will have their rotation uploaded + * @param array - The vertices to upload. + * @param stride - Stride to use for iteration. + * @param offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadUvs = function (children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var textureUvs = children[startIndex + i]._texture._uvs; + if (textureUvs) { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + array[offset + (stride * 2)] = textureUvs.x2; + array[offset + (stride * 2) + 1] = textureUvs.y2; + array[offset + (stride * 3)] = textureUvs.x3; + array[offset + (stride * 3) + 1] = textureUvs.y3; + offset += stride * 4; + } + else { + // TODO you know this can be easier! + array[offset] = 0; + array[offset + 1] = 0; + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + array[offset + (stride * 2)] = 0; + array[offset + (stride * 2) + 1] = 0; + array[offset + (stride * 3)] = 0; + array[offset + (stride * 3) + 1] = 0; + offset += stride * 4; + } + } + }; + /** + * Uploads the tint. + * @param children - the array of sprites to render + * @param startIndex - the index to start from in the children array + * @param amount - the amount of children that will have their rotation uploaded + * @param array - The vertices to upload. + * @param stride - Stride to use for iteration. + * @param offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadTint = function (children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var premultiplied = sprite._texture.baseTexture.alphaMode > 0; + var alpha = sprite.alpha; + // we dont call extra function if alpha is 1.0, that's faster + var argb = alpha < 1.0 && premultiplied + ? premultiplyTint(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); + array[offset] = argb; + array[offset + stride] = argb; + array[offset + (stride * 2)] = argb; + array[offset + (stride * 3)] = argb; + offset += stride * 4; + } + }; + /** Destroys the ParticleRenderer. */ + ParticleRenderer.prototype.destroy = function () { + _super.prototype.destroy.call(this); + if (this.shader) { + this.shader.destroy(); + this.shader = null; + } + this.tempMatrix = null; + }; + /** @ignore */ + ParticleRenderer.extension = { + name: 'particle', + type: exports.ExtensionType.RendererPlugin, + }; + return ParticleRenderer; + }(ObjectRenderer)); + + /*! + * @pixi/graphics - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/graphics is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ -/** - * Built-in hook to find textures from objects. - * - * @private - * @param {PIXI.DisplayObject} item - Display object to check - * @param {Array<*>} queue - Collection of items to upload - * @return {boolean} if a PIXI.Texture object was found. - */ -function findTexture(item, queue) { - if (item._texture && item._texture instanceof core.Texture) { - var texture = item._texture.baseTexture; + /** + * Supported line joints in `PIXI.LineStyle` for graphics. + * @see PIXI.Graphics#lineStyle + * @see https://graphicdesign.stackexchange.com/questions/59018/what-is-a-bevel-join-of-two-lines-exactly-illustrator + * @name LINE_JOIN + * @memberof PIXI + * @static + * @enum {string} + * @property {string} MITER - 'miter': make a sharp corner where outer part of lines meet + * @property {string} BEVEL - 'bevel': add a square butt at each end of line segment and fill the triangle at turn + * @property {string} ROUND - 'round': add an arc at the joint + */ + exports.LINE_JOIN = void 0; + (function (LINE_JOIN) { + LINE_JOIN["MITER"] = "miter"; + LINE_JOIN["BEVEL"] = "bevel"; + LINE_JOIN["ROUND"] = "round"; + })(exports.LINE_JOIN || (exports.LINE_JOIN = {})); + /** + * Support line caps in `PIXI.LineStyle` for graphics. + * @see PIXI.Graphics#lineStyle + * @name LINE_CAP + * @memberof PIXI + * @static + * @enum {string} + * @property {string} BUTT - 'butt': don't add any cap at line ends (leaves orthogonal edges) + * @property {string} ROUND - 'round': add semicircle at ends + * @property {string} SQUARE - 'square': add square at end (like `BUTT` except more length at end) + */ + exports.LINE_CAP = void 0; + (function (LINE_CAP) { + LINE_CAP["BUTT"] = "butt"; + LINE_CAP["ROUND"] = "round"; + LINE_CAP["SQUARE"] = "square"; + })(exports.LINE_CAP || (exports.LINE_CAP = {})); + /** + * Graphics curves resolution settings. If `adaptive` flag is set to `true`, + * the resolution is calculated based on the curve's length to ensure better visual quality. + * Adaptive draw works with `bezierCurveTo` and `quadraticCurveTo`. + * @static + * @constant + * @memberof PIXI + * @name GRAPHICS_CURVES + * @type {object} + * @property {boolean} [adaptive=true] - flag indicating if the resolution should be adaptive + * @property {number} [maxLength=10] - maximal length of a single segment of the curve (if adaptive = false, ignored) + * @property {number} [minSegments=8] - minimal number of segments in the curve (if adaptive = false, ignored) + * @property {number} [maxSegments=2048] - maximal number of segments in the curve (if adaptive = false, ignored) + */ + var GRAPHICS_CURVES = { + adaptive: true, + maxLength: 10, + minSegments: 8, + maxSegments: 2048, + epsilon: 0.0001, + _segmentsCount: function (length, defaultSegments) { + if (defaultSegments === void 0) { defaultSegments = 20; } + if (!this.adaptive || !length || isNaN(length)) { + return defaultSegments; + } + var result = Math.ceil(length / this.maxLength); + if (result < this.minSegments) { + result = this.minSegments; + } + else if (result > this.maxSegments) { + result = this.maxSegments; + } + return result; + }, + }; - if (queue.indexOf(texture) === -1) { - queue.push(texture); - } + /** + * Fill style object for Graphics. + * @memberof PIXI + */ + var FillStyle = /** @class */ (function () { + function FillStyle() { + /** + * The hex color value used when coloring the Graphics object. + * @default 0xFFFFFF + */ + this.color = 0xFFFFFF; + /** The alpha value used when filling the Graphics object. */ + this.alpha = 1.0; + /** + * The texture to be used for the fill. + * @default 0 + */ + this.texture = Texture.WHITE; + /** + * The transform applied to the texture. + * @default null + */ + this.matrix = null; + /** If the current fill is visible. */ + this.visible = false; + this.reset(); + } + /** Clones the object */ + FillStyle.prototype.clone = function () { + var obj = new FillStyle(); + obj.color = this.color; + obj.alpha = this.alpha; + obj.texture = this.texture; + obj.matrix = this.matrix; + obj.visible = this.visible; + return obj; + }; + /** Reset */ + FillStyle.prototype.reset = function () { + this.color = 0xFFFFFF; + this.alpha = 1; + this.texture = Texture.WHITE; + this.matrix = null; + this.visible = false; + }; + /** Destroy and don't use after this. */ + FillStyle.prototype.destroy = function () { + this.texture = null; + this.matrix = null; + }; + return FillStyle; + }()); + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$e = function(d, b) { + extendStatics$e = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$e(d, b); + }; - return true; - } + function __extends$e(d, b) { + extendStatics$e(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } - return false; -} + function fixOrientation(points, hole) { + var _a, _b; + if (hole === void 0) { hole = false; } + var m = points.length; + if (m < 6) { + return; + } + var area = 0; + for (var i = 0, x1 = points[m - 2], y1 = points[m - 1]; i < m; i += 2) { + var x2 = points[i]; + var y2 = points[i + 1]; + area += (x2 - x1) * (y2 + y1); + x1 = x2; + y1 = y2; + } + if ((!hole && area > 0) || (hole && area <= 0)) { + var n = m / 2; + for (var i = n + (n % 2); i < m; i += 2) { + var i1 = m - i - 2; + var i2 = m - i - 1; + var i3 = i; + var i4 = i + 1; + _a = [points[i3], points[i1]], points[i1] = _a[0], points[i3] = _a[1]; + _b = [points[i4], points[i2]], points[i2] = _b[0], points[i4] = _b[1]; + } + } + } + /** + * Builds a polygon to draw + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines + */ + var buildPoly = { + build: function (graphicsData) { + graphicsData.points = graphicsData.shape.points.slice(); + }, + triangulate: function (graphicsData, graphicsGeometry) { + var points = graphicsData.points; + var holes = graphicsData.holes; + var verts = graphicsGeometry.points; + var indices = graphicsGeometry.indices; + if (points.length >= 6) { + fixOrientation(points, false); + var holeArray = []; + // Process holes.. + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + fixOrientation(hole.points, true); + holeArray.push(points.length / 2); + points = points.concat(hole.points); + } + // sort color + var triangles = earcut_1(points, holeArray, 2); + if (!triangles) { + return; + } + var vertPos = verts.length / 2; + for (var i = 0; i < triangles.length; i += 3) { + indices.push(triangles[i] + vertPos); + indices.push(triangles[i + 1] + vertPos); + indices.push(triangles[i + 2] + vertPos); + } + for (var i = 0; i < points.length; i++) { + verts.push(points[i]); + } + } + }, + }; -/** - * Built-in hook to draw PIXI.Text to its texture. - * - * @private - * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler - * @param {PIXI.DisplayObject} item - Item to check - * @return {boolean} If item was uploaded. - */ -function drawText(helper, item) { - if (item instanceof core.Text) { - // updating text will return early if it is not dirty - item.updateText(true); + // for type only + /** + * Builds a circle to draw + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw + * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines + */ + var buildCircle = { + build: function (graphicsData) { + // need to convert points to a nice regular data + var points = graphicsData.points; + var x; + var y; + var dx; + var dy; + var rx; + var ry; + if (graphicsData.type === exports.SHAPES.CIRC) { + var circle = graphicsData.shape; + x = circle.x; + y = circle.y; + rx = ry = circle.radius; + dx = dy = 0; + } + else if (graphicsData.type === exports.SHAPES.ELIP) { + var ellipse = graphicsData.shape; + x = ellipse.x; + y = ellipse.y; + rx = ellipse.width; + ry = ellipse.height; + dx = dy = 0; + } + else { + var roundedRect = graphicsData.shape; + var halfWidth = roundedRect.width / 2; + var halfHeight = roundedRect.height / 2; + x = roundedRect.x + halfWidth; + y = roundedRect.y + halfHeight; + rx = ry = Math.max(0, Math.min(roundedRect.radius, Math.min(halfWidth, halfHeight))); + dx = halfWidth - rx; + dy = halfHeight - ry; + } + if (!(rx >= 0 && ry >= 0 && dx >= 0 && dy >= 0)) { + points.length = 0; + return; + } + // Choose a number of segments such that the maximum absolute deviation from the circle is approximately 0.029 + var n = Math.ceil(2.3 * Math.sqrt(rx + ry)); + var m = (n * 8) + (dx ? 4 : 0) + (dy ? 4 : 0); + points.length = m; + if (m === 0) { + return; + } + if (n === 0) { + points.length = 8; + points[0] = points[6] = x + dx; + points[1] = points[3] = y + dy; + points[2] = points[4] = x - dx; + points[5] = points[7] = y - dy; + return; + } + var j1 = 0; + var j2 = (n * 4) + (dx ? 2 : 0) + 2; + var j3 = j2; + var j4 = m; + { + var x0 = dx + rx; + var y0 = dy; + var x1 = x + x0; + var x2 = x - x0; + var y1 = y + y0; + points[j1++] = x1; + points[j1++] = y1; + points[--j2] = y1; + points[--j2] = x2; + if (dy) { + var y2 = y - y0; + points[j3++] = x2; + points[j3++] = y2; + points[--j4] = y2; + points[--j4] = x1; + } + } + for (var i = 1; i < n; i++) { + var a = Math.PI / 2 * (i / n); + var x0 = dx + (Math.cos(a) * rx); + var y0 = dy + (Math.sin(a) * ry); + var x1 = x + x0; + var x2 = x - x0; + var y1 = y + y0; + var y2 = y - y0; + points[j1++] = x1; + points[j1++] = y1; + points[--j2] = y1; + points[--j2] = x2; + points[j3++] = x2; + points[j3++] = y2; + points[--j4] = y2; + points[--j4] = x1; + } + { + var x0 = dx; + var y0 = dy + ry; + var x1 = x + x0; + var x2 = x - x0; + var y1 = y + y0; + var y2 = y - y0; + points[j1++] = x1; + points[j1++] = y1; + points[--j4] = y2; + points[--j4] = x1; + if (dx) { + points[j1++] = x2; + points[j1++] = y1; + points[--j4] = y2; + points[--j4] = x2; + } + } + }, + triangulate: function (graphicsData, graphicsGeometry) { + var points = graphicsData.points; + var verts = graphicsGeometry.points; + var indices = graphicsGeometry.indices; + if (points.length === 0) { + return; + } + var vertPos = verts.length / 2; + var center = vertPos; + var x; + var y; + if (graphicsData.type !== exports.SHAPES.RREC) { + var circle = graphicsData.shape; + x = circle.x; + y = circle.y; + } + else { + var roundedRect = graphicsData.shape; + x = roundedRect.x + (roundedRect.width / 2); + y = roundedRect.y + (roundedRect.height / 2); + } + var matrix = graphicsData.matrix; + // Push center (special point) + verts.push(graphicsData.matrix ? (matrix.a * x) + (matrix.c * y) + matrix.tx : x, graphicsData.matrix ? (matrix.b * x) + (matrix.d * y) + matrix.ty : y); + vertPos++; + verts.push(points[0], points[1]); + for (var i = 2; i < points.length; i += 2) { + verts.push(points[i], points[i + 1]); + // add some uvs + indices.push(vertPos++, center, vertPos); + } + indices.push(center + 1, center, vertPos); + }, + }; - return true; - } + /** + * Builds a rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines + */ + var buildRectangle = { + build: function (graphicsData) { + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + var points = graphicsData.points; + points.length = 0; + points.push(x, y, x + width, y, x + width, y + height, x, y + height); + }, + triangulate: function (graphicsData, graphicsGeometry) { + var points = graphicsData.points; + var verts = graphicsGeometry.points; + var vertPos = verts.length / 2; + verts.push(points[0], points[1], points[2], points[3], points[6], points[7], points[4], points[5]); + graphicsGeometry.indices.push(vertPos, vertPos + 1, vertPos + 2, vertPos + 1, vertPos + 2, vertPos + 3); + }, + }; - return false; -} + /** + * Calculate a single point for a quadratic bezier curve. + * Utility function used by quadraticBezierCurve. + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {number} n1 - first number + * @param {number} n2 - second number + * @param {number} perc - percentage + * @returns {number} the result + */ + function getPt(n1, n2, perc) { + var diff = n2 - n1; + return n1 + (diff * perc); + } + /** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {number} fromX - Origin point x + * @param {number} fromY - Origin point x + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. + * @returns {number[]} an array of points + */ + function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY, out) { + if (out === void 0) { out = []; } + var n = 20; + var points = out; + var xa = 0; + var ya = 0; + var xb = 0; + var yb = 0; + var x = 0; + var y = 0; + for (var i = 0, j = 0; i <= n; ++i) { + j = i / n; + // The Green Line + xa = getPt(fromX, cpX, j); + ya = getPt(fromY, cpY, j); + xb = getPt(cpX, toX, j); + yb = getPt(cpY, toY, j); + // The Black Dot + x = getPt(xa, xb, j); + y = getPt(ya, yb, j); + // Handle case when first curve points overlaps and earcut fails to triangulate + if (i === 0 && points[points.length - 2] === x && points[points.length - 1] === y) { + continue; + } + points.push(x, y); + } + return points; + } + /** + * Builds a rounded rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines + */ + var buildRoundedRectangle = { + build: function (graphicsData) { + if (Graphics.nextRoundedRectBehavior) { + buildCircle.build(graphicsData); + return; + } + var rrectData = graphicsData.shape; + var points = graphicsData.points; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + // Don't allow negative radius or greater than half the smallest width + var radius = Math.max(0, Math.min(rrectData.radius, Math.min(width, height) / 2)); + points.length = 0; + // No radius, do a simple rectangle + if (!radius) { + points.push(x, y, x + width, y, x + width, y + height, x, y + height); + } + else { + quadraticBezierCurve(x, y + radius, x, y, x + radius, y, points); + quadraticBezierCurve(x + width - radius, y, x + width, y, x + width, y + radius, points); + quadraticBezierCurve(x + width, y + height - radius, x + width, y + height, x + width - radius, y + height, points); + quadraticBezierCurve(x + radius, y + height, x, y + height, x, y + height - radius, points); + } + }, + triangulate: function (graphicsData, graphicsGeometry) { + if (Graphics.nextRoundedRectBehavior) { + buildCircle.triangulate(graphicsData, graphicsGeometry); + return; + } + var points = graphicsData.points; + var verts = graphicsGeometry.points; + var indices = graphicsGeometry.indices; + var vecPos = verts.length / 2; + var triangles = earcut_1(points, null, 2); + for (var i = 0, j = triangles.length; i < j; i += 3) { + indices.push(triangles[i] + vecPos); + // indices.push(triangles[i] + vecPos); + indices.push(triangles[i + 1] + vecPos); + // indices.push(triangles[i + 2] + vecPos); + indices.push(triangles[i + 2] + vecPos); + } + for (var i = 0, j = points.length; i < j; i++) { + verts.push(points[i], points[++i]); + } + }, + }; -/** - * Built-in hook to calculate a text style for a PIXI.Text object. - * - * @private - * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler - * @param {PIXI.DisplayObject} item - Item to check - * @return {boolean} If item was uploaded. - */ -function calculateTextStyle(helper, item) { - if (item instanceof core.TextStyle) { - var font = item.toFontString(); + /** + * Buffers vertices to draw a square cap. + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {number} x - X-coord of end point + * @param {number} y - Y-coord of end point + * @param {number} nx - X-coord of line normal pointing inside + * @param {number} ny - Y-coord of line normal pointing inside + * @param {number} innerWeight - Weight of inner points + * @param {number} outerWeight - Weight of outer points + * @param {boolean} clockwise - Whether the cap is drawn clockwise + * @param {Array} verts - vertex buffer + * @returns {number} - no. of vertices pushed + */ + function square(x, y, nx, ny, innerWeight, outerWeight, clockwise, /* rotation for square (true at left end, false at right end) */ verts) { + var ix = x - (nx * innerWeight); + var iy = y - (ny * innerWeight); + var ox = x + (nx * outerWeight); + var oy = y + (ny * outerWeight); + /* Rotate nx,ny for extension vector */ + var exx; + var eyy; + if (clockwise) { + exx = ny; + eyy = -nx; + } + else { + exx = -ny; + eyy = nx; + } + /* [i|0]x,y extended at cap */ + var eix = ix + exx; + var eiy = iy + eyy; + var eox = ox + exx; + var eoy = oy + eyy; + /* Square itself must be inserted clockwise*/ + verts.push(eix, eiy); + verts.push(eox, eoy); + return 2; + } + /** + * Buffers vertices to draw an arc at the line joint or cap. + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {number} cx - X-coord of center + * @param {number} cy - Y-coord of center + * @param {number} sx - X-coord of arc start + * @param {number} sy - Y-coord of arc start + * @param {number} ex - X-coord of arc end + * @param {number} ey - Y-coord of arc end + * @param {Array} verts - buffer of vertices + * @param {boolean} clockwise - orientation of vertices + * @returns {number} - no. of vertices pushed + */ + function round(cx, cy, sx, sy, ex, ey, verts, clockwise) { + var cx2p0x = sx - cx; + var cy2p0y = sy - cy; + var angle0 = Math.atan2(cx2p0x, cy2p0y); + var angle1 = Math.atan2(ex - cx, ey - cy); + if (clockwise && angle0 < angle1) { + angle0 += Math.PI * 2; + } + else if (!clockwise && angle0 > angle1) { + angle1 += Math.PI * 2; + } + var startAngle = angle0; + var angleDiff = angle1 - angle0; + var absAngleDiff = Math.abs(angleDiff); + /* if (absAngleDiff >= PI_LBOUND && absAngleDiff <= PI_UBOUND) + { + const r1x = cx - nxtPx; + const r1y = cy - nxtPy; + + if (r1x === 0) + { + if (r1y > 0) + { + angleDiff = -angleDiff; + } + } + else if (r1x >= -GRAPHICS_CURVES.epsilon) + { + angleDiff = -angleDiff; + } + }*/ + var radius = Math.sqrt((cx2p0x * cx2p0x) + (cy2p0y * cy2p0y)); + var segCount = ((15 * absAngleDiff * Math.sqrt(radius) / Math.PI) >> 0) + 1; + var angleInc = angleDiff / segCount; + startAngle += angleInc; + if (clockwise) { + verts.push(cx, cy); + verts.push(sx, sy); + for (var i = 1, angle = startAngle; i < segCount; i++, angle += angleInc) { + verts.push(cx, cy); + verts.push(cx + ((Math.sin(angle) * radius)), cy + ((Math.cos(angle) * radius))); + } + verts.push(cx, cy); + verts.push(ex, ey); + } + else { + verts.push(sx, sy); + verts.push(cx, cy); + for (var i = 1, angle = startAngle; i < segCount; i++, angle += angleInc) { + verts.push(cx + ((Math.sin(angle) * radius)), cy + ((Math.cos(angle) * radius))); + verts.push(cx, cy); + } + verts.push(ex, ey); + verts.push(cx, cy); + } + return segCount * 2; + } + /** + * Builds a line to draw using the polygon method. + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output + */ + function buildNonNativeLine(graphicsData, graphicsGeometry) { + var shape = graphicsData.shape; + var points = graphicsData.points || shape.points.slice(); + var eps = graphicsGeometry.closePointEps; + if (points.length === 0) { + return; + } + // if the line width is an odd number add 0.5 to align to a whole pixel + // commenting this out fixes #711 and #1620 + // if (graphicsData.lineWidth%2) + // { + // for (i = 0; i < points.length; i++) + // { + // points[i] += 0.5; + // } + // } + var style = graphicsData.lineStyle; + // get first and last point.. figure out the middle! + var firstPoint = new Point(points[0], points[1]); + var lastPoint = new Point(points[points.length - 2], points[points.length - 1]); + var closedShape = shape.type !== exports.SHAPES.POLY || shape.closeStroke; + var closedPath = Math.abs(firstPoint.x - lastPoint.x) < eps + && Math.abs(firstPoint.y - lastPoint.y) < eps; + // if the first point is the last point - gonna have issues :) + if (closedShape) { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + if (closedPath) { + points.pop(); + points.pop(); + lastPoint.set(points[points.length - 2], points[points.length - 1]); + } + var midPointX = (firstPoint.x + lastPoint.x) * 0.5; + var midPointY = (lastPoint.y + firstPoint.y) * 0.5; + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + var verts = graphicsGeometry.points; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length / 2; + // Max. inner and outer width + var width = style.width / 2; + var widthSquared = width * width; + var miterLimitSquared = style.miterLimit * style.miterLimit; + /* Line segments of interest where (x1,y1) forms the corner. */ + var x0 = points[0]; + var y0 = points[1]; + var x1 = points[2]; + var y1 = points[3]; + var x2 = 0; + var y2 = 0; + /* perp[?](x|y) = the line normal with magnitude lineWidth. */ + var perpx = -(y0 - y1); + var perpy = x0 - x1; + var perp1x = 0; + var perp1y = 0; + var dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + var ratio = style.alignment; // 0.5; + var innerWeight = (1 - ratio) * 2; + var outerWeight = ratio * 2; + if (!closedShape) { + if (style.cap === exports.LINE_CAP.ROUND) { + indexCount += round(x0 - (perpx * (innerWeight - outerWeight) * 0.5), y0 - (perpy * (innerWeight - outerWeight) * 0.5), x0 - (perpx * innerWeight), y0 - (perpy * innerWeight), x0 + (perpx * outerWeight), y0 + (perpy * outerWeight), verts, true) + 2; + } + else if (style.cap === exports.LINE_CAP.SQUARE) { + indexCount += square(x0, y0, perpx, perpy, innerWeight, outerWeight, true, verts); + } + } + // Push first point (below & above vertices) + verts.push(x0 - (perpx * innerWeight), y0 - (perpy * innerWeight)); + verts.push(x0 + (perpx * outerWeight), y0 + (perpy * outerWeight)); + for (var i = 1; i < length - 1; ++i) { + x0 = points[(i - 1) * 2]; + y0 = points[((i - 1) * 2) + 1]; + x1 = points[i * 2]; + y1 = points[(i * 2) + 1]; + x2 = points[(i + 1) * 2]; + y2 = points[((i + 1) * 2) + 1]; + perpx = -(y0 - y1); + perpy = x0 - x1; + dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + perp1x = -(y1 - y2); + perp1y = x1 - x2; + dist = Math.sqrt((perp1x * perp1x) + (perp1y * perp1y)); + perp1x /= dist; + perp1y /= dist; + perp1x *= width; + perp1y *= width; + /* d[x|y](0|1) = the component displacement between points p(0,1|1,2) */ + var dx0 = x1 - x0; + var dy0 = y0 - y1; + var dx1 = x1 - x2; + var dy1 = y2 - y1; + /* +ve if internal angle < 90 degree, -ve if internal angle > 90 degree. */ + var dot = (dx0 * dx1) + (dy0 * dy1); + /* +ve if internal angle counterclockwise, -ve if internal angle clockwise. */ + var cross = (dy0 * dx1) - (dy1 * dx0); + var clockwise = (cross < 0); + /* Going nearly parallel? */ + /* atan(0.001) ~= 0.001 rad ~= 0.057 degree */ + if (Math.abs(cross) < 0.001 * Math.abs(dot)) { + verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); + verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); + /* 180 degree corner? */ + if (dot >= 0) { + if (style.join === exports.LINE_JOIN.ROUND) { + indexCount += round(x1, y1, x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight), verts, false) + 4; + } + else { + indexCount += 2; + } + verts.push(x1 - (perp1x * outerWeight), y1 - (perp1y * outerWeight)); + verts.push(x1 + (perp1x * innerWeight), y1 + (perp1y * innerWeight)); + } + continue; + } + /* p[x|y] is the miter point. pdist is the distance between miter point and p1. */ + var c1 = ((-perpx + x0) * (-perpy + y1)) - ((-perpx + x1) * (-perpy + y0)); + var c2 = ((-perp1x + x2) * (-perp1y + y1)) - ((-perp1x + x1) * (-perp1y + y2)); + var px = ((dx0 * c2) - (dx1 * c1)) / cross; + var py = ((dy1 * c1) - (dy0 * c2)) / cross; + var pdist = ((px - x1) * (px - x1)) + ((py - y1) * (py - y1)); + /* Inner miter point */ + var imx = x1 + ((px - x1) * innerWeight); + var imy = y1 + ((py - y1) * innerWeight); + /* Outer miter point */ + var omx = x1 - ((px - x1) * outerWeight); + var omy = y1 - ((py - y1) * outerWeight); + /* Is the inside miter point too far away, creating a spike? */ + var smallerInsideSegmentSq = Math.min((dx0 * dx0) + (dy0 * dy0), (dx1 * dx1) + (dy1 * dy1)); + var insideWeight = clockwise ? innerWeight : outerWeight; + var smallerInsideDiagonalSq = smallerInsideSegmentSq + (insideWeight * insideWeight * widthSquared); + var insideMiterOk = pdist <= smallerInsideDiagonalSq; + if (insideMiterOk) { + if (style.join === exports.LINE_JOIN.BEVEL || pdist / widthSquared > miterLimitSquared) { + if (clockwise) /* rotating at inner angle */ { + verts.push(imx, imy); // inner miter point + verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); // first segment's outer vertex + verts.push(imx, imy); // inner miter point + verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); // second segment's outer vertex + } + else /* rotating at outer angle */ { + verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); // first segment's inner vertex + verts.push(omx, omy); // outer miter point + verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); // second segment's outer vertex + verts.push(omx, omy); // outer miter point + } + indexCount += 2; + } + else if (style.join === exports.LINE_JOIN.ROUND) { + if (clockwise) /* arc is outside */ { + verts.push(imx, imy); + verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); + indexCount += round(x1, y1, x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight), verts, true) + 4; + verts.push(imx, imy); + verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); + } + else /* arc is inside */ { + verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); + verts.push(omx, omy); + indexCount += round(x1, y1, x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight), verts, false) + 4; + verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); + verts.push(omx, omy); + } + } + else { + verts.push(imx, imy); + verts.push(omx, omy); + } + } + else // inside miter is NOT ok + { + verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); // first segment's inner vertex + verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); // first segment's outer vertex + if (style.join === exports.LINE_JOIN.ROUND) { + if (clockwise) /* arc is outside */ { + indexCount += round(x1, y1, x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight), verts, true) + 2; + } + else /* arc is inside */ { + indexCount += round(x1, y1, x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight), verts, false) + 2; + } + } + else if (style.join === exports.LINE_JOIN.MITER && pdist / widthSquared <= miterLimitSquared) { + if (clockwise) { + verts.push(omx, omy); // inner miter point + verts.push(omx, omy); // inner miter point + } + else { + verts.push(imx, imy); // outer miter point + verts.push(imx, imy); // outer miter point + } + indexCount += 2; + } + verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); // second segment's inner vertex + verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); // second segment's outer vertex + indexCount += 2; + } + } + x0 = points[(length - 2) * 2]; + y0 = points[((length - 2) * 2) + 1]; + x1 = points[(length - 1) * 2]; + y1 = points[((length - 1) * 2) + 1]; + perpx = -(y0 - y1); + perpy = x0 - x1; + dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); + verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); + if (!closedShape) { + if (style.cap === exports.LINE_CAP.ROUND) { + indexCount += round(x1 - (perpx * (innerWeight - outerWeight) * 0.5), y1 - (perpy * (innerWeight - outerWeight) * 0.5), x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), verts, false) + 2; + } + else if (style.cap === exports.LINE_CAP.SQUARE) { + indexCount += square(x1, y1, perpx, perpy, innerWeight, outerWeight, false, verts); + } + } + var indices = graphicsGeometry.indices; + var eps2 = GRAPHICS_CURVES.epsilon * GRAPHICS_CURVES.epsilon; + // indices.push(indexStart); + for (var i = indexStart; i < indexCount + indexStart - 2; ++i) { + x0 = verts[(i * 2)]; + y0 = verts[(i * 2) + 1]; + x1 = verts[(i + 1) * 2]; + y1 = verts[((i + 1) * 2) + 1]; + x2 = verts[(i + 2) * 2]; + y2 = verts[((i + 2) * 2) + 1]; + /* Skip zero area triangles */ + if (Math.abs((x0 * (y1 - y2)) + (x1 * (y2 - y0)) + (x2 * (y0 - y1))) < eps2) { + continue; + } + indices.push(i, i + 1, i + 2); + } + } + /** + * Builds a line to draw using the gl.drawArrays(gl.LINES) method + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output + */ + function buildNativeLine(graphicsData, graphicsGeometry) { + var i = 0; + var shape = graphicsData.shape; + var points = graphicsData.points || shape.points; + var closedShape = shape.type !== exports.SHAPES.POLY || shape.closeStroke; + if (points.length === 0) + { return; } + var verts = graphicsGeometry.points; + var indices = graphicsGeometry.indices; + var length = points.length / 2; + var startIndex = verts.length / 2; + var currentIndex = startIndex; + verts.push(points[0], points[1]); + for (i = 1; i < length; i++) { + verts.push(points[i * 2], points[(i * 2) + 1]); + indices.push(currentIndex, currentIndex + 1); + currentIndex++; + } + if (closedShape) { + indices.push(currentIndex, startIndex); + } + } + /** + * Builds a line to draw + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output + */ + function buildLine(graphicsData, graphicsGeometry) { + if (graphicsData.lineStyle.native) { + buildNativeLine(graphicsData, graphicsGeometry); + } + else { + buildNonNativeLine(graphicsData, graphicsGeometry); + } + } - core.TextMetrics.measureFont(font); + /** + * Utilities for arc curves. + * @private + */ + var ArcUtils = /** @class */ (function () { + function ArcUtils() { + } + /** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * @private + * @param x1 - The x-coordinate of the beginning of the arc + * @param y1 - The y-coordinate of the beginning of the arc + * @param x2 - The x-coordinate of the end of the arc + * @param y2 - The y-coordinate of the end of the arc + * @param radius - The radius of the arc + * @param points - + * @returns - If the arc length is valid, return center of circle, radius and other info otherwise `null`. + */ + ArcUtils.curveTo = function (x1, y1, x2, y2, radius, points) { + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var a1 = fromY - y1; + var b1 = fromX - x1; + var a2 = y2 - y1; + var b2 = x2 - x1; + var mm = Math.abs((a1 * b2) - (b1 * a2)); + if (mm < 1.0e-8 || radius === 0) { + if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { + points.push(x1, y1); + } + return null; + } + var dd = (a1 * a1) + (b1 * b1); + var cc = (a2 * a2) + (b2 * b2); + var tt = (a1 * a2) + (b1 * b2); + var k1 = radius * Math.sqrt(dd) / mm; + var k2 = radius * Math.sqrt(cc) / mm; + var j1 = k1 * tt / dd; + var j2 = k2 * tt / cc; + var cx = (k1 * b2) + (k2 * b1); + var cy = (k1 * a2) + (k2 * a1); + var px = b1 * (k2 + j1); + var py = a1 * (k2 + j1); + var qx = b2 * (k1 + j2); + var qy = a2 * (k1 + j2); + var startAngle = Math.atan2(py - cy, px - cx); + var endAngle = Math.atan2(qy - cy, qx - cx); + return { + cx: (cx + x1), + cy: (cy + y1), + radius: radius, + startAngle: startAngle, + endAngle: endAngle, + anticlockwise: (b1 * a2 > b2 * a1), + }; + }; + /* eslint-disable max-len */ + /** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * @private + * @param _startX - Start x location of arc + * @param _startY - Start y location of arc + * @param cx - The x-coordinate of the center of the circle + * @param cy - The y-coordinate of the center of the circle + * @param radius - The radius of the circle + * @param startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param endAngle - The ending angle, in radians + * @param _anticlockwise - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @param points - Collection of points to add to + */ + ArcUtils.arc = function (_startX, _startY, cx, cy, radius, startAngle, endAngle, _anticlockwise, points) { + var sweep = endAngle - startAngle; + var n = GRAPHICS_CURVES._segmentsCount(Math.abs(sweep) * radius, Math.ceil(Math.abs(sweep) / PI_2) * 40); + var theta = (sweep) / (n * 2); + var theta2 = theta * 2; + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + var segMinus = n - 1; + var remainder = (segMinus % 1) / segMinus; + for (var i = 0; i <= segMinus; ++i) { + var real = i + (remainder * i); + var angle = ((theta) + startAngle + (theta2 * real)); + var c = Math.cos(angle); + var s = -Math.sin(angle); + points.push((((cTheta * c) + (sTheta * s)) * radius) + cx, (((cTheta * -s) + (sTheta * c)) * radius) + cy); + } + }; + return ArcUtils; + }()); - return true; - } + /** + * Utilities for bezier curves + * @private + */ + var BezierUtils = /** @class */ (function () { + function BezierUtils() { + } + /** + * Calculate length of bezier curve. + * Analytical solution is impossible, since it involves an integral that does not integrate in general. + * Therefore numerical solution is used. + * @private + * @param fromX - Starting point x + * @param fromY - Starting point y + * @param cpX - Control point x + * @param cpY - Control point y + * @param cpX2 - Second Control point x + * @param cpY2 - Second Control point y + * @param toX - Destination point x + * @param toY - Destination point y + * @returns - Length of bezier curve + */ + BezierUtils.curveLength = function (fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { + var n = 10; + var result = 0.0; + var t = 0.0; + var t2 = 0.0; + var t3 = 0.0; + var nt = 0.0; + var nt2 = 0.0; + var nt3 = 0.0; + var x = 0.0; + var y = 0.0; + var dx = 0.0; + var dy = 0.0; + var prevX = fromX; + var prevY = fromY; + for (var i = 1; i <= n; ++i) { + t = i / n; + t2 = t * t; + t3 = t2 * t; + nt = (1.0 - t); + nt2 = nt * nt; + nt3 = nt2 * nt; + x = (nt3 * fromX) + (3.0 * nt2 * t * cpX) + (3.0 * nt * t2 * cpX2) + (t3 * toX); + y = (nt3 * fromY) + (3.0 * nt2 * t * cpY) + (3 * nt * t2 * cpY2) + (t3 * toY); + dx = prevX - x; + dy = prevY - y; + prevX = x; + prevY = y; + result += Math.sqrt((dx * dx) + (dy * dy)); + } + return result; + }; + /** + * Calculate the points for a bezier curve and then draws it. + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @param cpX - Control point x + * @param cpY - Control point y + * @param cpX2 - Second Control point x + * @param cpY2 - Second Control point y + * @param toX - Destination point x + * @param toY - Destination point y + * @param points - Path array to push points into + */ + BezierUtils.curveTo = function (cpX, cpY, cpX2, cpY2, toX, toY, points) { + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + points.length -= 2; + var n = GRAPHICS_CURVES._segmentsCount(BezierUtils.curveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY)); + var dt = 0; + var dt2 = 0; + var dt3 = 0; + var t2 = 0; + var t3 = 0; + points.push(fromX, fromY); + for (var i = 1, j = 0; i <= n; ++i) { + j = i / n; + dt = (1 - j); + dt2 = dt * dt; + dt3 = dt2 * dt; + t2 = j * j; + t3 = t2 * j; + points.push((dt3 * fromX) + (3 * dt2 * j * cpX) + (3 * dt * t2 * cpX2) + (t3 * toX), (dt3 * fromY) + (3 * dt2 * j * cpY) + (3 * dt * t2 * cpY2) + (t3 * toY)); + } + }; + return BezierUtils; + }()); - return false; -} + /** + * Utilities for quadratic curves. + * @private + */ + var QuadraticUtils = /** @class */ (function () { + function QuadraticUtils() { + } + /** + * Calculate length of quadratic curve + * @see {@link http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/} + * for the detailed explanation of math behind this. + * @private + * @param fromX - x-coordinate of curve start point + * @param fromY - y-coordinate of curve start point + * @param cpX - x-coordinate of curve control point + * @param cpY - y-coordinate of curve control point + * @param toX - x-coordinate of curve end point + * @param toY - y-coordinate of curve end point + * @returns - Length of quadratic curve + */ + QuadraticUtils.curveLength = function (fromX, fromY, cpX, cpY, toX, toY) { + var ax = fromX - (2.0 * cpX) + toX; + var ay = fromY - (2.0 * cpY) + toY; + var bx = (2.0 * cpX) - (2.0 * fromX); + var by = (2.0 * cpY) - (2.0 * fromY); + var a = 4.0 * ((ax * ax) + (ay * ay)); + var b = 4.0 * ((ax * bx) + (ay * by)); + var c = (bx * bx) + (by * by); + var s = 2.0 * Math.sqrt(a + b + c); + var a2 = Math.sqrt(a); + var a32 = 2.0 * a * a2; + var c2 = 2.0 * Math.sqrt(c); + var ba = b / a2; + return ((a32 * s) + + (a2 * b * (s - c2)) + + (((4.0 * c * a) - (b * b)) + * Math.log(((2.0 * a2) + ba + s) / (ba + c2)))) / (4.0 * a32); + }; + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * @private + * @param cpX - Control point x + * @param cpY - Control point y + * @param toX - Destination point x + * @param toY - Destination point y + * @param points - Points to add segments to. + */ + QuadraticUtils.curveTo = function (cpX, cpY, toX, toY, points) { + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var n = GRAPHICS_CURVES._segmentsCount(QuadraticUtils.curveLength(fromX, fromY, cpX, cpY, toX, toY)); + var xa = 0; + var ya = 0; + for (var i = 1; i <= n; ++i) { + var j = i / n; + xa = fromX + ((cpX - fromX) * j); + ya = fromY + ((cpY - fromY) * j); + points.push(xa + (((cpX + ((toX - cpX) * j)) - xa) * j), ya + (((cpY + ((toY - cpY) * j)) - ya) * j)); + } + }; + return QuadraticUtils; + }()); -/** - * Built-in hook to find Text objects. - * - * @private - * @param {PIXI.DisplayObject} item - Display object to check - * @param {Array<*>} queue - Collection of items to upload - * @return {boolean} if a PIXI.Text object was found. - */ -function findText(item, queue) { - if (item instanceof core.Text) { - // push the text style to prepare it - this can be really expensive - if (queue.indexOf(item.style) === -1) { - queue.push(item.style); - } - // also push the text object so that we can render it (to canvas/texture) if needed - if (queue.indexOf(item) === -1) { - queue.push(item); - } - // also push the Text's texture for upload to GPU - var texture = item._texture.baseTexture; + /** + * A structure to hold interim batch objects for Graphics. + * @memberof PIXI.graphicsUtils + */ + var BatchPart = /** @class */ (function () { + function BatchPart() { + this.reset(); + } + /** + * Begin batch part. + * @param style + * @param startIndex + * @param attribStart + */ + BatchPart.prototype.begin = function (style, startIndex, attribStart) { + this.reset(); + this.style = style; + this.start = startIndex; + this.attribStart = attribStart; + }; + /** + * End batch part. + * @param endIndex + * @param endAttrib + */ + BatchPart.prototype.end = function (endIndex, endAttrib) { + this.attribSize = endAttrib - this.attribStart; + this.size = endIndex - this.start; + }; + BatchPart.prototype.reset = function () { + this.style = null; + this.size = 0; + this.start = 0; + this.attribStart = 0; + this.attribSize = 0; + }; + return BatchPart; + }()); - if (queue.indexOf(texture) === -1) { - queue.push(texture); - } + /** + * Generalized convenience utilities for Graphics. + * @namespace graphicsUtils + * @memberof PIXI + */ + var _a; + /** + * Map of fill commands for each shape type. + * @memberof PIXI.graphicsUtils + * @member {object} FILL_COMMANDS + */ + var FILL_COMMANDS = (_a = {}, + _a[exports.SHAPES.POLY] = buildPoly, + _a[exports.SHAPES.CIRC] = buildCircle, + _a[exports.SHAPES.ELIP] = buildCircle, + _a[exports.SHAPES.RECT] = buildRectangle, + _a[exports.SHAPES.RREC] = buildRoundedRectangle, + _a); + /** + * Batch pool, stores unused batches for preventing allocations. + * @memberof PIXI.graphicsUtils + * @member {Array} BATCH_POOL + */ + var BATCH_POOL = []; + /** + * Draw call pool, stores unused draw calls for preventing allocations. + * @memberof PIXI.graphicsUtils + * @member {Array} DRAW_CALL_POOL + */ + var DRAW_CALL_POOL = []; - return true; - } + /** + * A class to contain data useful for Graphics objects + * @memberof PIXI + */ + var GraphicsData = /** @class */ (function () { + /** + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @param fillStyle - the width of the line to draw + * @param lineStyle - the color of the line to draw + * @param matrix - Transform matrix + */ + function GraphicsData(shape, fillStyle, lineStyle, matrix) { + if (fillStyle === void 0) { fillStyle = null; } + if (lineStyle === void 0) { lineStyle = null; } + if (matrix === void 0) { matrix = null; } + /** The collection of points. */ + this.points = []; + /** The collection of holes. */ + this.holes = []; + this.shape = shape; + this.lineStyle = lineStyle; + this.fillStyle = fillStyle; + this.matrix = matrix; + this.type = shape.type; + } + /** + * Creates a new GraphicsData object with the same values as this one. + * @returns - Cloned GraphicsData object + */ + GraphicsData.prototype.clone = function () { + return new GraphicsData(this.shape, this.fillStyle, this.lineStyle, this.matrix); + }; + /** Destroys the Graphics data. */ + GraphicsData.prototype.destroy = function () { + this.shape = null; + this.holes.length = 0; + this.holes = null; + this.points.length = 0; + this.points = null; + this.lineStyle = null; + this.fillStyle = null; + }; + return GraphicsData; + }()); + + var tmpPoint = new Point(); + /** + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. + * + * GraphicsGeometry is designed to not be continually updating the geometry since it's expensive + * to re-tesselate using **earcut**. Consider using {@link PIXI.Mesh} for this use-case, it's much faster. + * @memberof PIXI + */ + var GraphicsGeometry = /** @class */ (function (_super) { + __extends$e(GraphicsGeometry, _super); + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + function GraphicsGeometry() { + var _this = _super.call(this) || this; + /** Minimal distance between points that are considered different. Affects line tesselation. */ + _this.closePointEps = 1e-4; + /** Padding to add to the bounds. */ + _this.boundsPadding = 0; + _this.uvsFloat32 = null; + _this.indicesUint16 = null; + _this.batchable = false; + /** An array of points to draw, 2 numbers per point */ + _this.points = []; + /** The collection of colors */ + _this.colors = []; + /** The UVs collection */ + _this.uvs = []; + /** The indices of the vertices */ + _this.indices = []; + /** Reference to the texture IDs. */ + _this.textureIds = []; + /** + * The collection of drawn shapes. + * @member {PIXI.GraphicsData[]} + */ + _this.graphicsData = []; + /** + * List of current draw calls drived from the batches. + * @member {PIXI.BatchDrawCall[]} + */ + _this.drawCalls = []; + /** Batches need to regenerated if the geometry is updated. */ + _this.batchDirty = -1; + /** + * Intermediate abstract format sent to batch system. + * Can be converted to drawCalls or to batchable objects. + * @member {PIXI.graphicsUtils.BatchPart[]} + */ + _this.batches = []; + /** Used to detect if the graphics object has changed. */ + _this.dirty = 0; + /** Used to check if the cache is dirty. */ + _this.cacheDirty = -1; + /** Used to detect if we cleared the graphicsData. */ + _this.clearDirty = 0; + /** Index of the last batched shape in the stack of calls. */ + _this.shapeIndex = 0; + /** Cached bounds. */ + _this._bounds = new Bounds(); + /** The bounds dirty flag. */ + _this.boundsDirty = -1; + return _this; + } + Object.defineProperty(GraphicsGeometry.prototype, "bounds", { + /** + * Get the current bounds of the graphic geometry. + * @readonly + */ + get: function () { + this.updateBatches(); + if (this.boundsDirty !== this.dirty) { + this.boundsDirty = this.dirty; + this.calculateBounds(); + } + return this._bounds; + }, + enumerable: false, + configurable: true + }); + /** Call if you changed graphicsData manually. Empties all batch buffers. */ + GraphicsGeometry.prototype.invalidate = function () { + this.boundsDirty = -1; + this.dirty++; + this.batchDirty++; + this.shapeIndex = 0; + this.points.length = 0; + this.colors.length = 0; + this.uvs.length = 0; + this.indices.length = 0; + this.textureIds.length = 0; + for (var i = 0; i < this.drawCalls.length; i++) { + this.drawCalls[i].texArray.clear(); + DRAW_CALL_POOL.push(this.drawCalls[i]); + } + this.drawCalls.length = 0; + for (var i = 0; i < this.batches.length; i++) { + var batchPart = this.batches[i]; + batchPart.reset(); + BATCH_POOL.push(batchPart); + } + this.batches.length = 0; + }; + /** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * @returns - This GraphicsGeometry object. Good for chaining method calls + */ + GraphicsGeometry.prototype.clear = function () { + if (this.graphicsData.length > 0) { + this.invalidate(); + this.clearDirty++; + this.graphicsData.length = 0; + } + return this; + }; + /** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @param fillStyle - Defines style of the fill. + * @param lineStyle - Defines style of the lines. + * @param matrix - Transform applied to the points of the shape. + * @returns - Returns geometry for chaining. + */ + GraphicsGeometry.prototype.drawShape = function (shape, fillStyle, lineStyle, matrix) { + if (fillStyle === void 0) { fillStyle = null; } + if (lineStyle === void 0) { lineStyle = null; } + if (matrix === void 0) { matrix = null; } + var data = new GraphicsData(shape, fillStyle, lineStyle, matrix); + this.graphicsData.push(data); + this.dirty++; + return this; + }; + /** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @param matrix - Transform applied to the points of the shape. + * @returns - Returns geometry for chaining. + */ + GraphicsGeometry.prototype.drawHole = function (shape, matrix) { + if (matrix === void 0) { matrix = null; } + if (!this.graphicsData.length) { + return null; + } + var data = new GraphicsData(shape, null, null, matrix); + var lastShape = this.graphicsData[this.graphicsData.length - 1]; + data.lineStyle = lastShape.lineStyle; + lastShape.holes.push(data); + this.dirty++; + return this; + }; + /** Destroys the GraphicsGeometry object. */ + GraphicsGeometry.prototype.destroy = function () { + _super.prototype.destroy.call(this); + // destroy each of the GraphicsData objects + for (var i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); + } + this.points.length = 0; + this.points = null; + this.colors.length = 0; + this.colors = null; + this.uvs.length = 0; + this.uvs = null; + this.indices.length = 0; + this.indices = null; + this.indexBuffer.destroy(); + this.indexBuffer = null; + this.graphicsData.length = 0; + this.graphicsData = null; + this.drawCalls.length = 0; + this.drawCalls = null; + this.batches.length = 0; + this.batches = null; + this._bounds = null; + }; + /** + * Check to see if a point is contained within this geometry. + * @param point - Point to check if it's contained. + * @returns {boolean} `true` if the point is contained within geometry. + */ + GraphicsGeometry.prototype.containsPoint = function (point) { + var graphicsData = this.graphicsData; + for (var i = 0; i < graphicsData.length; ++i) { + var data = graphicsData[i]; + if (!data.fillStyle.visible) { + continue; + } + // only deal with fills.. + if (data.shape) { + if (data.matrix) { + data.matrix.applyInverse(point, tmpPoint); + } + else { + tmpPoint.copyFrom(point); + } + if (data.shape.contains(tmpPoint.x, tmpPoint.y)) { + var hitHole = false; + if (data.holes) { + for (var i_1 = 0; i_1 < data.holes.length; i_1++) { + var hole = data.holes[i_1]; + if (hole.shape.contains(tmpPoint.x, tmpPoint.y)) { + hitHole = true; + break; + } + } + } + if (!hitHole) { + return true; + } + } + } + } + return false; + }; + /** + * Generates intermediate batch data. Either gets converted to drawCalls + * or used to convert to batch objects directly by the Graphics object. + */ + GraphicsGeometry.prototype.updateBatches = function () { + if (!this.graphicsData.length) { + this.batchable = true; + return; + } + if (!this.validateBatching()) { + return; + } + this.cacheDirty = this.dirty; + var uvs = this.uvs; + var graphicsData = this.graphicsData; + var batchPart = null; + var currentStyle = null; + if (this.batches.length > 0) { + batchPart = this.batches[this.batches.length - 1]; + currentStyle = batchPart.style; + } + for (var i = this.shapeIndex; i < graphicsData.length; i++) { + this.shapeIndex++; + var data = graphicsData[i]; + var fillStyle = data.fillStyle; + var lineStyle = data.lineStyle; + var command = FILL_COMMANDS[data.type]; + // build out the shapes points.. + command.build(data); + if (data.matrix) { + this.transformPoints(data.points, data.matrix); + } + if (fillStyle.visible || lineStyle.visible) { + this.processHoles(data.holes); + } + for (var j = 0; j < 2; j++) { + var style = (j === 0) ? fillStyle : lineStyle; + if (!style.visible) + { continue; } + var nextTexture = style.texture.baseTexture; + var index_1 = this.indices.length; + var attribIndex = this.points.length / 2; + nextTexture.wrapMode = exports.WRAP_MODES.REPEAT; + if (j === 0) { + this.processFill(data); + } + else { + this.processLine(data); + } + var size = (this.points.length / 2) - attribIndex; + if (size === 0) + { continue; } + // close batch if style is different + if (batchPart && !this._compareStyles(currentStyle, style)) { + batchPart.end(index_1, attribIndex); + batchPart = null; + } + // spawn new batch if its first batch or previous was closed + if (!batchPart) { + batchPart = BATCH_POOL.pop() || new BatchPart(); + batchPart.begin(style, index_1, attribIndex); + this.batches.push(batchPart); + currentStyle = style; + } + this.addUvs(this.points, uvs, style.texture, attribIndex, size, style.matrix); + } + } + var index = this.indices.length; + var attrib = this.points.length / 2; + if (batchPart) { + batchPart.end(index, attrib); + } + if (this.batches.length === 0) { + // there are no visible styles in GraphicsData + // its possible that someone wants Graphics just for the bounds + this.batchable = true; + return; + } + var need32 = attrib > 0xffff; + // prevent allocation when length is same as buffer + if (this.indicesUint16 && this.indices.length === this.indicesUint16.length + && need32 === (this.indicesUint16.BYTES_PER_ELEMENT > 2)) { + this.indicesUint16.set(this.indices); + } + else { + this.indicesUint16 = need32 ? new Uint32Array(this.indices) : new Uint16Array(this.indices); + } + // TODO make this a const.. + this.batchable = this.isBatchable(); + if (this.batchable) { + this.packBatches(); + } + else { + this.buildDrawCalls(); + } + }; + /** + * Affinity check + * @param styleA + * @param styleB + */ + GraphicsGeometry.prototype._compareStyles = function (styleA, styleB) { + if (!styleA || !styleB) { + return false; + } + if (styleA.texture.baseTexture !== styleB.texture.baseTexture) { + return false; + } + if (styleA.color + styleA.alpha !== styleB.color + styleB.alpha) { + return false; + } + if (!!styleA.native !== !!styleB.native) { + return false; + } + return true; + }; + /** Test geometry for batching process. */ + GraphicsGeometry.prototype.validateBatching = function () { + if (this.dirty === this.cacheDirty || !this.graphicsData.length) { + return false; + } + for (var i = 0, l = this.graphicsData.length; i < l; i++) { + var data = this.graphicsData[i]; + var fill = data.fillStyle; + var line = data.lineStyle; + if (fill && !fill.texture.baseTexture.valid) + { return false; } + if (line && !line.texture.baseTexture.valid) + { return false; } + } + return true; + }; + /** Offset the indices so that it works with the batcher. */ + GraphicsGeometry.prototype.packBatches = function () { + this.batchDirty++; + this.uvsFloat32 = new Float32Array(this.uvs); + var batches = this.batches; + for (var i = 0, l = batches.length; i < l; i++) { + var batch = batches[i]; + for (var j = 0; j < batch.size; j++) { + var index = batch.start + j; + this.indicesUint16[index] = this.indicesUint16[index] - batch.attribStart; + } + } + }; + /** + * Checks to see if this graphics geometry can be batched. + * Currently it needs to be small enough and not contain any native lines. + */ + GraphicsGeometry.prototype.isBatchable = function () { + // prevent heavy mesh batching + if (this.points.length > 0xffff * 2) { + return false; + } + var batches = this.batches; + for (var i = 0; i < batches.length; i++) { + if (batches[i].style.native) { + return false; + } + } + return (this.points.length < GraphicsGeometry.BATCHABLE_SIZE * 2); + }; + /** Converts intermediate batches data to drawCalls. */ + GraphicsGeometry.prototype.buildDrawCalls = function () { + var TICK = ++BaseTexture._globalBatch; + for (var i = 0; i < this.drawCalls.length; i++) { + this.drawCalls[i].texArray.clear(); + DRAW_CALL_POOL.push(this.drawCalls[i]); + } + this.drawCalls.length = 0; + var colors = this.colors; + var textureIds = this.textureIds; + var currentGroup = DRAW_CALL_POOL.pop(); + if (!currentGroup) { + currentGroup = new BatchDrawCall(); + currentGroup.texArray = new BatchTextureArray(); + } + currentGroup.texArray.count = 0; + currentGroup.start = 0; + currentGroup.size = 0; + currentGroup.type = exports.DRAW_MODES.TRIANGLES; + var textureCount = 0; + var currentTexture = null; + var textureId = 0; + var native = false; + var drawMode = exports.DRAW_MODES.TRIANGLES; + var index = 0; + this.drawCalls.push(currentGroup); + // TODO - this can be simplified + for (var i = 0; i < this.batches.length; i++) { + var data = this.batches[i]; + // TODO add some full on MAX_TEXTURE CODE.. + var MAX_TEXTURES = 8; + // Forced cast for checking `native` without errors + var style = data.style; + var nextTexture = style.texture.baseTexture; + if (native !== !!style.native) { + native = !!style.native; + drawMode = native ? exports.DRAW_MODES.LINES : exports.DRAW_MODES.TRIANGLES; + // force the batch to break! + currentTexture = null; + textureCount = MAX_TEXTURES; + TICK++; + } + if (currentTexture !== nextTexture) { + currentTexture = nextTexture; + if (nextTexture._batchEnabled !== TICK) { + if (textureCount === MAX_TEXTURES) { + TICK++; + textureCount = 0; + if (currentGroup.size > 0) { + currentGroup = DRAW_CALL_POOL.pop(); + if (!currentGroup) { + currentGroup = new BatchDrawCall(); + currentGroup.texArray = new BatchTextureArray(); + } + this.drawCalls.push(currentGroup); + } + currentGroup.start = index; + currentGroup.size = 0; + currentGroup.texArray.count = 0; + currentGroup.type = drawMode; + } + // TODO add this to the render part.. + // Hack! Because texture has protected `touched` + nextTexture.touched = 1; // touch; + nextTexture._batchEnabled = TICK; + nextTexture._batchLocation = textureCount; + nextTexture.wrapMode = exports.WRAP_MODES.REPEAT; + currentGroup.texArray.elements[currentGroup.texArray.count++] = nextTexture; + textureCount++; + } + } + currentGroup.size += data.size; + index += data.size; + textureId = nextTexture._batchLocation; + this.addColors(colors, style.color, style.alpha, data.attribSize, data.attribStart); + this.addTextureIds(textureIds, textureId, data.attribSize, data.attribStart); + } + BaseTexture._globalBatch = TICK; + // upload.. + // merge for now! + this.packAttributes(); + }; + /** Packs attributes to single buffer. */ + GraphicsGeometry.prototype.packAttributes = function () { + var verts = this.points; + var uvs = this.uvs; + var colors = this.colors; + var textureIds = this.textureIds; + // verts are 2 positions.. so we * by 3 as there are 6 properties.. then 4 cos its bytes + var glPoints = new ArrayBuffer(verts.length * 3 * 4); + var f32 = new Float32Array(glPoints); + var u32 = new Uint32Array(glPoints); + var p = 0; + for (var i = 0; i < verts.length / 2; i++) { + f32[p++] = verts[i * 2]; + f32[p++] = verts[(i * 2) + 1]; + f32[p++] = uvs[i * 2]; + f32[p++] = uvs[(i * 2) + 1]; + u32[p++] = colors[i]; + f32[p++] = textureIds[i]; + } + this._buffer.update(glPoints); + this._indexBuffer.update(this.indicesUint16); + }; + /** + * Process fill part of Graphics. + * @param data + */ + GraphicsGeometry.prototype.processFill = function (data) { + if (data.holes.length) { + buildPoly.triangulate(data, this); + } + else { + var command = FILL_COMMANDS[data.type]; + command.triangulate(data, this); + } + }; + /** + * Process line part of Graphics. + * @param data + */ + GraphicsGeometry.prototype.processLine = function (data) { + buildLine(data, this); + for (var i = 0; i < data.holes.length; i++) { + buildLine(data.holes[i], this); + } + }; + /** + * Process the holes data. + * @param holes + */ + GraphicsGeometry.prototype.processHoles = function (holes) { + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + var command = FILL_COMMANDS[hole.type]; + command.build(hole); + if (hole.matrix) { + this.transformPoints(hole.points, hole.matrix); + } + } + }; + /** Update the local bounds of the object. Expensive to use performance-wise. */ + GraphicsGeometry.prototype.calculateBounds = function () { + var bounds = this._bounds; + bounds.clear(); + bounds.addVertexData(this.points, 0, this.points.length); + bounds.pad(this.boundsPadding, this.boundsPadding); + }; + /** + * Transform points using matrix. + * @param points - Points to transform + * @param matrix - Transform matrix + */ + GraphicsGeometry.prototype.transformPoints = function (points, matrix) { + for (var i = 0; i < points.length / 2; i++) { + var x = points[(i * 2)]; + var y = points[(i * 2) + 1]; + points[(i * 2)] = (matrix.a * x) + (matrix.c * y) + matrix.tx; + points[(i * 2) + 1] = (matrix.b * x) + (matrix.d * y) + matrix.ty; + } + }; + /** + * Add colors. + * @param colors - List of colors to add to + * @param color - Color to add + * @param alpha - Alpha to use + * @param size - Number of colors to add + * @param offset + */ + GraphicsGeometry.prototype.addColors = function (colors, color, alpha, size, offset) { + if (offset === void 0) { offset = 0; } + // TODO use the premultiply bits Ivan added + var rgb = (color >> 16) + (color & 0xff00) + ((color & 0xff) << 16); + var rgba = premultiplyTint(rgb, alpha); + colors.length = Math.max(colors.length, offset + size); + for (var i = 0; i < size; i++) { + colors[offset + i] = rgba; + } + }; + /** + * Add texture id that the shader/fragment wants to use. + * @param textureIds + * @param id + * @param size + * @param offset + */ + GraphicsGeometry.prototype.addTextureIds = function (textureIds, id, size, offset) { + if (offset === void 0) { offset = 0; } + textureIds.length = Math.max(textureIds.length, offset + size); + for (var i = 0; i < size; i++) { + textureIds[offset + i] = id; + } + }; + /** + * Generates the UVs for a shape. + * @param verts - Vertices + * @param uvs - UVs + * @param texture - Reference to Texture + * @param start - Index buffer start index. + * @param size - The size/length for index buffer. + * @param matrix - Optional transform for all points. + */ + GraphicsGeometry.prototype.addUvs = function (verts, uvs, texture, start, size, matrix) { + if (matrix === void 0) { matrix = null; } + var index = 0; + var uvsStart = uvs.length; + var frame = texture.frame; + while (index < size) { + var x = verts[(start + index) * 2]; + var y = verts[((start + index) * 2) + 1]; + if (matrix) { + var nx = (matrix.a * x) + (matrix.c * y) + matrix.tx; + y = (matrix.b * x) + (matrix.d * y) + matrix.ty; + x = nx; + } + index++; + uvs.push(x / frame.width, y / frame.height); + } + var baseTexture = texture.baseTexture; + if (frame.width < baseTexture.width + || frame.height < baseTexture.height) { + this.adjustUvs(uvs, texture, uvsStart, size); + } + }; + /** + * Modify uvs array according to position of texture region + * Does not work with rotated or trimmed textures + * @param uvs - array + * @param texture - region + * @param start - starting index for uvs + * @param size - how many points to adjust + */ + GraphicsGeometry.prototype.adjustUvs = function (uvs, texture, start, size) { + var baseTexture = texture.baseTexture; + var eps = 1e-6; + var finish = start + (size * 2); + var frame = texture.frame; + var scaleX = frame.width / baseTexture.width; + var scaleY = frame.height / baseTexture.height; + var offsetX = frame.x / frame.width; + var offsetY = frame.y / frame.height; + var minX = Math.floor(uvs[start] + eps); + var minY = Math.floor(uvs[start + 1] + eps); + for (var i = start + 2; i < finish; i += 2) { + minX = Math.min(minX, Math.floor(uvs[i] + eps)); + minY = Math.min(minY, Math.floor(uvs[i + 1] + eps)); + } + offsetX -= minX; + offsetY -= minY; + for (var i = start; i < finish; i += 2) { + uvs[i] = (uvs[i] + offsetX) * scaleX; + uvs[i + 1] = (uvs[i + 1] + offsetY) * scaleY; + } + }; + /** + * The maximum number of points to consider an object "batchable", + * able to be batched by the renderer's batch system. + \ + */ + GraphicsGeometry.BATCHABLE_SIZE = 100; + return GraphicsGeometry; + }(BatchGeometry)); - return false; -} + /** + * Represents the line style for Graphics. + * @memberof PIXI + */ + var LineStyle = /** @class */ (function (_super) { + __extends$e(LineStyle, _super); + function LineStyle() { + var _this = _super !== null && _super.apply(this, arguments) || this; + /** The width (thickness) of any lines drawn. */ + _this.width = 0; + /** The alignment of any lines drawn (0.5 = middle, 1 = outer, 0 = inner). WebGL only. */ + _this.alignment = 0.5; + /** If true the lines will be draw using LINES instead of TRIANGLE_STRIP. */ + _this.native = false; + /** + * Line cap style. + * @member {PIXI.LINE_CAP} + * @default PIXI.LINE_CAP.BUTT + */ + _this.cap = exports.LINE_CAP.BUTT; + /** + * Line join style. + * @member {PIXI.LINE_JOIN} + * @default PIXI.LINE_JOIN.MITER + */ + _this.join = exports.LINE_JOIN.MITER; + /** Miter limit. */ + _this.miterLimit = 10; + return _this; + } + /** Clones the object. */ + LineStyle.prototype.clone = function () { + var obj = new LineStyle(); + obj.color = this.color; + obj.alpha = this.alpha; + obj.texture = this.texture; + obj.matrix = this.matrix; + obj.visible = this.visible; + obj.width = this.width; + obj.alignment = this.alignment; + obj.native = this.native; + obj.cap = this.cap; + obj.join = this.join; + obj.miterLimit = this.miterLimit; + return obj; + }; + /** Reset the line style to default. */ + LineStyle.prototype.reset = function () { + _super.prototype.reset.call(this); + // Override default line style color + this.color = 0x0; + this.alignment = 0.5; + this.width = 0; + this.native = false; + }; + return LineStyle; + }(FillStyle)); + + var temp = new Float32Array(3); + // a default shaders map used by graphics.. + var DEFAULT_SHADERS = {}; + /** + * The Graphics class is primarily used to render primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. However, you can also use a Graphics + * object to build a list of primitives to use as a mask, or as a complex hitArea. + * + * Please note that due to legacy naming conventions, the behavior of some functions in this class + * can be confusing. Each call to `drawRect()`, `drawPolygon()`, etc. actually stores that primitive + * in the Geometry class's GraphicsGeometry object for later use in rendering or hit testing - the + * functions do not directly draw anything to the screen. Similarly, the `clear()` function doesn't + * change the screen, it simply resets the list of primitives, which can be useful if you want to + * rebuild the contents of an existing Graphics object. + * + * Once a GraphicsGeometry list is built, you can re-use it in other Geometry objects as + * an optimization, by passing it into a new Geometry object's constructor. Because of this + * ability, it's important to call `destroy()` on Geometry objects once you are done with them, to + * properly dereference each GraphicsGeometry and prevent memory leaks. + * @memberof PIXI + */ + var Graphics = /** @class */ (function (_super) { + __extends$e(Graphics, _super); + /** + * @param geometry - Geometry to use, if omitted will create a new GraphicsGeometry instance. + */ + function Graphics(geometry) { + if (geometry === void 0) { geometry = null; } + var _this = _super.call(this) || this; + /** + * Represents the vertex and fragment shaders that processes the geometry and runs on the GPU. + * Can be shared between multiple Graphics objects. + */ + _this.shader = null; + /** Renderer plugin for batching */ + _this.pluginName = 'batch'; + /** + * Current path + * @readonly + */ + _this.currentPath = null; + /** A collections of batches! These can be drawn by the renderer batch system. */ + _this.batches = []; + /** Update dirty for limiting calculating tints for batches. */ + _this.batchTint = -1; + /** Update dirty for limiting calculating batches.*/ + _this.batchDirty = -1; + /** Copy of the object vertex data. */ + _this.vertexData = null; + /** Current fill style. */ + _this._fillStyle = new FillStyle(); + /** Current line style. */ + _this._lineStyle = new LineStyle(); + /** Current shape transform matrix. */ + _this._matrix = null; + /** Current hole mode is enabled. */ + _this._holeMode = false; + /** + * Represents the WebGL state the Graphics required to render, excludes shader and geometry. E.g., + * blend mode, culling, depth testing, direction of rendering triangles, backface, etc. + */ + _this.state = State.for2d(); + _this._geometry = geometry || new GraphicsGeometry(); + _this._geometry.refCount++; + /** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. + * This is useful if your graphics element does not change often, as it will speed up the rendering + * of the object in exchange for taking up texture memory. It is also useful if you need the graphics + * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if + * you are constantly redrawing the graphics element. + * @name cacheAsBitmap + * @member {boolean} + * @memberof PIXI.Graphics# + * @default false + */ + _this._transformID = -1; + // Set default + _this.tint = 0xFFFFFF; + _this.blendMode = exports.BLEND_MODES.NORMAL; + return _this; + } + Object.defineProperty(Graphics.prototype, "geometry", { + /** + * Includes vertex positions, face indices, normals, colors, UVs, and + * custom attributes within buffers, reducing the cost of passing all + * this data to the GPU. Can be shared between multiple Mesh or Graphics objects. + * @readonly + */ + get: function () { + return this._geometry; + }, + enumerable: false, + configurable: true + }); + /** + * Creates a new Graphics object with the same values as this one. + * Note that only the geometry of the object is cloned, not its transform (position,scale,etc) + * @returns - A clone of the graphics object + */ + Graphics.prototype.clone = function () { + this.finishPoly(); + return new Graphics(this._geometry); + }; + Object.defineProperty(Graphics.prototype, "blendMode", { + get: function () { + return this.state.blendMode; + }, + /** + * The blend mode to be applied to the graphic shape. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. Note that, since each + * primitive in the GraphicsGeometry list is rendered sequentially, modes + * such as `PIXI.BLEND_MODES.ADD` and `PIXI.BLEND_MODES.MULTIPLY` will + * be applied per-primitive. + * @default PIXI.BLEND_MODES.NORMAL + */ + set: function (value) { + this.state.blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Graphics.prototype, "tint", { + /** + * The tint applied to each graphic shape. This is a hex value. A value of + * 0xFFFFFF will remove any tint effect. + * @default 0xFFFFFF + */ + get: function () { + return this._tint; + }, + set: function (value) { + this._tint = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Graphics.prototype, "fill", { + /** + * The current fill style. + * @readonly + */ + get: function () { + return this._fillStyle; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Graphics.prototype, "line", { + /** + * The current line style. + * @readonly + */ + get: function () { + return this._lineStyle; + }, + enumerable: false, + configurable: true + }); + Graphics.prototype.lineStyle = function (options, color, alpha, alignment, native) { + if (options === void 0) { options = null; } + if (color === void 0) { color = 0x0; } + if (alpha === void 0) { alpha = 1; } + if (alignment === void 0) { alignment = 0.5; } + if (native === void 0) { native = false; } + // Support non-object params: (width, color, alpha, alignment, native) + if (typeof options === 'number') { + options = { width: options, color: color, alpha: alpha, alignment: alignment, native: native }; + } + return this.lineTextureStyle(options); + }; + /** + * Like line style but support texture for line fill. + * @param [options] - Collection of options for setting line style. + * @param {number} [options.width=0] - width of the line to draw, will update the objects stored style + * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to use + * @param {number} [options.color=0x0] - color of the line to draw, will update the objects stored style. + * Default 0xFFFFFF if texture present. + * @param {number} [options.alpha=1] - alpha of the line to draw, will update the objects stored style + * @param {PIXI.Matrix} [options.matrix=null] - Texture matrix to transform texture + * @param {number} [options.alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outer). + * WebGL only. + * @param {boolean} [options.native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP + * @param {PIXI.LINE_CAP}[options.cap=PIXI.LINE_CAP.BUTT] - line cap style + * @param {PIXI.LINE_JOIN}[options.join=PIXI.LINE_JOIN.MITER] - line join style + * @param {number}[options.miterLimit=10] - miter limit ratio + * @returns {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + Graphics.prototype.lineTextureStyle = function (options) { + // Apply defaults + options = Object.assign({ + width: 0, + texture: Texture.WHITE, + color: (options && options.texture) ? 0xFFFFFF : 0x0, + alpha: 1, + matrix: null, + alignment: 0.5, + native: false, + cap: exports.LINE_CAP.BUTT, + join: exports.LINE_JOIN.MITER, + miterLimit: 10, + }, options); + if (this.currentPath) { + this.startPoly(); + } + var visible = options.width > 0 && options.alpha > 0; + if (!visible) { + this._lineStyle.reset(); + } + else { + if (options.matrix) { + options.matrix = options.matrix.clone(); + options.matrix.invert(); + } + Object.assign(this._lineStyle, { visible: visible }, options); + } + return this; + }; + /** + * Start a polygon object internally. + * @protected + */ + Graphics.prototype.startPoly = function () { + if (this.currentPath) { + var points = this.currentPath.points; + var len = this.currentPath.points.length; + if (len > 2) { + this.drawShape(this.currentPath); + this.currentPath = new Polygon(); + this.currentPath.closeStroke = false; + this.currentPath.points.push(points[len - 2], points[len - 1]); + } + } + else { + this.currentPath = new Polygon(); + this.currentPath.closeStroke = false; + } + }; + /** + * Finish the polygon object. + * @protected + */ + Graphics.prototype.finishPoly = function () { + if (this.currentPath) { + if (this.currentPath.points.length > 2) { + this.drawShape(this.currentPath); + this.currentPath = null; + } + else { + this.currentPath.points.length = 0; + } + } + }; + /** + * Moves the current drawing position to x, y. + * @param x - the X coordinate to move to + * @param y - the Y coordinate to move to + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.moveTo = function (x, y) { + this.startPoly(); + this.currentPath.points[0] = x; + this.currentPath.points[1] = y; + return this; + }; + /** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * @param x - the X coordinate to draw to + * @param y - the Y coordinate to draw to + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.lineTo = function (x, y) { + if (!this.currentPath) { + this.moveTo(0, 0); + } + // remove duplicates.. + var points = this.currentPath.points; + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + if (fromX !== x || fromY !== y) { + points.push(x, y); + } + return this; + }; + /** + * Initialize the curve + * @param x + * @param y + */ + Graphics.prototype._initCurve = function (x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (this.currentPath) { + if (this.currentPath.points.length === 0) { + this.currentPath.points = [x, y]; + } + } + else { + this.moveTo(x, y); + } + }; + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * @param cpX - Control point x + * @param cpY - Control point y + * @param toX - Destination point x + * @param toY - Destination point y + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { + this._initCurve(); + var points = this.currentPath.points; + if (points.length === 0) { + this.moveTo(0, 0); + } + QuadraticUtils.curveTo(cpX, cpY, toX, toY, points); + return this; + }; + /** + * Calculate the points for a bezier curve and then draws it. + * @param cpX - Control point x + * @param cpY - Control point y + * @param cpX2 - Second Control point x + * @param cpY2 - Second Control point y + * @param toX - Destination point x + * @param toY - Destination point y + * @returns This Graphics object. Good for chaining method calls + */ + Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { + this._initCurve(); + BezierUtils.curveTo(cpX, cpY, cpX2, cpY2, toX, toY, this.currentPath.points); + return this; + }; + /** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * @param x1 - The x-coordinate of the first tangent point of the arc + * @param y1 - The y-coordinate of the first tangent point of the arc + * @param x2 - The x-coordinate of the end of the arc + * @param y2 - The y-coordinate of the end of the arc + * @param radius - The radius of the arc + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { + this._initCurve(x1, y1); + var points = this.currentPath.points; + var result = ArcUtils.curveTo(x1, y1, x2, y2, radius, points); + if (result) { + var cx = result.cx, cy = result.cy, radius_1 = result.radius, startAngle = result.startAngle, endAngle = result.endAngle, anticlockwise = result.anticlockwise; + this.arc(cx, cy, radius_1, startAngle, endAngle, anticlockwise); + } + return this; + }; + /** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * @param cx - The x-coordinate of the center of the circle + * @param cy - The y-coordinate of the center of the circle + * @param radius - The radius of the circle + * @param startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param endAngle - The ending angle, in radians + * @param anticlockwise - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { + if (anticlockwise === void 0) { anticlockwise = false; } + if (startAngle === endAngle) { + return this; + } + if (!anticlockwise && endAngle <= startAngle) { + endAngle += PI_2; + } + else if (anticlockwise && startAngle <= endAngle) { + startAngle += PI_2; + } + var sweep = endAngle - startAngle; + if (sweep === 0) { + return this; + } + var startX = cx + (Math.cos(startAngle) * radius); + var startY = cy + (Math.sin(startAngle) * radius); + var eps = this._geometry.closePointEps; + // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. + var points = this.currentPath ? this.currentPath.points : null; + if (points) { + // TODO: make a better fix. + // We check how far our start is from the last existing point + var xDiff = Math.abs(points[points.length - 2] - startX); + var yDiff = Math.abs(points[points.length - 1] - startY); + if (xDiff < eps && yDiff < eps) { ; } + else { + points.push(startX, startY); + } + } + else { + this.moveTo(startX, startY); + points = this.currentPath.points; + } + ArcUtils.arc(startX, startY, cx, cy, radius, startAngle, endAngle, anticlockwise, points); + return this; + }; + /** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * @param color - the color of the fill + * @param alpha - the alpha of the fill + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.beginFill = function (color, alpha) { + if (color === void 0) { color = 0; } + if (alpha === void 0) { alpha = 1; } + return this.beginTextureFill({ texture: Texture.WHITE, color: color, alpha: alpha }); + }; + /** + * Begin the texture fill + * @param options - Object object. + * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to fill + * @param {number} [options.color=0xffffff] - Background to fill behind texture + * @param {number} [options.alpha=1] - Alpha of fill + * @param {PIXI.Matrix} [options.matrix=null] - Transform matrix + * @returns {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + Graphics.prototype.beginTextureFill = function (options) { + // Apply defaults + options = Object.assign({ + texture: Texture.WHITE, + color: 0xFFFFFF, + alpha: 1, + matrix: null, + }, options); + if (this.currentPath) { + this.startPoly(); + } + var visible = options.alpha > 0; + if (!visible) { + this._fillStyle.reset(); + } + else { + if (options.matrix) { + options.matrix = options.matrix.clone(); + options.matrix.invert(); + } + Object.assign(this._fillStyle, { visible: visible }, options); + } + return this; + }; + /** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.endFill = function () { + this.finishPoly(); + this._fillStyle.reset(); + return this; + }; + /** + * Draws a rectangle shape. + * @param x - The X coord of the top-left of the rectangle + * @param y - The Y coord of the top-left of the rectangle + * @param width - The width of the rectangle + * @param height - The height of the rectangle + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawRect = function (x, y, width, height) { + return this.drawShape(new Rectangle(x, y, width, height)); + }; + /** + * Draw a rectangle shape with rounded/beveled corners. + * @param x - The X coord of the top-left of the rectangle + * @param y - The Y coord of the top-left of the rectangle + * @param width - The width of the rectangle + * @param height - The height of the rectangle + * @param radius - Radius of the rectangle corners + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) { + return this.drawShape(new RoundedRectangle(x, y, width, height, radius)); + }; + /** + * Draws a circle. + * @param x - The X coordinate of the center of the circle + * @param y - The Y coordinate of the center of the circle + * @param radius - The radius of the circle + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawCircle = function (x, y, radius) { + return this.drawShape(new Circle(x, y, radius)); + }; + /** + * Draws an ellipse. + * @param x - The X coordinate of the center of the ellipse + * @param y - The Y coordinate of the center of the ellipse + * @param width - The half width of the ellipse + * @param height - The half height of the ellipse + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawEllipse = function (x, y, width, height) { + return this.drawShape(new Ellipse(x, y, width, height)); + }; + /** + * Draws a polygon using the given path. + * @param {number[]|PIXI.IPointData[]|PIXI.Polygon} path - The path data used to construct the polygon. + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawPolygon = function () { + var arguments$1 = arguments; -/** - * Built-in hook to find TextStyle objects. - * - * @private - * @param {PIXI.TextStyle} item - Display object to check - * @param {Array<*>} queue - Collection of items to upload - * @return {boolean} if a PIXI.TextStyle object was found. - */ -function findTextStyle(item, queue) { - if (item instanceof core.TextStyle) { - if (queue.indexOf(item) === -1) { - queue.push(item); - } + var path = []; + for (var _i = 0; _i < arguments.length; _i++) { + path[_i] = arguments$1[_i]; + } + var points; + var closeStroke = true; // !!this._fillStyle; + var poly = path[0]; + // check if data has points.. + if (poly.points) { + closeStroke = poly.closeStroke; + points = poly.points; + } + else if (Array.isArray(path[0])) { + points = path[0]; + } + else { + points = path; + } + var shape = new Polygon(points); + shape.closeStroke = closeStroke; + this.drawShape(shape); + return this; + }; + /** + * Draw any shape. + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - Shape to draw + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawShape = function (shape) { + if (!this._holeMode) { + this._geometry.drawShape(shape, this._fillStyle.clone(), this._lineStyle.clone(), this._matrix); + } + else { + this._geometry.drawHole(shape, this._matrix); + } + return this; + }; + /** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.clear = function () { + this._geometry.clear(); + this._lineStyle.reset(); + this._fillStyle.reset(); + this._boundsID++; + this._matrix = null; + this._holeMode = false; + this.currentPath = null; + return this; + }; + /** + * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and + * masked with gl.scissor. + * @returns - True if only 1 rect. + */ + Graphics.prototype.isFastRect = function () { + var data = this._geometry.graphicsData; + return data.length === 1 + && data[0].shape.type === exports.SHAPES.RECT + && !data[0].matrix + && !data[0].holes.length + && !(data[0].lineStyle.visible && data[0].lineStyle.width); + }; + /** + * Renders the object using the WebGL renderer + * @param renderer - The renderer + */ + Graphics.prototype._render = function (renderer) { + this.finishPoly(); + var geometry = this._geometry; + // batch part.. + // batch it! + geometry.updateBatches(); + if (geometry.batchable) { + if (this.batchDirty !== geometry.batchDirty) { + this._populateBatches(); + } + this._renderBatched(renderer); + } + else { + // no batching... + renderer.batch.flush(); + this._renderDirect(renderer); + } + }; + /** Populating batches for rendering. */ + Graphics.prototype._populateBatches = function () { + var geometry = this._geometry; + var blendMode = this.blendMode; + var len = geometry.batches.length; + this.batchTint = -1; + this._transformID = -1; + this.batchDirty = geometry.batchDirty; + this.batches.length = len; + this.vertexData = new Float32Array(geometry.points); + for (var i = 0; i < len; i++) { + var gI = geometry.batches[i]; + var color = gI.style.color; + var vertexData = new Float32Array(this.vertexData.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2); + var uvs = new Float32Array(geometry.uvsFloat32.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2); + var indices = new Uint16Array(geometry.indicesUint16.buffer, gI.start * 2, gI.size); + var batch = { + vertexData: vertexData, + blendMode: blendMode, + indices: indices, + uvs: uvs, + _batchRGB: hex2rgb(color), + _tintRGB: color, + _texture: gI.style.texture, + alpha: gI.style.alpha, + worldAlpha: 1 + }; + this.batches[i] = batch; + } + }; + /** + * Renders the batches using the BathedRenderer plugin + * @param renderer - The renderer + */ + Graphics.prototype._renderBatched = function (renderer) { + if (!this.batches.length) { + return; + } + renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); + this.calculateVertices(); + this.calculateTints(); + for (var i = 0, l = this.batches.length; i < l; i++) { + var batch = this.batches[i]; + batch.worldAlpha = this.worldAlpha * batch.alpha; + renderer.plugins[this.pluginName].render(batch); + } + }; + /** + * Renders the graphics direct + * @param renderer - The renderer + */ + Graphics.prototype._renderDirect = function (renderer) { + var shader = this._resolveDirectShader(renderer); + var geometry = this._geometry; + var tint = this.tint; + var worldAlpha = this.worldAlpha; + var uniforms = shader.uniforms; + var drawCalls = geometry.drawCalls; + // lets set the transfomr + uniforms.translationMatrix = this.transform.worldTransform; + // and then lets set the tint.. + uniforms.tint[0] = (((tint >> 16) & 0xFF) / 255) * worldAlpha; + uniforms.tint[1] = (((tint >> 8) & 0xFF) / 255) * worldAlpha; + uniforms.tint[2] = ((tint & 0xFF) / 255) * worldAlpha; + uniforms.tint[3] = worldAlpha; + // the first draw call, we can set the uniforms of the shader directly here. + // this means that we can tack advantage of the sync function of pixi! + // bind and sync uniforms.. + // there is a way to optimise this.. + renderer.shader.bind(shader); + renderer.geometry.bind(geometry, shader); + // set state.. + renderer.state.set(this.state); + // then render the rest of them... + for (var i = 0, l = drawCalls.length; i < l; i++) { + this._renderDrawCallDirect(renderer, geometry.drawCalls[i]); + } + }; + /** + * Renders specific DrawCall + * @param renderer + * @param drawCall + */ + Graphics.prototype._renderDrawCallDirect = function (renderer, drawCall) { + var texArray = drawCall.texArray, type = drawCall.type, size = drawCall.size, start = drawCall.start; + var groupTextureCount = texArray.count; + for (var j = 0; j < groupTextureCount; j++) { + renderer.texture.bind(texArray.elements[j], j); + } + renderer.geometry.draw(type, size, start); + }; + /** + * Resolves shader for direct rendering + * @param renderer - The renderer + */ + Graphics.prototype._resolveDirectShader = function (renderer) { + var shader = this.shader; + var pluginName = this.pluginName; + if (!shader) { + // if there is no shader here, we can use the default shader. + // and that only gets created if we actually need it.. + // but may be more than one plugins for graphics + if (!DEFAULT_SHADERS[pluginName]) { + var MAX_TEXTURES = renderer.plugins[pluginName].MAX_TEXTURES; + var sampleValues = new Int32Array(MAX_TEXTURES); + for (var i = 0; i < MAX_TEXTURES; i++) { + sampleValues[i] = i; + } + var uniforms = { + tint: new Float32Array([1, 1, 1, 1]), + translationMatrix: new Matrix(), + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; + var program = renderer.plugins[pluginName]._shader.program; + DEFAULT_SHADERS[pluginName] = new Shader(program, uniforms); + } + shader = DEFAULT_SHADERS[pluginName]; + } + return shader; + }; + /** Retrieves the bounds of the graphic shape as a rectangle object. */ + Graphics.prototype._calculateBounds = function () { + this.finishPoly(); + var geometry = this._geometry; + // skipping when graphics is empty, like a container + if (!geometry.graphicsData.length) { + return; + } + var _a = geometry.bounds, minX = _a.minX, minY = _a.minY, maxX = _a.maxX, maxY = _a.maxY; + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + }; + /** + * Tests if a point is inside this graphics object + * @param point - the point to test + * @returns - the result of the test + */ + Graphics.prototype.containsPoint = function (point) { + this.worldTransform.applyInverse(point, Graphics._TEMP_POINT); + return this._geometry.containsPoint(Graphics._TEMP_POINT); + }; + /** Recalculate the tint by applying tint to batches using Graphics tint. */ + Graphics.prototype.calculateTints = function () { + if (this.batchTint !== this.tint) { + this.batchTint = this.tint; + var tintRGB = hex2rgb(this.tint, temp); + for (var i = 0; i < this.batches.length; i++) { + var batch = this.batches[i]; + var batchTint = batch._batchRGB; + var r = (tintRGB[0] * batchTint[0]) * 255; + var g = (tintRGB[1] * batchTint[1]) * 255; + var b = (tintRGB[2] * batchTint[2]) * 255; + // TODO Ivan, can this be done in one go? + var color = (r << 16) + (g << 8) + (b | 0); + batch._tintRGB = (color >> 16) + + (color & 0xff00) + + ((color & 0xff) << 16); + } + } + }; + /** If there's a transform update or a change to the shape of the geometry, recalculate the vertices. */ + Graphics.prototype.calculateVertices = function () { + var wtID = this.transform._worldID; + if (this._transformID === wtID) { + return; + } + this._transformID = wtID; + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var data = this._geometry.points; // batch.vertexDataOriginal; + var vertexData = this.vertexData; + var count = 0; + for (var i = 0; i < data.length; i += 2) { + var x = data[i]; + var y = data[i + 1]; + vertexData[count++] = (a * x) + (c * y) + tx; + vertexData[count++] = (d * y) + (b * x) + ty; + } + }; + /** + * Closes the current path. + * @returns - Returns itself. + */ + Graphics.prototype.closePath = function () { + var currentPath = this.currentPath; + if (currentPath) { + // we don't need to add extra point in the end because buildLine will take care of that + currentPath.closeStroke = true; + // ensure that the polygon is completed, and is available for hit detection + // (even if the graphics is not rendered yet) + this.finishPoly(); + } + return this; + }; + /** + * Apply a matrix to the positional data. + * @param matrix - Matrix to use for transform current shape. + * @returns - Returns itself. + */ + Graphics.prototype.setMatrix = function (matrix) { + this._matrix = matrix; + return this; + }; + /** + * Begin adding holes to the last draw shape + * IMPORTANT: holes must be fully inside a shape to work + * Also weirdness ensues if holes overlap! + * Ellipses, Circles, Rectangles and Rounded Rectangles cannot be holes or host for holes in CanvasRenderer, + * please use `moveTo` `lineTo`, `quadraticCurveTo` if you rely on pixi-legacy bundle. + * @returns - Returns itself. + */ + Graphics.prototype.beginHole = function () { + this.finishPoly(); + this._holeMode = true; + return this; + }; + /** + * End adding holes to the last draw shape. + * @returns - Returns itself. + */ + Graphics.prototype.endHole = function () { + this.finishPoly(); + this._holeMode = false; + return this; + }; + /** + * Destroys the Graphics object. + * @param options - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + Graphics.prototype.destroy = function (options) { + this._geometry.refCount--; + if (this._geometry.refCount === 0) { + this._geometry.dispose(); + } + this._matrix = null; + this.currentPath = null; + this._lineStyle.destroy(); + this._lineStyle = null; + this._fillStyle.destroy(); + this._fillStyle = null; + this._geometry = null; + this.shader = null; + this.vertexData = null; + this.batches.length = 0; + this.batches = null; + _super.prototype.destroy.call(this, options); + }; + /** + * New rendering behavior for rounded rectangles: circular arcs instead of quadratic bezier curves. + * In the next major release, we'll enable this by default. + */ + Graphics.nextRoundedRectBehavior = false; + /** + * Temporary point to use for containsPoint. + * @private + */ + Graphics._TEMP_POINT = new Point(); + return Graphics; + }(Container)); + + var graphicsUtils = { + buildPoly: buildPoly, + buildCircle: buildCircle, + buildRectangle: buildRectangle, + buildRoundedRectangle: buildRoundedRectangle, + buildLine: buildLine, + ArcUtils: ArcUtils, + BezierUtils: BezierUtils, + QuadraticUtils: QuadraticUtils, + BatchPart: BatchPart, + FILL_COMMANDS: FILL_COMMANDS, + BATCH_POOL: BATCH_POOL, + DRAW_CALL_POOL: DRAW_CALL_POOL + }; - return true; - } + /*! + * @pixi/sprite - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/sprite is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ - return false; -} + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$d = function(d, b) { + extendStatics$d = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$d(d, b); + }; -},{"../core":65,"./limiters/CountLimiter":185}],183:[function(require,module,exports){ -'use strict'; + function __extends$d(d, b) { + extendStatics$d(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } -exports.__esModule = true; + var tempPoint$2 = new Point(); + var indices = new Uint16Array([0, 1, 2, 0, 2, 3]); + /** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * A sprite can be created directly from an image like this: + * + * ```js + * let sprite = PIXI.Sprite.from('assets/image.png'); + * ``` + * + * The more efficient way to create sprites is using a {@link PIXI.Spritesheet}, + * as swapping base textures when rendering to the screen is inefficient. + * + * ```js + * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet; + * let sprite = new PIXI.Sprite(sheet.textures["image.png"]); + * ... + * } + * ``` + * @memberof PIXI + */ + var Sprite = /** @class */ (function (_super) { + __extends$d(Sprite, _super); + /** @param texture - The texture for this sprite. */ + function Sprite(texture) { + var _this = _super.call(this) || this; + _this._anchor = new ObservablePoint(_this._onAnchorUpdate, _this, (texture ? texture.defaultAnchor.x : 0), (texture ? texture.defaultAnchor.y : 0)); + _this._texture = null; + _this._width = 0; + _this._height = 0; + _this._tint = null; + _this._tintRGB = null; + _this.tint = 0xFFFFFF; + _this.blendMode = exports.BLEND_MODES.NORMAL; + _this._cachedTint = 0xFFFFFF; + _this.uvs = null; + // call texture setter + _this.texture = texture || Texture.EMPTY; + _this.vertexData = new Float32Array(8); + _this.vertexTrimmedData = null; + _this._transformID = -1; + _this._textureID = -1; + _this._transformTrimmedID = -1; + _this._textureTrimmedID = -1; + // Batchable stuff.. + // TODO could make this a mixin? + _this.indices = indices; + _this.pluginName = 'batch'; + /** + * Used to fast check if a sprite is.. a sprite! + * @member {boolean} + */ + _this.isSprite = true; + _this._roundPixels = settings.ROUND_PIXELS; + return _this; + } + /** When the texture is updated, this event will fire to update the scale and frame. */ + Sprite.prototype._onTextureUpdate = function () { + this._textureID = -1; + this._textureTrimmedID = -1; + this._cachedTint = 0xFFFFFF; + // so if _width is 0 then width was not set.. + if (this._width) { + this.scale.x = sign(this.scale.x) * this._width / this._texture.orig.width; + } + if (this._height) { + this.scale.y = sign(this.scale.y) * this._height / this._texture.orig.height; + } + }; + /** Called when the anchor position updates. */ + Sprite.prototype._onAnchorUpdate = function () { + this._transformID = -1; + this._transformTrimmedID = -1; + }; + /** Calculates worldTransform * vertices, store it in vertexData. */ + Sprite.prototype.calculateVertices = function () { + var texture = this._texture; + if (this._transformID === this.transform._worldID && this._textureID === texture._updateID) { + return; + } + // update texture UV here, because base texture can be changed without calling `_onTextureUpdate` + if (this._textureID !== texture._updateID) { + this.uvs = this._texture._uvs.uvsFloat32; + } + this._transformID = this.transform._worldID; + this._textureID = texture._updateID; + // set the vertex data + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + var trim = texture.trim; + var orig = texture.orig; + var anchor = this._anchor; + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra + // space before transforming the sprite coords. + w1 = trim.x - (anchor._x * orig.width); + w0 = w1 + trim.width; + h1 = trim.y - (anchor._y * orig.height); + h0 = h1 + trim.height; + } + else { + w1 = -anchor._x * orig.width; + w0 = w1 + orig.width; + h1 = -anchor._y * orig.height; + h0 = h1 + orig.height; + } + // xy + vertexData[0] = (a * w1) + (c * h1) + tx; + vertexData[1] = (d * h1) + (b * w1) + ty; + // xy + vertexData[2] = (a * w0) + (c * h1) + tx; + vertexData[3] = (d * h1) + (b * w0) + ty; + // xy + vertexData[4] = (a * w0) + (c * h0) + tx; + vertexData[5] = (d * h0) + (b * w0) + ty; + // xy + vertexData[6] = (a * w1) + (c * h0) + tx; + vertexData[7] = (d * h0) + (b * w1) + ty; + if (this._roundPixels) { + var resolution = settings.RESOLUTION; + for (var i = 0; i < vertexData.length; ++i) { + vertexData[i] = Math.round((vertexData[i] * resolution | 0) / resolution); + } + } + }; + /** + * Calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData. + * + * This is used to ensure that the true width and height of a trimmed texture is respected. + */ + Sprite.prototype.calculateTrimmedVertices = function () { + if (!this.vertexTrimmedData) { + this.vertexTrimmedData = new Float32Array(8); + } + else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { + return; + } + this._transformTrimmedID = this.transform._worldID; + this._textureTrimmedID = this._texture._updateID; + // lets do some special trim code! + var texture = this._texture; + var vertexData = this.vertexTrimmedData; + var orig = texture.orig; + var anchor = this._anchor; + // lets calculate the new untrimmed bounds.. + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var w1 = -anchor._x * orig.width; + var w0 = w1 + orig.width; + var h1 = -anchor._y * orig.height; + var h0 = h1 + orig.height; + // xy + vertexData[0] = (a * w1) + (c * h1) + tx; + vertexData[1] = (d * h1) + (b * w1) + ty; + // xy + vertexData[2] = (a * w0) + (c * h1) + tx; + vertexData[3] = (d * h1) + (b * w0) + ty; + // xy + vertexData[4] = (a * w0) + (c * h0) + tx; + vertexData[5] = (d * h0) + (b * w0) + ty; + // xy + vertexData[6] = (a * w1) + (c * h0) + tx; + vertexData[7] = (d * h0) + (b * w1) + ty; + }; + /** + * + * Renders the object using the WebGL renderer + * @param renderer - The webgl renderer to use. + */ + Sprite.prototype._render = function (renderer) { + this.calculateVertices(); + renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + /** Updates the bounds of the sprite. */ + Sprite.prototype._calculateBounds = function () { + var trim = this._texture.trim; + var orig = this._texture.orig; + // First lets check to see if the current texture has a trim.. + if (!trim || (trim.width === orig.width && trim.height === orig.height)) { + // no trim! lets use the usual calculations.. + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } + else { + // lets calculate a special trimmed bounds... + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } + }; + /** + * Gets the local bounds of the sprite object. + * @param rect - Optional output rectangle. + * @returns The bounds. + */ + Sprite.prototype.getLocalBounds = function (rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + if (!this._localBounds) { + this._localBounds = new Bounds(); + } + this._localBounds.minX = this._texture.orig.width * -this._anchor._x; + this._localBounds.minY = this._texture.orig.height * -this._anchor._y; + this._localBounds.maxX = this._texture.orig.width * (1 - this._anchor._x); + this._localBounds.maxY = this._texture.orig.height * (1 - this._anchor._y); + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new Rectangle(); + } + rect = this._localBoundsRect; + } + return this._localBounds.getRectangle(rect); + } + return _super.prototype.getLocalBounds.call(this, rect); + }; + /** + * Tests if a point is inside this sprite + * @param point - the point to test + * @returns The result of the test + */ + Sprite.prototype.containsPoint = function (point) { + this.worldTransform.applyInverse(point, tempPoint$2); + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1 = 0; + if (tempPoint$2.x >= x1 && tempPoint$2.x < x1 + width) { + y1 = -height * this.anchor.y; + if (tempPoint$2.y >= y1 && tempPoint$2.y < y1 + height) { + return true; + } + } + return false; + }; + /** + * Destroys this sprite and optionally its texture and children. + * @param options - Options parameter. A boolean will act as if all options + * have been set to that value + * @param [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + Sprite.prototype.destroy = function (options) { + _super.prototype.destroy.call(this, options); + this._texture.off('update', this._onTextureUpdate, this); + this._anchor = null; + var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + if (destroyTexture) { + var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + this._texture.destroy(!!destroyBaseTexture); + } + this._texture = null; + }; + // some helper functions.. + /** + * Helper function that creates a new sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * @param {string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {object} [options] - See {@link PIXI.BaseTexture}'s constructor for options. + * @returns The newly created sprite + */ + Sprite.from = function (source, options) { + var texture = (source instanceof Texture) + ? source + : Texture.from(source, options); + return new Sprite(texture); + }; + Object.defineProperty(Sprite.prototype, "roundPixels", { + get: function () { + return this._roundPixels; + }, + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * + * Advantages can include sharper image quality (like text) and faster rendering on canvas. + * The main disadvantage is movement of objects may appear less smooth. + * + * To set the global default, change {@link PIXI.settings.ROUND_PIXELS}. + * @default false + */ + set: function (value) { + if (this._roundPixels !== value) { + this._transformID = -1; + } + this._roundPixels = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "width", { + /** The width of the sprite, setting this will actually modify the scale to achieve the value set. */ + get: function () { + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function (value) { + var s = sign(this.scale.x) || 1; + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "height", { + /** The height of the sprite, setting this will actually modify the scale to achieve the value set. */ + get: function () { + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function (value) { + var s = sign(this.scale.y) || 1; + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "anchor", { + /** + * The anchor sets the origin point of the sprite. The default value is taken from the {@link PIXI.Texture|Texture} + * and passed to the constructor. + * + * The default is `(0,0)`, this means the sprite's origin is the top left. + * + * Setting the anchor to `(0.5,0.5)` means the sprite's origin is centered. + * + * Setting the anchor to `(1,1)` would mean the sprite's origin point will be the bottom right corner. + * + * If you pass only single parameter, it will set both x and y to the same value as shown in the example below. + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.anchor.set(0.5); // This will set the origin to center. (0.5) is same as (0.5, 0.5). + */ + get: function () { + return this._anchor; + }, + set: function (value) { + this._anchor.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "tint", { + /** + * The tint applied to the sprite. This is a hex value. + * + * A value of 0xFFFFFF will remove any tint effect. + * @default 0xFFFFFF + */ + get: function () { + return this._tint; + }, + set: function (value) { + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "texture", { + /** The texture that the sprite is using. */ + get: function () { + return this._texture; + }, + set: function (value) { + if (this._texture === value) { + return; + } + if (this._texture) { + this._texture.off('update', this._onTextureUpdate, this); + } + this._texture = value || Texture.EMPTY; + this._cachedTint = 0xFFFFFF; + this._textureID = -1; + this._textureTrimmedID = -1; + if (value) { + // wait for the texture to load + if (value.baseTexture.valid) { + this._onTextureUpdate(); + } + else { + value.once('update', this._onTextureUpdate, this); + } + } + }, + enumerable: false, + configurable: true + }); + return Sprite; + }(Container)); + + /*! + * @pixi/text - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/text is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ -var _core = require('../../core'); + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$c = function(d, b) { + extendStatics$c = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$c(d, b); + }; -var core = _interopRequireWildcard(_core); + function __extends$c(d, b) { + extendStatics$c(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } -var _BasePrepare2 = require('../BasePrepare'); + /** + * Constants that define the type of gradient on text. + * @static + * @constant + * @name TEXT_GRADIENT + * @memberof PIXI + * @type {object} + * @property {number} LINEAR_VERTICAL Vertical gradient + * @property {number} LINEAR_HORIZONTAL Linear gradient + */ + exports.TEXT_GRADIENT = void 0; + (function (TEXT_GRADIENT) { + TEXT_GRADIENT[TEXT_GRADIENT["LINEAR_VERTICAL"] = 0] = "LINEAR_VERTICAL"; + TEXT_GRADIENT[TEXT_GRADIENT["LINEAR_HORIZONTAL"] = 1] = "LINEAR_HORIZONTAL"; + })(exports.TEXT_GRADIENT || (exports.TEXT_GRADIENT = {})); + + // disabling eslint for now, going to rewrite this in v5 + var defaultStyle = { + align: 'left', + breakWords: false, + dropShadow: false, + dropShadowAlpha: 1, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: 'black', + dropShadowDistance: 5, + fill: 'black', + fillGradientType: exports.TEXT_GRADIENT.LINEAR_VERTICAL, + fillGradientStops: [], + fontFamily: 'Arial', + fontSize: 26, + fontStyle: 'normal', + fontVariant: 'normal', + fontWeight: 'normal', + letterSpacing: 0, + lineHeight: 0, + lineJoin: 'miter', + miterLimit: 10, + padding: 0, + stroke: 'black', + strokeThickness: 0, + textBaseline: 'alphabetic', + trim: false, + whiteSpace: 'pre', + wordWrap: false, + wordWrapWidth: 100, + leading: 0, + }; + var genericFontFamilies = [ + 'serif', + 'sans-serif', + 'monospace', + 'cursive', + 'fantasy', + 'system-ui' ]; + /** + * A TextStyle Object contains information to decorate a Text objects. + * + * An instance can be shared between multiple Text objects; then changing the style will update all text objects using it. + * + * A tool can be used to generate a text style [here](https://pixijs.io/pixi-text-style). + * + * @memberof PIXI + */ + var TextStyle = /** @class */ (function () { + /** + * @param {object} [style] - The style parameters + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), + * does not affect single line text + * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it + * needs wordWrap to be set to true + * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text + * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow + * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow + * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius + * @param {string|number} [style.dropShadowColor='black'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow + * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas + * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient + * eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours + * to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} + * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set + * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * @param {string|string[]} [style.fontFamily='Arial'] - The font family + * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, + * equivalents are '26px','20pt','160%' or '1.6em') + * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') + * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') + * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', + * '200', '300', '400', '500', '600', '700', '800' or '900') + * @param {number} [style.leading=0] - The space between lines + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 + * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses + * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve + * spiked text issues. Possible values "miter" (creates a sharp corner), "round" (creates a round corner) or "bevel" + * (creates a squared corner). + * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce + * or increase the spikiness of rendered text. + * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from + * happening by adding padding to all sides of the text. + * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * @param {boolean} [style.trim=false] - Trim transparent borders + * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. + * @param {string} [style.whiteSpace='pre'] - Determines whether newlines & spaces are collapsed or preserved "normal" + * (collapse, collapse), "pre" (preserve, preserve) | "pre-line" (preserve, collapse). It needs wordWrap to be set to true + * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used + * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true + */ + function TextStyle(style) { + this.styleID = 0; + this.reset(); + deepCopyProperties(this, style, style); + } + /** + * Creates a new TextStyle object with the same values as this one. + * Note that the only the properties of the object are cloned. + * + * @return New cloned TextStyle object + */ + TextStyle.prototype.clone = function () { + var clonedProperties = {}; + deepCopyProperties(clonedProperties, this, defaultStyle); + return new TextStyle(clonedProperties); + }; + /** Resets all properties to the defaults specified in TextStyle.prototype._default */ + TextStyle.prototype.reset = function () { + deepCopyProperties(this, defaultStyle, defaultStyle); + }; + Object.defineProperty(TextStyle.prototype, "align", { + /** + * Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text + * + * @member {string} + */ + get: function () { + return this._align; + }, + set: function (align) { + if (this._align !== align) { + this._align = align; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "breakWords", { + /** Indicates if lines can be wrapped within words, it needs wordWrap to be set to true. */ + get: function () { + return this._breakWords; + }, + set: function (breakWords) { + if (this._breakWords !== breakWords) { + this._breakWords = breakWords; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadow", { + /** Set a drop shadow for the text. */ + get: function () { + return this._dropShadow; + }, + set: function (dropShadow) { + if (this._dropShadow !== dropShadow) { + this._dropShadow = dropShadow; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowAlpha", { + /** Set alpha for the drop shadow. */ + get: function () { + return this._dropShadowAlpha; + }, + set: function (dropShadowAlpha) { + if (this._dropShadowAlpha !== dropShadowAlpha) { + this._dropShadowAlpha = dropShadowAlpha; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowAngle", { + /** Set a angle of the drop shadow. */ + get: function () { + return this._dropShadowAngle; + }, + set: function (dropShadowAngle) { + if (this._dropShadowAngle !== dropShadowAngle) { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowBlur", { + /** Set a shadow blur radius. */ + get: function () { + return this._dropShadowBlur; + }, + set: function (dropShadowBlur) { + if (this._dropShadowBlur !== dropShadowBlur) { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowColor", { + /** A fill style to be used on the dropshadow e.g 'red', '#00FF00'. */ + get: function () { + return this._dropShadowColor; + }, + set: function (dropShadowColor) { + var outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) { + this._dropShadowColor = outputColor; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowDistance", { + /** Set a distance of the drop shadow. */ + get: function () { + return this._dropShadowDistance; + }, + set: function (dropShadowDistance) { + if (this._dropShadowDistance !== dropShadowDistance) { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fill", { + /** + * A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'. + * + * Can be an array to create a gradient eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * + * @member {string|string[]|number|number[]|CanvasGradient|CanvasPattern} + */ + get: function () { + return this._fill; + }, + set: function (fill) { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + // TODO: Not sure if getColor works properly with CanvasGradient and/or CanvasPattern, can't pass in + // without casting here. + var outputColor = getColor(fill); + if (this._fill !== outputColor) { + this._fill = outputColor; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fillGradientType", { + /** + * If fill is an array of colours to create a gradient, this can change the type/direction of the gradient. + * + * @see PIXI.TEXT_GRADIENT + */ + get: function () { + return this._fillGradientType; + }, + set: function (fillGradientType) { + if (this._fillGradientType !== fillGradientType) { + this._fillGradientType = fillGradientType; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fillGradientStops", { + /** + * If fill is an array of colours to create a gradient, this array can set the stop points + * (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + */ + get: function () { + return this._fillGradientStops; + }, + set: function (fillGradientStops) { + if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) { + this._fillGradientStops = fillGradientStops; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontFamily", { + /** The font family. */ + get: function () { + return this._fontFamily; + }, + set: function (fontFamily) { + if (this.fontFamily !== fontFamily) { + this._fontFamily = fontFamily; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontSize", { + /** + * The font size + * (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em') + */ + get: function () { + return this._fontSize; + }, + set: function (fontSize) { + if (this._fontSize !== fontSize) { + this._fontSize = fontSize; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontStyle", { + /** + * The font style + * ('normal', 'italic' or 'oblique') + * + * @member {string} + */ + get: function () { + return this._fontStyle; + }, + set: function (fontStyle) { + if (this._fontStyle !== fontStyle) { + this._fontStyle = fontStyle; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontVariant", { + /** + * The font variant + * ('normal' or 'small-caps') + * + * @member {string} + */ + get: function () { + return this._fontVariant; + }, + set: function (fontVariant) { + if (this._fontVariant !== fontVariant) { + this._fontVariant = fontVariant; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontWeight", { + /** + * The font weight + * ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900') + * + * @member {string} + */ + get: function () { + return this._fontWeight; + }, + set: function (fontWeight) { + if (this._fontWeight !== fontWeight) { + this._fontWeight = fontWeight; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "letterSpacing", { + /** The amount of spacing between letters, default is 0. */ + get: function () { + return this._letterSpacing; + }, + set: function (letterSpacing) { + if (this._letterSpacing !== letterSpacing) { + this._letterSpacing = letterSpacing; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "lineHeight", { + /** The line height, a number that represents the vertical space that a letter uses. */ + get: function () { + return this._lineHeight; + }, + set: function (lineHeight) { + if (this._lineHeight !== lineHeight) { + this._lineHeight = lineHeight; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "leading", { + /** The space between lines. */ + get: function () { + return this._leading; + }, + set: function (leading) { + if (this._leading !== leading) { + this._leading = leading; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "lineJoin", { + /** + * The lineJoin property sets the type of corner created, it can resolve spiked text issues. + * Default is 'miter' (creates a sharp corner). + * + * @member {string} + */ + get: function () { + return this._lineJoin; + }, + set: function (lineJoin) { + if (this._lineJoin !== lineJoin) { + this._lineJoin = lineJoin; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "miterLimit", { + /** + * The miter limit to use when using the 'miter' lineJoin mode. + * + * This can reduce or increase the spikiness of rendered text. + */ + get: function () { + return this._miterLimit; + }, + set: function (miterLimit) { + if (this._miterLimit !== miterLimit) { + this._miterLimit = miterLimit; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "padding", { + /** + * Occasionally some fonts are cropped. Adding some padding will prevent this from happening + * by adding padding to all sides of the text. + */ + get: function () { + return this._padding; + }, + set: function (padding) { + if (this._padding !== padding) { + this._padding = padding; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "stroke", { + /** + * A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + */ + get: function () { + return this._stroke; + }, + set: function (stroke) { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + var outputColor = getColor(stroke); + if (this._stroke !== outputColor) { + this._stroke = outputColor; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "strokeThickness", { + /** + * A number that represents the thickness of the stroke. + * + * @default 0 + */ + get: function () { + return this._strokeThickness; + }, + set: function (strokeThickness) { + if (this._strokeThickness !== strokeThickness) { + this._strokeThickness = strokeThickness; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "textBaseline", { + /** + * The baseline of the text that is rendered. + * + * @member {string} + */ + get: function () { + return this._textBaseline; + }, + set: function (textBaseline) { + if (this._textBaseline !== textBaseline) { + this._textBaseline = textBaseline; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "trim", { + /** Trim transparent borders. */ + get: function () { + return this._trim; + }, + set: function (trim) { + if (this._trim !== trim) { + this._trim = trim; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "whiteSpace", { + /** + * How newlines and spaces should be handled. + * Default is 'pre' (preserve, preserve). + * + * value | New lines | Spaces + * --- | --- | --- + * 'normal' | Collapse | Collapse + * 'pre' | Preserve | Preserve + * 'pre-line' | Preserve | Collapse + * + * @member {string} + */ + get: function () { + return this._whiteSpace; + }, + set: function (whiteSpace) { + if (this._whiteSpace !== whiteSpace) { + this._whiteSpace = whiteSpace; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "wordWrap", { + /** Indicates if word wrap should be used. */ + get: function () { + return this._wordWrap; + }, + set: function (wordWrap) { + if (this._wordWrap !== wordWrap) { + this._wordWrap = wordWrap; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "wordWrapWidth", { + /** The width at which text will wrap, it needs wordWrap to be set to true. */ + get: function () { + return this._wordWrapWidth; + }, + set: function (wordWrapWidth) { + if (this._wordWrapWidth !== wordWrapWidth) { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + /** + * Generates a font style string to use for `TextMetrics.measureFont()`. + * + * @return Font style string, for passing to `TextMetrics.measureFont()` + */ + TextStyle.prototype.toFontString = function () { + // build canvas api font setting from individual components. Convert a numeric this.fontSize to px + var fontSizeString = (typeof this.fontSize === 'number') ? this.fontSize + "px" : this.fontSize; + // Clean-up fontFamily property by quoting each font name + // this will support font names with spaces + var fontFamilies = this.fontFamily; + if (!Array.isArray(this.fontFamily)) { + fontFamilies = this.fontFamily.split(','); + } + for (var i = fontFamilies.length - 1; i >= 0; i--) { + // Trim any extra white-space + var fontFamily = fontFamilies[i].trim(); + // Check if font already contains strings + if (!(/([\"\'])[^\'\"]+\1/).test(fontFamily) && genericFontFamilies.indexOf(fontFamily) < 0) { + fontFamily = "\"" + fontFamily + "\""; + } + fontFamilies[i] = fontFamily; + } + return this.fontStyle + " " + this.fontVariant + " " + this.fontWeight + " " + fontSizeString + " " + fontFamilies.join(','); + }; + return TextStyle; + }()); + /** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * @private + * @param color + * @return The color as a string. + */ + function getSingleColor(color) { + if (typeof color === 'number') { + return hex2string(color); + } + else if (typeof color === 'string') { + if (color.indexOf('0x') === 0) { + color = color.replace('0x', '#'); + } + } + return color; + } + function getColor(color) { + if (!Array.isArray(color)) { + return getSingleColor(color); + } + else { + for (var i = 0; i < color.length; ++i) { + color[i] = getSingleColor(color[i]); + } + return color; + } + } + /** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * @private + * @param array1 - First array to compare + * @param array2 - Second array to compare + * @return Do the arrays contain the same values in the same order + */ + function areArraysEqual(array1, array2) { + if (!Array.isArray(array1) || !Array.isArray(array2)) { + return false; + } + if (array1.length !== array2.length) { + return false; + } + for (var i = 0; i < array1.length; ++i) { + if (array1[i] !== array2[i]) { + return false; + } + } + return true; + } + /** + * Utility function to ensure that object properties are copied by value, and not by reference + * @private + * @param target - Target object to copy properties into + * @param source - Source object for the properties to copy + * @param propertyObj - Object containing properties names we want to loop over + */ + function deepCopyProperties(target, source, propertyObj) { + for (var prop in propertyObj) { + if (Array.isArray(source[prop])) { + target[prop] = source[prop].slice(); + } + else { + target[prop] = source[prop]; + } + } + } -var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + // Default settings used for all getContext calls + var contextSettings = { + // TextMetrics requires getImageData readback for measuring fonts. + willReadFrequently: true, + }; + /** + * The TextMetrics object represents the measurement of a block of text with a specified style. + * + * ```js + * let style = new PIXI.TextStyle({fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}) + * let textMetrics = PIXI.TextMetrics.measureText('Your text', style) + * ``` + * @memberof PIXI + */ + var TextMetrics = /** @class */ (function () { + /** + * @param text - the text that was measured + * @param style - the style that was measured + * @param width - the measured width of the text + * @param height - the measured height of the text + * @param lines - an array of the lines of text broken by new lines and wrapping if specified in style + * @param lineWidths - an array of the line widths for each line matched to `lines` + * @param lineHeight - the measured line height for this style + * @param maxLineWidth - the maximum line width for all measured lines + * @param {PIXI.IFontMetrics} fontProperties - the font properties object from TextMetrics.measureFont + */ + function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) { + this.text = text; + this.style = style; + this.width = width; + this.height = height; + this.lines = lines; + this.lineWidths = lineWidths; + this.lineHeight = lineHeight; + this.maxLineWidth = maxLineWidth; + this.fontProperties = fontProperties; + } + /** + * Measures the supplied string of text and returns a Rectangle. + * @param text - The text to measure. + * @param style - The text style to use for measuring + * @param wordWrap - Override for if word-wrap should be applied to the text. + * @param canvas - optional specification of the canvas to use for measuring. + * @returns Measured width and height of the text. + */ + TextMetrics.measureText = function (text, style, wordWrap, canvas) { + if (canvas === void 0) { canvas = TextMetrics._canvas; } + wordWrap = (wordWrap === undefined || wordWrap === null) ? style.wordWrap : wordWrap; + var font = style.toFontString(); + var fontProperties = TextMetrics.measureFont(font); + // fallback in case UA disallow canvas data extraction + // (toDataURI, getImageData functions) + if (fontProperties.fontSize === 0) { + fontProperties.fontSize = style.fontSize; + fontProperties.ascent = style.fontSize; + } + var context = canvas.getContext('2d', contextSettings); + context.font = font; + var outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text; + var lines = outputText.split(/(?:\r\n|\r|\n)/); + var lineWidths = new Array(lines.length); + var maxLineWidth = 0; + for (var i = 0; i < lines.length; i++) { + var lineWidth = context.measureText(lines[i]).width + ((lines[i].length - 1) * style.letterSpacing); + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + var width = maxLineWidth + style.strokeThickness; + if (style.dropShadow) { + width += style.dropShadowDistance; + } + var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; + var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + + ((lines.length - 1) * (lineHeight + style.leading)); + if (style.dropShadow) { + height += style.dropShadowDistance; + } + return new TextMetrics(text, style, width, height, lines, lineWidths, lineHeight + style.leading, maxLineWidth, fontProperties); + }; + /** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * @param text - String to apply word wrapping to + * @param style - the style to use when wrapping + * @param canvas - optional specification of the canvas to use for measuring. + * @returns New string with new lines applied where required + */ + TextMetrics.wordWrap = function (text, style, canvas) { + if (canvas === void 0) { canvas = TextMetrics._canvas; } + var context = canvas.getContext('2d', contextSettings); + var width = 0; + var line = ''; + var lines = ''; + var cache = Object.create(null); + var letterSpacing = style.letterSpacing, whiteSpace = style.whiteSpace; + // How to handle whitespaces + var collapseSpaces = TextMetrics.collapseSpaces(whiteSpace); + var collapseNewlines = TextMetrics.collapseNewlines(whiteSpace); + // whether or not spaces may be added to the beginning of lines + var canPrependSpaces = !collapseSpaces; + // There is letterSpacing after every char except the last one + // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_! + // so for convenience the above needs to be compared to width + 1 extra letterSpace + // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!_ + // ________________________________________________ + // And then the final space is simply no appended to each line + var wordWrapWidth = style.wordWrapWidth + letterSpacing; + // break text into words, spaces and newline chars + var tokens = TextMetrics.tokenize(text); + for (var i = 0; i < tokens.length; i++) { + // get the word, space or newlineChar + var token = tokens[i]; + // if word is a new line + if (TextMetrics.isNewline(token)) { + // keep the new line + if (!collapseNewlines) { + lines += TextMetrics.addLine(line); + canPrependSpaces = !collapseSpaces; + line = ''; + width = 0; + continue; + } + // if we should collapse new lines + // we simply convert it into a space + token = ' '; + } + // if we should collapse repeated whitespaces + if (collapseSpaces) { + // check both this and the last tokens for spaces + var currIsBreakingSpace = TextMetrics.isBreakingSpace(token); + var lastIsBreakingSpace = TextMetrics.isBreakingSpace(line[line.length - 1]); + if (currIsBreakingSpace && lastIsBreakingSpace) { + continue; + } + } + // get word width from cache if possible + var tokenWidth = TextMetrics.getFromCache(token, letterSpacing, cache, context); + // word is longer than desired bounds + if (tokenWidth > wordWrapWidth) { + // if we are not already at the beginning of a line + if (line !== '') { + // start newlines for overflow words + lines += TextMetrics.addLine(line); + line = ''; + width = 0; + } + // break large word over multiple lines + if (TextMetrics.canBreakWords(token, style.breakWords)) { + // break word into characters + var characters = TextMetrics.wordWrapSplit(token); + // loop the characters + for (var j = 0; j < characters.length; j++) { + var char = characters[j]; + var k = 1; + // we are not at the end of the token + while (characters[j + k]) { + var nextChar = characters[j + k]; + var lastChar = char[char.length - 1]; + // should not split chars + if (!TextMetrics.canBreakChars(lastChar, nextChar, token, j, style.breakWords)) { + // combine chars & move forward one + char += nextChar; + } + else { + break; + } + k++; + } + j += char.length - 1; + var characterWidth = TextMetrics.getFromCache(char, letterSpacing, cache, context); + if (characterWidth + width > wordWrapWidth) { + lines += TextMetrics.addLine(line); + canPrependSpaces = false; + line = ''; + width = 0; + } + line += char; + width += characterWidth; + } + } + // run word out of the bounds + else { + // if there are words in this line already + // finish that line and start a new one + if (line.length > 0) { + lines += TextMetrics.addLine(line); + line = ''; + width = 0; + } + var isLastToken = i === tokens.length - 1; + // give it its own line if it's not the end + lines += TextMetrics.addLine(token, !isLastToken); + canPrependSpaces = false; + line = ''; + width = 0; + } + } + // word could fit + else { + // word won't fit because of existing words + // start a new line + if (tokenWidth + width > wordWrapWidth) { + // if its a space we don't want it + canPrependSpaces = false; + // add a new line + lines += TextMetrics.addLine(line); + // start a new line + line = ''; + width = 0; + } + // don't add spaces to the beginning of lines + if (line.length > 0 || !TextMetrics.isBreakingSpace(token) || canPrependSpaces) { + // add the word to the current line + line += token; + // update width counter + width += tokenWidth; + } + } + } + lines += TextMetrics.addLine(line, false); + return lines; + }; + /** + * Convienience function for logging each line added during the wordWrap method. + * @param line - The line of text to add + * @param newLine - Add new line character to end + * @returns A formatted line + */ + TextMetrics.addLine = function (line, newLine) { + if (newLine === void 0) { newLine = true; } + line = TextMetrics.trimRight(line); + line = (newLine) ? line + "\n" : line; + return line; + }; + /** + * Gets & sets the widths of calculated characters in a cache object + * @param key - The key + * @param letterSpacing - The letter spacing + * @param cache - The cache + * @param context - The canvas context + * @returns The from cache. + */ + TextMetrics.getFromCache = function (key, letterSpacing, cache, context) { + var width = cache[key]; + if (typeof width !== 'number') { + var spacing = ((key.length) * letterSpacing); + width = context.measureText(key).width + spacing; + cache[key] = width; + } + return width; + }; + /** + * Determines whether we should collapse breaking spaces. + * @param whiteSpace - The TextStyle property whiteSpace + * @returns Should collapse + */ + TextMetrics.collapseSpaces = function (whiteSpace) { + return (whiteSpace === 'normal' || whiteSpace === 'pre-line'); + }; + /** + * Determines whether we should collapse newLine chars. + * @param whiteSpace - The white space + * @returns should collapse + */ + TextMetrics.collapseNewlines = function (whiteSpace) { + return (whiteSpace === 'normal'); + }; + /** + * Trims breaking whitespaces from string. + * @param text - The text + * @returns Trimmed string + */ + TextMetrics.trimRight = function (text) { + if (typeof text !== 'string') { + return ''; + } + for (var i = text.length - 1; i >= 0; i--) { + var char = text[i]; + if (!TextMetrics.isBreakingSpace(char)) { + break; + } + text = text.slice(0, -1); + } + return text; + }; + /** + * Determines if char is a newline. + * @param char - The character + * @returns True if newline, False otherwise. + */ + TextMetrics.isNewline = function (char) { + if (typeof char !== 'string') { + return false; + } + return (TextMetrics._newlines.indexOf(char.charCodeAt(0)) >= 0); + }; + /** + * Determines if char is a breaking whitespace. + * + * It allows one to determine whether char should be a breaking whitespace + * For example certain characters in CJK langs or numbers. + * It must return a boolean. + * @param char - The character + * @param [_nextChar] - The next character + * @returns True if whitespace, False otherwise. + */ + TextMetrics.isBreakingSpace = function (char, _nextChar) { + if (typeof char !== 'string') { + return false; + } + return (TextMetrics._breakingSpaces.indexOf(char.charCodeAt(0)) >= 0); + }; + /** + * Splits a string into words, breaking-spaces and newLine characters + * @param text - The text + * @returns A tokenized array + */ + TextMetrics.tokenize = function (text) { + var tokens = []; + var token = ''; + if (typeof text !== 'string') { + return tokens; + } + for (var i = 0; i < text.length; i++) { + var char = text[i]; + var nextChar = text[i + 1]; + if (TextMetrics.isBreakingSpace(char, nextChar) || TextMetrics.isNewline(char)) { + if (token !== '') { + tokens.push(token); + token = ''; + } + tokens.push(char); + continue; + } + token += char; + } + if (token !== '') { + tokens.push(token); + } + return tokens; + }; + /** + * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. + * + * It allows one to customise which words should break + * Examples are if the token is CJK or numbers. + * It must return a boolean. + * @param _token - The token + * @param breakWords - The style attr break words + * @returns Whether to break word or not + */ + TextMetrics.canBreakWords = function (_token, breakWords) { + return breakWords; + }; + /** + * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. + * + * It allows one to determine whether a pair of characters + * should be broken by newlines + * For example certain characters in CJK langs or numbers. + * It must return a boolean. + * @param _char - The character + * @param _nextChar - The next character + * @param _token - The token/word the characters are from + * @param _index - The index in the token of the char + * @param _breakWords - The style attr break words + * @returns whether to break word or not + */ + TextMetrics.canBreakChars = function (_char, _nextChar, _token, _index, _breakWords) { + return true; + }; + /** + * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. + * + * It is called when a token (usually a word) has to be split into separate pieces + * in order to determine the point to break a word. + * It must return an array of characters. + * @example + * // Correctly splits emojis, eg "🤪🤪" will result in two element array, each with one emoji. + * TextMetrics.wordWrapSplit = (token) => [...token]; + * @param token - The token to split + * @returns The characters of the token + */ + TextMetrics.wordWrapSplit = function (token) { + return token.split(''); + }; + /** + * Calculates the ascent, descent and fontSize of a given font-style + * @param font - String representing the style of the font + * @returns Font properties object + */ + TextMetrics.measureFont = function (font) { + // as this method is used for preparing assets, don't recalculate things if we don't need to + if (TextMetrics._fonts[font]) { + return TextMetrics._fonts[font]; + } + var properties = { + ascent: 0, + descent: 0, + fontSize: 0, + }; + var canvas = TextMetrics._canvas; + var context = TextMetrics._context; + context.font = font; + var metricsString = TextMetrics.METRICS_STRING + TextMetrics.BASELINE_SYMBOL; + var width = Math.ceil(context.measureText(metricsString).width); + var baseline = Math.ceil(context.measureText(TextMetrics.BASELINE_SYMBOL).width); + var height = Math.ceil(TextMetrics.HEIGHT_MULTIPLIER * baseline); + baseline = baseline * TextMetrics.BASELINE_MULTIPLIER | 0; + canvas.width = width; + canvas.height = height; + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + context.font = font; + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText(metricsString, 0, baseline); + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + var i = 0; + var idx = 0; + var stop = false; + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; ++i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx += line; + } + else { + break; + } + } + properties.ascent = baseline - i; + idx = pixels - line; + stop = false; + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; --i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx -= line; + } + else { + break; + } + } + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + TextMetrics._fonts[font] = properties; + return properties; + }; + /** + * Clear font metrics in metrics cache. + * @param {string} [font] - font name. If font name not set then clear cache for all fonts. + */ + TextMetrics.clearMetrics = function (font) { + if (font === void 0) { font = ''; } + if (font) { + delete TextMetrics._fonts[font]; + } + else { + TextMetrics._fonts = {}; + } + }; + Object.defineProperty(TextMetrics, "_canvas", { + /** + * Cached canvas element for measuring text + * TODO: this should be private, but isn't because of backward compat, will fix later. + * @ignore + */ + get: function () { + if (!TextMetrics.__canvas) { + var canvas = void 0; + try { + // OffscreenCanvas2D measureText can be up to 40% faster. + var c = new OffscreenCanvas(0, 0); + var context = c.getContext('2d', contextSettings); + if (context && context.measureText) { + TextMetrics.__canvas = c; + return c; + } + canvas = settings.ADAPTER.createCanvas(); + } + catch (ex) { + canvas = settings.ADAPTER.createCanvas(); + } + canvas.width = canvas.height = 10; + TextMetrics.__canvas = canvas; + } + return TextMetrics.__canvas; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextMetrics, "_context", { + /** + * TODO: this should be private, but isn't because of backward compat, will fix later. + * @ignore + */ + get: function () { + if (!TextMetrics.__context) { + TextMetrics.__context = TextMetrics._canvas.getContext('2d', contextSettings); + } + return TextMetrics.__context; + }, + enumerable: false, + configurable: true + }); + return TextMetrics; + }()); + /** + * Internal return object for {@link PIXI.TextMetrics.measureFont `TextMetrics.measureFont`}. + * @typedef {object} FontMetrics + * @property {number} ascent - The ascent distance + * @property {number} descent - The descent distance + * @property {number} fontSize - Font size from ascent to descent + * @memberof PIXI.TextMetrics + * @private + */ + /** + * Cache of {@see PIXI.TextMetrics.FontMetrics} objects. + * @memberof PIXI.TextMetrics + * @type {object} + * @private + */ + TextMetrics._fonts = {}; + /** + * String used for calculate font metrics. + * These characters are all tall to help calculate the height required for text. + * @static + * @memberof PIXI.TextMetrics + * @name METRICS_STRING + * @type {string} + * @default |ÉqÅ + */ + TextMetrics.METRICS_STRING = '|ÉqÅ'; + /** + * Baseline symbol for calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name BASELINE_SYMBOL + * @type {string} + * @default M + */ + TextMetrics.BASELINE_SYMBOL = 'M'; + /** + * Baseline multiplier for calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name BASELINE_MULTIPLIER + * @type {number} + * @default 1.4 + */ + TextMetrics.BASELINE_MULTIPLIER = 1.4; + /** + * Height multiplier for setting height of canvas to calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name HEIGHT_MULTIPLIER + * @type {number} + * @default 2.00 + */ + TextMetrics.HEIGHT_MULTIPLIER = 2.0; + /** + * Cache of new line chars. + * @memberof PIXI.TextMetrics + * @type {number[]} + * @private + */ + TextMetrics._newlines = [ + 0x000A, + 0x000D ]; + /** + * Cache of breaking spaces. + * @memberof PIXI.TextMetrics + * @type {number[]} + * @private + */ + TextMetrics._breakingSpaces = [ + 0x0009, + 0x0020, + 0x2000, + 0x2001, + 0x2002, + 0x2003, + 0x2004, + 0x2005, + 0x2006, + 0x2008, + 0x2009, + 0x200A, + 0x205F, + 0x3000 ]; + /** + * A number, or a string containing a number. + * @memberof PIXI + * @typedef {object} IFontMetrics + * @property {number} ascent - Font ascent + * @property {number} descent - Font descent + * @property {number} fontSize - Font size + */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var defaultDestroyOptions = { + texture: true, + children: false, + baseTexture: true, + }; + /** + * A Text Object will create a line or multiple lines of text. + * + * The text is created using the [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API). + * + * The primary advantage of this class over BitmapText is that you have great control over the style of the text, + * which you can change at runtime. + * + * The primary disadvantages is that each piece of text has it's own texture, which can use more memory. + * When text changes, this texture has to be re-generated and re-uploaded to the GPU, taking up time. + * + * To split a line you can use '\n' in your text string, or, on the `style` object, + * change its `wordWrap` property to true and and give the `wordWrapWidth` property a value. + * + * A Text can be created directly from a string and a style object, + * which can be generated [here](https://pixijs.io/pixi-text-style). + * + * ```js + * let text = new PIXI.Text('This is a PixiJS text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); + * ``` + * @memberof PIXI + */ + var Text = /** @class */ (function (_super) { + __extends$c(Text, _super); + /** + * @param text - The string that you would like the text to display + * @param {object|PIXI.TextStyle} [style] - The style parameters + * @param canvas - The canvas element for drawing text + */ + function Text(text, style, canvas) { + var _this = this; + var ownCanvas = false; + if (!canvas) { + canvas = settings.ADAPTER.createCanvas(); + ownCanvas = true; + } + canvas.width = 3; + canvas.height = 3; + var texture = Texture.from(canvas); + texture.orig = new Rectangle(); + texture.trim = new Rectangle(); + _this = _super.call(this, texture) || this; + _this._ownCanvas = ownCanvas; + _this.canvas = canvas; + _this.context = canvas.getContext('2d', { + // required for trimming to work without warnings + willReadFrequently: true, + }); + _this._resolution = settings.RESOLUTION; + _this._autoResolution = true; + _this._text = null; + _this._style = null; + _this._styleListener = null; + _this._font = ''; + _this.text = text; + _this.style = style; + _this.localStyleID = -1; + return _this; + } + /** + * Renders text to its canvas, and updates its texture. + * + * By default this is used internally to ensure the texture is correct before rendering, + * but it can be used called externally, for example from this class to 'pre-generate' the texture from a piece of text, + * and then shared across multiple Sprites. + * @param respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. + */ + Text.prototype.updateText = function (respectDirty) { + var style = this._style; + // check if style has changed.. + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } + if (!this.dirty && respectDirty) { + return; + } + this._font = this._style.toFontString(); + var context = this.context; + var measured = TextMetrics.measureText(this._text || ' ', this._style, this._style.wordWrap, this.canvas); + var width = measured.width; + var height = measured.height; + var lines = measured.lines; + var lineHeight = measured.lineHeight; + var lineWidths = measured.lineWidths; + var maxLineWidth = measured.maxLineWidth; + var fontProperties = measured.fontProperties; + this.canvas.width = Math.ceil(Math.ceil((Math.max(1, width) + (style.padding * 2))) * this._resolution); + this.canvas.height = Math.ceil(Math.ceil((Math.max(1, height) + (style.padding * 2))) * this._resolution); + context.scale(this._resolution, this._resolution); + context.clearRect(0, 0, this.canvas.width, this.canvas.height); + context.font = this._font; + context.lineWidth = style.strokeThickness; + context.textBaseline = style.textBaseline; + context.lineJoin = style.lineJoin; + context.miterLimit = style.miterLimit; + var linePositionX; + var linePositionY; + // require 2 passes if a shadow; the first to draw the drop shadow, the second to draw the text + var passesCount = style.dropShadow ? 2 : 1; + // For v4, we drew text at the colours of the drop shadow underneath the normal text. This gave the correct zIndex, + // but features such as alpha and shadowblur did not look right at all, since we were using actual text as a shadow. + // + // For v5.0.0, we moved over to just use the canvas API for drop shadows, which made them look much nicer and more + // visually please, but now because the stroke is drawn and then the fill, drop shadows would appear on both the fill + // and the stroke; and fill drop shadows would appear over the top of the stroke. + // + // For v5.1.1, the new route is to revert to v4 style of drawing text first to get the drop shadows underneath normal + // text, but instead drawing text in the correct location, we'll draw it off screen (-paddingY), and then adjust the + // drop shadow so only that appears on screen (+paddingY). Now we'll have the correct draw order of the shadow + // beneath the text, whilst also having the proper text shadow styling. + for (var i = 0; i < passesCount; ++i) { + var isShadowPass = style.dropShadow && i === 0; + // we only want the drop shadow, so put text way off-screen + var dsOffsetText = isShadowPass ? Math.ceil(Math.max(1, height) + (style.padding * 2)) : 0; + var dsOffsetShadow = dsOffsetText * this._resolution; + if (isShadowPass) { + // On Safari, text with gradient and drop shadows together do not position correctly + // if the scale of the canvas is not 1: https://bugs.webkit.org/show_bug.cgi?id=197689 + // Therefore we'll set the styles to be a plain black whilst generating this drop shadow + context.fillStyle = 'black'; + context.strokeStyle = 'black'; + var dropShadowColor = style.dropShadowColor; + var rgb = hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : string2hex(dropShadowColor)); + var dropShadowBlur = style.dropShadowBlur * this._resolution; + var dropShadowDistance = style.dropShadowDistance * this._resolution; + context.shadowColor = "rgba(" + rgb[0] * 255 + "," + rgb[1] * 255 + "," + rgb[2] * 255 + "," + style.dropShadowAlpha + ")"; + context.shadowBlur = dropShadowBlur; + context.shadowOffsetX = Math.cos(style.dropShadowAngle) * dropShadowDistance; + context.shadowOffsetY = (Math.sin(style.dropShadowAngle) * dropShadowDistance) + dsOffsetShadow; + } + else { + // set canvas text styles + context.fillStyle = this._generateFillStyle(style, lines, measured); + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + context.strokeStyle = style.stroke; + context.shadowColor = 'black'; + context.shadowBlur = 0; + context.shadowOffsetX = 0; + context.shadowOffsetY = 0; + } + var linePositionYShift = (lineHeight - fontProperties.fontSize) / 2; + if (!Text.nextLineHeightBehavior || lineHeight - fontProperties.fontSize < 0) { + linePositionYShift = 0; + } + // draw lines line by line + for (var i_1 = 0; i_1 < lines.length; i_1++) { + linePositionX = style.strokeThickness / 2; + linePositionY = ((style.strokeThickness / 2) + (i_1 * lineHeight)) + fontProperties.ascent + + linePositionYShift; + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[i_1]; + } + else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[i_1]) / 2; + } + if (style.stroke && style.strokeThickness) { + this.drawLetterSpacing(lines[i_1], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText, true); + } + if (style.fill) { + this.drawLetterSpacing(lines[i_1], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText); + } + } + } + this.updateTexture(); + }; + /** + * Render the text with letter-spacing. + * @param text - The text to draw + * @param x - Horizontal position to draw the text + * @param y - Vertical position to draw the text + * @param isStroke - Is this drawing for the outside stroke of the + * text? If not, it's for the inside fill + */ + Text.prototype.drawLetterSpacing = function (text, x, y, isStroke) { + if (isStroke === void 0) { isStroke = false; } + var style = this._style; + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; + // Checking that we can use moddern canvas2D api + // https://developer.chrome.com/origintrials/#/view_trial/3585991203293757441 + // note: this is unstable API, Chrome less 94 use a `textLetterSpacing`, newest use a letterSpacing + // eslint-disable-next-line max-len + var supportLetterSpacing = Text.experimentalLetterSpacing + && ('letterSpacing' in CanvasRenderingContext2D.prototype + || 'textLetterSpacing' in CanvasRenderingContext2D.prototype); + if (letterSpacing === 0 || supportLetterSpacing) { + if (supportLetterSpacing) { + this.context.letterSpacing = letterSpacing; + this.context.textLetterSpacing = letterSpacing; + } + if (isStroke) { + this.context.strokeText(text, x, y); + } + else { + this.context.fillText(text, x, y); + } + return; + } + var currentPosition = x; + // Using Array.from correctly splits characters whilst keeping emoji together. + // This is not supported on IE as it requires ES6, so regular text splitting occurs. + // This also doesn't account for emoji that are multiple emoji put together to make something else. + // Handling all of this would require a big library itself. + // https://medium.com/@giltayar/iterating-over-emoji-characters-the-es6-way-f06e4589516 + // https://github.com/orling/grapheme-splitter + var stringArray = Array.from ? Array.from(text) : text.split(''); + var previousWidth = this.context.measureText(text).width; + var currentWidth = 0; + for (var i = 0; i < stringArray.length; ++i) { + var currentChar = stringArray[i]; + if (isStroke) { + this.context.strokeText(currentChar, currentPosition, y); + } + else { + this.context.fillText(currentChar, currentPosition, y); + } + var textStr = ''; + for (var j = i + 1; j < stringArray.length; ++j) { + textStr += stringArray[j]; + } + currentWidth = this.context.measureText(textStr).width; + currentPosition += previousWidth - currentWidth + letterSpacing; + previousWidth = currentWidth; + } + }; + /** Updates texture size based on canvas size. */ + Text.prototype.updateTexture = function () { + var canvas = this.canvas; + if (this._style.trim) { + var trimmed = trimCanvas(canvas); + if (trimmed.data) { + canvas.width = trimmed.width; + canvas.height = trimmed.height; + this.context.putImageData(trimmed.data, 0, 0); + } + } + var texture = this._texture; + var style = this._style; + var padding = style.trim ? 0 : style.padding; + var baseTexture = texture.baseTexture; + texture.trim.width = texture._frame.width = canvas.width / this._resolution; + texture.trim.height = texture._frame.height = canvas.height / this._resolution; + texture.trim.x = -padding; + texture.trim.y = -padding; + texture.orig.width = texture._frame.width - (padding * 2); + texture.orig.height = texture._frame.height - (padding * 2); + // call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); + baseTexture.setRealSize(canvas.width, canvas.height, this._resolution); + texture.updateUvs(); + this.dirty = false; + }; + /** + * Renders the object using the WebGL renderer + * @param renderer - The renderer + */ + Text.prototype._render = function (renderer) { + if (this._autoResolution && this._resolution !== renderer.resolution) { + this._resolution = renderer.resolution; + this.dirty = true; + } + this.updateText(true); + _super.prototype._render.call(this, renderer); + }; + /** Updates the transform on all children of this container for rendering. */ + Text.prototype.updateTransform = function () { + this.updateText(true); + _super.prototype.updateTransform.call(this); + }; + Text.prototype.getBounds = function (skipUpdate, rect) { + this.updateText(true); + if (this._textureID === -1) { + // texture was updated: recalculate transforms + skipUpdate = false; + } + return _super.prototype.getBounds.call(this, skipUpdate, rect); + }; + /** + * Gets the local bounds of the text object. + * @param rect - The output rectangle. + * @returns The bounds. + */ + Text.prototype.getLocalBounds = function (rect) { + this.updateText(true); + return _super.prototype.getLocalBounds.call(this, rect); + }; + /** Calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. */ + Text.prototype._calculateBounds = function () { + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); + }; + /** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * @param style - The style. + * @param lines - The lines of text. + * @param metrics + * @returns The fill style + */ + Text.prototype._generateFillStyle = function (style, lines, metrics) { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + var fillStyle = style.fill; + if (!Array.isArray(fillStyle)) { + return fillStyle; + } + else if (fillStyle.length === 1) { + return fillStyle[0]; + } + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient; + // a dropshadow will enlarge the canvas and result in the gradient being + // generated with the incorrect dimensions + var dropShadowCorrection = (style.dropShadow) ? style.dropShadowDistance : 0; + // should also take padding into account, padding can offset the gradient + var padding = style.padding || 0; + var width = (this.canvas.width / this._resolution) - dropShadowCorrection - (padding * 2); + var height = (this.canvas.height / this._resolution) - dropShadowCorrection - (padding * 2); + // make a copy of the style settings, so we can manipulate them later + var fill = fillStyle.slice(); + var fillGradientStops = style.fillGradientStops.slice(); + // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 + if (!fillGradientStops.length) { + var lengthPlus1 = fill.length + 1; + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + // stop the bleeding of the last gradient on the line above to the top gradient of the this line + // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 + fill.unshift(fillStyle[0]); + fillGradientStops.unshift(0); + fill.push(fillStyle[fillStyle.length - 1]); + fillGradientStops.push(1); + if (style.fillGradientType === exports.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = this.context.createLinearGradient(width / 2, padding, width / 2, height + padding); + // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + // Actual height of the text itself, not counting spacing for lineHeight/leading/dropShadow etc + var textHeight = metrics.fontProperties.fontSize + style.strokeThickness; + for (var i = 0; i < lines.length; i++) { + var lastLineBottom = (metrics.lineHeight * (i - 1)) + textHeight; + var thisLineTop = metrics.lineHeight * i; + var thisLineGradientStart = thisLineTop; + // Handle case where last & this line overlap + if (i > 0 && lastLineBottom > thisLineTop) { + thisLineGradientStart = (thisLineTop + lastLineBottom) / 2; + } + var thisLineBottom = thisLineTop + textHeight; + var nextLineTop = metrics.lineHeight * (i + 1); + var thisLineGradientEnd = thisLineBottom; + // Handle case where this & next line overlap + if (i + 1 < lines.length && nextLineTop < thisLineBottom) { + thisLineGradientEnd = (thisLineBottom + nextLineTop) / 2; + } + // textHeight, but as a 0-1 size in global gradient stop space + var gradStopLineHeight = (thisLineGradientEnd - thisLineGradientStart) / height; + for (var j = 0; j < fill.length; j++) { + // 0-1 stop point for the current line, multiplied to global space afterwards + var lineStop = 0; + if (typeof fillGradientStops[j] === 'number') { + lineStop = fillGradientStops[j]; + } + else { + lineStop = j / fill.length; + } + var globalStop = Math.min(1, Math.max(0, (thisLineGradientStart / height) + (lineStop * gradStopLineHeight))); + // There's potential for floating point precision issues at the seams between gradient repeats. + globalStop = Number(globalStop.toFixed(5)); + gradient.addColorStop(globalStop, fill[j]); + } + } + } + else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = this.context.createLinearGradient(padding, height / 2, width + padding, height / 2); + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + var totalIterations = fill.length + 1; + var currentIteration = 1; + for (var i = 0; i < fill.length; i++) { + var stop = void 0; + if (typeof fillGradientStops[i] === 'number') { + stop = fillGradientStops[i]; + } + else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[i]); + currentIteration++; + } + } + return gradient; + }; + /** + * Destroys this text object. + * + * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as + * the majority of the time the texture will not be shared with any other Sprites. + * @param options - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well + */ + Text.prototype.destroy = function (options) { + if (typeof options === 'boolean') { + options = { children: options }; + } + options = Object.assign({}, defaultDestroyOptions, options); + _super.prototype.destroy.call(this, options); + // set canvas width and height to 0 to workaround memory leak in Safari < 13 + // https://stackoverflow.com/questions/52532614/total-canvas-memory-use-exceeds-the-maximum-limit-safari-12 + if (this._ownCanvas) { + this.canvas.height = this.canvas.width = 0; + } + // make sure to reset the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; + this._style = null; + }; + Object.defineProperty(Text.prototype, "width", { + /** The width of the Text, setting this will actually modify the scale to achieve the value set. */ + get: function () { + this.updateText(true); + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function (value) { + this.updateText(true); + var s = sign(this.scale.x) || 1; + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Text.prototype, "height", { + /** The height of the Text, setting this will actually modify the scale to achieve the value set. */ + get: function () { + this.updateText(true); + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function (value) { + this.updateText(true); + var s = sign(this.scale.y) || 1; + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Text.prototype, "style", { + /** + * Set the style of the text. + * + * Set up an event listener to listen for changes on the style object and mark the text as dirty. + */ + get: function () { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the ITextStyle + // since the setter creates the TextStyle. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + return this._style; + }, + set: function (style) { + style = style || {}; + if (style instanceof TextStyle) { + this._style = style; + } + else { + this._style = new TextStyle(style); + } + this.localStyleID = -1; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Text.prototype, "text", { + /** Set the copy for the text object. To split a line you can use '\n'. */ + get: function () { + return this._text; + }, + set: function (text) { + text = String(text === null || text === undefined ? '' : text); + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Text.prototype, "resolution", { + /** + * The resolution / device pixel ratio of the canvas. + * + * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually. + * @default 1 + */ + get: function () { + return this._resolution; + }, + set: function (value) { + this._autoResolution = false; + if (this._resolution === value) { + return; + } + this._resolution = value; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + /** + * New behavior for `lineHeight` that's meant to mimic HTML text. A value of `true` will + * make sure the first baseline is offset by the `lineHeight` value if it is greater than `fontSize`. + * A value of `false` will use the legacy behavior and not change the baseline of the first line. + * In the next major release, we'll enable this by default. + */ + Text.nextLineHeightBehavior = false; + /** + * New rendering behavior for letter-spacing which uses Chrome's new native API. This will + * lead to more accurate letter-spacing results because it does not try to manually draw + * each character. However, this Chrome API is experimental and may not serve all cases yet. + */ + Text.experimentalLetterSpacing = false; + return Text; + }(Sprite)); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + /*! + * @pixi/prepare - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/prepare is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + /** + * Default number of uploads per frame using prepare plugin. + * @static + * @memberof PIXI.settings + * @name UPLOADS_PER_FRAME + * @type {number} + * @default 4 + */ + settings.UPLOADS_PER_FRAME = 4; + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$b = function(d, b) { + extendStatics$b = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$b(d, b); + }; -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + function __extends$b(d, b) { + extendStatics$b(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + /** + * CountLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified + * number of items per frame. + * @memberof PIXI + */ + var CountLimiter = /** @class */ (function () { + /** + * @param maxItemsPerFrame - The maximum number of items that can be prepared each frame. + */ + function CountLimiter(maxItemsPerFrame) { + this.maxItemsPerFrame = maxItemsPerFrame; + this.itemsLeft = 0; + } + /** Resets any counting properties to start fresh on a new frame. */ + CountLimiter.prototype.beginFrame = function () { + this.itemsLeft = this.maxItemsPerFrame; + }; + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @returns If the item is allowed to be uploaded. + */ + CountLimiter.prototype.allowedToUpload = function () { + return this.itemsLeft-- > 0; + }; + return CountLimiter; + }()); -var CANVAS_START_SIZE = 16; + /** + * Built-in hook to find multiple textures from objects like AnimatedSprites. + * @private + * @param item - Display object to check + * @param queue - Collection of items to upload + * @returns If a PIXI.Texture object was found. + */ + function findMultipleBaseTextures(item, queue) { + var result = false; + // Objects with multiple textures + if (item && item._textures && item._textures.length) { + for (var i = 0; i < item._textures.length; i++) { + if (item._textures[i] instanceof Texture) { + var baseTexture = item._textures[i].baseTexture; + if (queue.indexOf(baseTexture) === -1) { + queue.push(baseTexture); + result = true; + } + } + } + } + return result; + } + /** + * Built-in hook to find BaseTextures from Texture. + * @private + * @param item - Display object to check + * @param queue - Collection of items to upload + * @returns If a PIXI.Texture object was found. + */ + function findBaseTexture(item, queue) { + if (item.baseTexture instanceof BaseTexture) { + var texture = item.baseTexture; + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + return true; + } + return false; + } + /** + * Built-in hook to find textures from objects. + * @private + * @param item - Display object to check + * @param queue - Collection of items to upload + * @returns If a PIXI.Texture object was found. + */ + function findTexture(item, queue) { + if (item._texture && item._texture instanceof Texture) { + var texture = item._texture.baseTexture; + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + return true; + } + return false; + } + /** + * Built-in hook to draw PIXI.Text to its texture. + * @private + * @param _helper - Not used by this upload handler + * @param item - Item to check + * @returns If item was uploaded. + */ + function drawText(_helper, item) { + if (item instanceof Text) { + // updating text will return early if it is not dirty + item.updateText(true); + return true; + } + return false; + } + /** + * Built-in hook to calculate a text style for a PIXI.Text object. + * @private + * @param _helper - Not used by this upload handler + * @param item - Item to check + * @returns If item was uploaded. + */ + function calculateTextStyle(_helper, item) { + if (item instanceof TextStyle) { + var font = item.toFontString(); + TextMetrics.measureFont(font); + return true; + } + return false; + } + /** + * Built-in hook to find Text objects. + * @private + * @param item - Display object to check + * @param queue - Collection of items to upload + * @returns if a PIXI.Text object was found. + */ + function findText(item, queue) { + if (item instanceof Text) { + // push the text style to prepare it - this can be really expensive + if (queue.indexOf(item.style) === -1) { + queue.push(item.style); + } + // also push the text object so that we can render it (to canvas/texture) if needed + if (queue.indexOf(item) === -1) { + queue.push(item); + } + // also push the Text's texture for upload to GPU + var texture = item._texture.baseTexture; + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + return true; + } + return false; + } + /** + * Built-in hook to find TextStyle objects. + * @private + * @param item - Display object to check + * @param queue - Collection of items to upload + * @returns If a PIXI.TextStyle object was found. + */ + function findTextStyle(item, queue) { + if (item instanceof TextStyle) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + return true; + } + return false; + } + /** + * The prepare manager provides functionality to upload content to the GPU. + * + * BasePrepare handles basic queuing functionality and is extended by + * {@link PIXI.Prepare} and {@link PIXI.CanvasPrepare} + * to provide preparation capabilities specific to their respective renderers. + * @example + * // Create a sprite + * const sprite = PIXI.Sprite.from('something.png'); + * + * // Load object into GPU + * app.renderer.plugins.prepare.upload(sprite, () => { + * + * //Texture(s) has been uploaded to GPU + * app.stage.addChild(sprite); + * + * }) + * @abstract + * @memberof PIXI + */ + var BasePrepare = /** @class */ (function () { + /** + * @param {PIXI.AbstractRenderer} renderer - A reference to the current renderer + */ + function BasePrepare(renderer) { + var _this = this; + this.limiter = new CountLimiter(settings.UPLOADS_PER_FRAME); + this.renderer = renderer; + this.uploadHookHelper = null; + this.queue = []; + this.addHooks = []; + this.uploadHooks = []; + this.completes = []; + this.ticking = false; + this.delayedTick = function () { + // unlikely, but in case we were destroyed between tick() and delayedTick() + if (!_this.queue) { + return; + } + _this.prepareItems(); + }; + // hooks to find the correct texture + this.registerFindHook(findText); + this.registerFindHook(findTextStyle); + this.registerFindHook(findMultipleBaseTextures); + this.registerFindHook(findBaseTexture); + this.registerFindHook(findTexture); + // upload hooks + this.registerUploadHook(drawText); + this.registerUploadHook(calculateTextStyle); + } + /** @ignore */ + BasePrepare.prototype.upload = function (item, done) { + var _this = this; + if (typeof item === 'function') { + done = item; + item = null; + } + if (done) { + deprecation('6.5.0', 'BasePrepare.upload callback is deprecated, use the return Promise instead.'); + } + return new Promise(function (resolve) { + // If a display object, search for items + // that we could upload + if (item) { + _this.add(item); + } + // TODO: remove done callback and just use resolve + var complete = function () { + done === null || done === void 0 ? void 0 : done(); + resolve(); + }; + // Get the items for upload from the display + if (_this.queue.length) { + _this.completes.push(complete); + if (!_this.ticking) { + _this.ticking = true; + Ticker.system.addOnce(_this.tick, _this, exports.UPDATE_PRIORITY.UTILITY); + } + } + else { + complete(); + } + }); + }; + /** + * Handle tick update + * @private + */ + BasePrepare.prototype.tick = function () { + setTimeout(this.delayedTick, 0); + }; + /** + * Actually prepare items. This is handled outside of the tick because it will take a while + * and we do NOT want to block the current animation frame from rendering. + * @private + */ + BasePrepare.prototype.prepareItems = function () { + this.limiter.beginFrame(); + // Upload the graphics + while (this.queue.length && this.limiter.allowedToUpload()) { + var item = this.queue[0]; + var uploaded = false; + if (item && !item._destroyed) { + for (var i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this.uploadHookHelper, item)) { + this.queue.shift(); + uploaded = true; + break; + } + } + } + if (!uploaded) { + this.queue.shift(); + } + } + // We're finished + if (!this.queue.length) { + this.ticking = false; + var completes = this.completes.slice(0); + this.completes.length = 0; + for (var i = 0, len = completes.length; i < len; i++) { + completes[i](); + } + } + else { + // if we are not finished, on the next rAF do this again + Ticker.system.addOnce(this.tick, this, exports.UPDATE_PRIORITY.UTILITY); + } + }; + /** + * Adds hooks for finding items. + * @param {Function} addHook - Function call that takes two parameters: `item:*, queue:Array` + * function must return `true` if it was able to add item to the queue. + * @returns Instance of plugin for chaining. + */ + BasePrepare.prototype.registerFindHook = function (addHook) { + if (addHook) { + this.addHooks.push(addHook); + } + return this; + }; + /** + * Adds hooks for uploading items. + * @param {Function} uploadHook - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @returns Instance of plugin for chaining. + */ + BasePrepare.prototype.registerUploadHook = function (uploadHook) { + if (uploadHook) { + this.uploadHooks.push(uploadHook); + } + return this; + }; + /** + * Manually add an item to the uploading queue. + * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to + * add to the queue + * @returns Instance of plugin for chaining. + */ + BasePrepare.prototype.add = function (item) { + // Add additional hooks for finding elements on special + // types of objects that + for (var i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } + } + // Get children recursively + if (item instanceof Container) { + for (var i = item.children.length - 1; i >= 0; i--) { + this.add(item.children[i]); + } + } + return this; + }; + /** Destroys the plugin, don't use after this. */ + BasePrepare.prototype.destroy = function () { + if (this.ticking) { + Ticker.system.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + this.limiter = null; + this.uploadHookHelper = null; + }; + return BasePrepare; + }()); -/** - * The prepare manager provides functionality to upload content to the GPU - * This cannot be done directly for Canvas like in WebGL, but the effect can be achieved by drawing - * textures to an offline canvas. - * This draw call will force the texture to be moved onto the GPU. - * - * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare - * - * @class - * @extends PIXI.prepare.BasePrepare - * @memberof PIXI.prepare - */ + /** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * @private + * @param renderer - instance of the webgl renderer + * @param item - Item to check + * @returns If item was uploaded. + */ + function uploadBaseTextures(renderer, item) { + if (item instanceof BaseTexture) { + // if the texture already has a GL texture, then the texture has been prepared or rendered + // before now. If the texture changed, then the changer should be calling texture.update() which + // reuploads the texture without need for preparing it again + if (!item._glTextures[renderer.CONTEXT_UID]) { + renderer.texture.bind(item); + } + return true; + } + return false; + } + /** + * Built-in hook to upload PIXI.Graphics to the GPU. + * @private + * @param renderer - instance of the webgl renderer + * @param item - Item to check + * @returns If item was uploaded. + */ + function uploadGraphics(renderer, item) { + if (!(item instanceof Graphics)) { + return false; + } + var geometry = item.geometry; + // update dirty graphics to get batches + item.finishPoly(); + geometry.updateBatches(); + var batches = geometry.batches; + // upload all textures found in styles + for (var i = 0; i < batches.length; i++) { + var texture = batches[i].style.texture; + if (texture) { + uploadBaseTextures(renderer, texture.baseTexture); + } + } + // if its not batchable - update vao for particular shader + if (!geometry.batchable) { + renderer.geometry.bind(geometry, item._resolveDirectShader(renderer)); + } + return true; + } + /** + * Built-in hook to find graphics. + * @private + * @param item - Display object to check + * @param queue - Collection of items to upload + * @returns if a PIXI.Graphics object was found. + */ + function findGraphics(item, queue) { + if (item instanceof Graphics) { + queue.push(item); + return true; + } + return false; + } + /** + * The prepare plugin provides renderer-specific plugins for pre-rendering DisplayObjects. These plugins are useful for + * asynchronously preparing and uploading to the GPU assets, textures, graphics waiting to be displayed. + * + * Do not instantiate this plugin directly. It is available from the `renderer.plugins` property. + * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. + * @example + * // Create a new application + * const app = new PIXI.Application(); + * document.body.appendChild(app.view); + * + * // Don't start rendering right away + * app.stop(); + * + * // create a display object + * const rect = new PIXI.Graphics() + * .beginFill(0x00ff00) + * .drawRect(40, 40, 200, 200); + * + * // Add to the stage + * app.stage.addChild(rect); + * + * // Don't start rendering until the graphic is uploaded to the GPU + * app.renderer.plugins.prepare.upload(app.stage, () => { + * app.start(); + * }); + * @memberof PIXI + */ + var Prepare = /** @class */ (function (_super) { + __extends$b(Prepare, _super); + /** + * @param {PIXI.Renderer} renderer - A reference to the current renderer + */ + function Prepare(renderer) { + var _this = _super.call(this, renderer) || this; + _this.uploadHookHelper = _this.renderer; + // Add textures and graphics to upload + _this.registerFindHook(findGraphics); + _this.registerUploadHook(uploadBaseTextures); + _this.registerUploadHook(uploadGraphics); + return _this; + } + /** @ignore */ + Prepare.extension = { + name: 'prepare', + type: exports.ExtensionType.RendererPlugin, + }; + return Prepare; + }(BasePrepare)); -var CanvasPrepare = function (_BasePrepare) { - _inherits(CanvasPrepare, _BasePrepare); - - /** - * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer - */ - function CanvasPrepare(renderer) { - _classCallCheck(this, CanvasPrepare); - - var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); - - _this.uploadHookHelper = _this; - - /** - * An offline canvas to render textures to - * @type {HTMLCanvasElement} - * @private - */ - _this.canvas = document.createElement('canvas'); - _this.canvas.width = CANVAS_START_SIZE; - _this.canvas.height = CANVAS_START_SIZE; - - /** - * The context to the canvas - * @type {CanvasRenderingContext2D} - * @private - */ - _this.ctx = _this.canvas.getContext('2d'); - - // Add textures to upload - _this.registerUploadHook(uploadBaseTextures); - return _this; - } + /** + * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified + * number of milliseconds per frame. + * @memberof PIXI + */ + var TimeLimiter = /** @class */ (function () { + /** @param maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. */ + function TimeLimiter(maxMilliseconds) { + this.maxMilliseconds = maxMilliseconds; + this.frameStart = 0; + } + /** Resets any counting properties to start fresh on a new frame. */ + TimeLimiter.prototype.beginFrame = function () { + this.frameStart = Date.now(); + }; + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @returns - If the item is allowed to be uploaded. + */ + TimeLimiter.prototype.allowedToUpload = function () { + return Date.now() - this.frameStart < this.maxMilliseconds; + }; + return TimeLimiter; + }()); + + /*! + * @pixi/spritesheet - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/spritesheet is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ - /** - * Destroys the plugin, don't use after this. - * - */ + /** + * Utility class for maintaining reference to a collection + * of Textures on a single Spritesheet. + * + * To access a sprite sheet from your code you may pass its JSON data file to Pixi's loader: + * + * ```js + * PIXI.Loader.shared.add("images/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.Loader.shared.resources["images/spritesheet.json"].spritesheet; + * ... + * } + * ``` + * + * Alternately, you may circumvent the loader by instantiating the Spritesheet directly: + * ```js + * const sheet = new PIXI.Spritesheet(texture, spritesheetData); + * await sheet.parse(); + * console.log('Spritesheet ready to use!'); + * ``` + * + * With the `sheet.textures` you can create Sprite objects,`sheet.animations` can be used to create an AnimatedSprite. + * + * Sprite sheets can be packed using tools like {@link https://codeandweb.com/texturepacker|TexturePacker}, + * {@link https://renderhjs.net/shoebox/|Shoebox} or {@link https://github.com/krzysztof-o/spritesheet.js|Spritesheet.js}. + * Default anchor points (see {@link PIXI.Texture#defaultAnchor}) and grouping of animation sprites are currently only + * supported by TexturePacker. + * @memberof PIXI + */ + var Spritesheet = /** @class */ (function () { + /** + * @param texture - Reference to the source BaseTexture object. + * @param {object} data - Spritesheet image data. + * @param resolutionFilename - The filename to consider when determining + * the resolution of the spritesheet. If not provided, the imageUrl will + * be used on the BaseTexture. + */ + function Spritesheet(texture, data, resolutionFilename) { + if (resolutionFilename === void 0) { resolutionFilename = null; } + /** For multi-packed spritesheets, this contains a reference to all the other spritesheets it depends on. */ + this.linkedSheets = []; + this._texture = texture instanceof Texture ? texture : null; + this.baseTexture = texture instanceof BaseTexture ? texture : this._texture.baseTexture; + this.textures = {}; + this.animations = {}; + this.data = data; + var resource = this.baseTexture.resource; + this.resolution = this._updateResolution(resolutionFilename || (resource ? resource.url : null)); + this._frames = this.data.frames; + this._frameKeys = Object.keys(this._frames); + this._batchIndex = 0; + this._callback = null; + } + /** + * Generate the resolution from the filename or fallback + * to the meta.scale field of the JSON data. + * @param resolutionFilename - The filename to use for resolving + * the default resolution. + * @returns Resolution to use for spritesheet. + */ + Spritesheet.prototype._updateResolution = function (resolutionFilename) { + if (resolutionFilename === void 0) { resolutionFilename = null; } + var scale = this.data.meta.scale; + // Use a defaultValue of `null` to check if a url-based resolution is set + var resolution = getResolutionOfUrl(resolutionFilename, null); + // No resolution found via URL + if (resolution === null) { + // Use the scale value or default to 1 + resolution = scale !== undefined ? parseFloat(scale) : 1; + } + // For non-1 resolutions, update baseTexture + if (resolution !== 1) { + this.baseTexture.setResolution(resolution); + } + return resolution; + }; + /** @ignore */ + Spritesheet.prototype.parse = function (callback) { + var _this = this; + if (callback) { + deprecation('6.5.0', 'Spritesheet.parse callback is deprecated, use the return Promise instead.'); + } + return new Promise(function (resolve) { + _this._callback = function (textures) { + callback === null || callback === void 0 ? void 0 : callback(textures); + resolve(textures); + }; + _this._batchIndex = 0; + if (_this._frameKeys.length <= Spritesheet.BATCH_SIZE) { + _this._processFrames(0); + _this._processAnimations(); + _this._parseComplete(); + } + else { + _this._nextBatch(); + } + }); + }; + /** + * Process a batch of frames + * @param initialFrameIndex - The index of frame to start. + */ + Spritesheet.prototype._processFrames = function (initialFrameIndex) { + var frameIndex = initialFrameIndex; + var maxFrames = Spritesheet.BATCH_SIZE; + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { + var i = this._frameKeys[frameIndex]; + var data = this._frames[i]; + var rect = data.frame; + if (rect) { + var frame = null; + var trim = null; + var sourceSize = data.trimmed !== false && data.sourceSize + ? data.sourceSize : data.frame; + var orig = new Rectangle(0, 0, Math.floor(sourceSize.w) / this.resolution, Math.floor(sourceSize.h) / this.resolution); + if (data.rotated) { + frame = new Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.h) / this.resolution, Math.floor(rect.w) / this.resolution); + } + else { + frame = new Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution); + } + // Check to see if the sprite is trimmed + if (data.trimmed !== false && data.spriteSourceSize) { + trim = new Rectangle(Math.floor(data.spriteSourceSize.x) / this.resolution, Math.floor(data.spriteSourceSize.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution); + } + this.textures[i] = new Texture(this.baseTexture, frame, orig, trim, data.rotated ? 2 : 0, data.anchor); + // lets also add the frame to pixi's global cache for 'from' and 'fromLoader' functions + Texture.addToCache(this.textures[i], i); + } + frameIndex++; + } + }; + /** Parse animations config. */ + Spritesheet.prototype._processAnimations = function () { + var animations = this.data.animations || {}; + for (var animName in animations) { + this.animations[animName] = []; + for (var i = 0; i < animations[animName].length; i++) { + var frameName = animations[animName][i]; + this.animations[animName].push(this.textures[frameName]); + } + } + }; + /** The parse has completed. */ + Spritesheet.prototype._parseComplete = function () { + var callback = this._callback; + this._callback = null; + this._batchIndex = 0; + callback.call(this, this.textures); + }; + /** Begin the next batch of textures. */ + Spritesheet.prototype._nextBatch = function () { + var _this = this; + this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); + this._batchIndex++; + setTimeout(function () { + if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) { + _this._nextBatch(); + } + else { + _this._processAnimations(); + _this._parseComplete(); + } + }, 0); + }; + /** + * Destroy Spritesheet and don't use after this. + * @param {boolean} [destroyBase=false] - Whether to destroy the base texture as well + */ + Spritesheet.prototype.destroy = function (destroyBase) { + var _a; + if (destroyBase === void 0) { destroyBase = false; } + for (var i in this.textures) { + this.textures[i].destroy(); + } + this._frames = null; + this._frameKeys = null; + this.data = null; + this.textures = null; + if (destroyBase) { + (_a = this._texture) === null || _a === void 0 ? void 0 : _a.destroy(); + this.baseTexture.destroy(); + } + this._texture = null; + this.baseTexture = null; + this.linkedSheets = []; + }; + /** The maximum number of Textures to build per process. */ + Spritesheet.BATCH_SIZE = 1000; + return Spritesheet; + }()); + /** + * Reference to Spritesheet object created. + * @member {PIXI.Spritesheet} spritesheet + * @memberof PIXI.LoaderResource + * @instance + */ + /** + * Dictionary of textures from Spritesheet. + * @member {Object} textures + * @memberof PIXI.LoaderResource + * @instance + */ + /** + * {@link PIXI.Loader} middleware for loading texture atlases that have been created with + * TexturePacker or similar JSON-based spritesheet. + * + * This middleware automatically generates Texture resources. + * + * If you're using Webpack or other bundlers and plan on bundling the atlas' JSON, + * use the {@link PIXI.Spritesheet} class to directly parse the JSON. + * + * The Loader's image Resource name is automatically appended with `"_image"`. + * If a Resource with this name is already loaded, the Loader will skip parsing the + * Spritesheet. The code below will generate an internal Loader Resource called `"myatlas_image"`. + * @example + * loader.add('myatlas', 'path/to/myatlas.json'); + * loader.load(() => { + * loader.resources.myatlas; // atlas JSON resource + * loader.resources.myatlas_image; // atlas Image resource + * }); + * @memberof PIXI + */ + var SpritesheetLoader = /** @class */ (function () { + function SpritesheetLoader() { + } + /** + * Called after a resource is loaded. + * @see PIXI.Loader.loaderMiddleware + * @param resource + * @param next + */ + SpritesheetLoader.use = function (resource, next) { + var _a, _b; + // because this is middleware, it execute in loader context. `this` = loader + var loader = this; + var imageResourceName = resource.name + "_image"; + // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists + if (!resource.data + || resource.type !== exports.LoaderResource.TYPE.JSON + || !resource.data.frames + || loader.resources[imageResourceName]) { + next(); + return; + } + // Check and add the multi atlas + // Heavily influenced and based on https://github.com/rocket-ua/pixi-tps-loader/blob/master/src/ResourceLoader.js + // eslint-disable-next-line camelcase + var multiPacks = (_b = (_a = resource.data) === null || _a === void 0 ? void 0 : _a.meta) === null || _b === void 0 ? void 0 : _b.related_multi_packs; + if (Array.isArray(multiPacks)) { + var _loop_1 = function (item) { + if (typeof item !== 'string') { + return "continue"; + } + var itemName = item.replace('.json', ''); + var itemUrl = url.resolve(resource.url.replace(loader.baseUrl, ''), item); + // Check if the file wasn't already added as multipacks are redundant + if (loader.resources[itemName] + || Object.values(loader.resources).some(function (r) { return url.format(url.parse(r.url)) === itemUrl; })) { + return "continue"; + } + var options = { + crossOrigin: resource.crossOrigin, + loadType: exports.LoaderResource.LOAD_TYPE.XHR, + xhrType: exports.LoaderResource.XHR_RESPONSE_TYPE.JSON, + parentResource: resource, + metadata: resource.metadata + }; + loader.add(itemName, itemUrl, options); + }; + for (var _i = 0, multiPacks_1 = multiPacks; _i < multiPacks_1.length; _i++) { + var item = multiPacks_1[_i]; + _loop_1(item); + } + } + var loadOptions = { + crossOrigin: resource.crossOrigin, + metadata: resource.metadata.imageMetadata, + parentResource: resource, + }; + var resourcePath = SpritesheetLoader.getResourcePath(resource, loader.baseUrl); + // load the image for this sheet + loader.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { + if (res.error) { + next(res.error); + return; + } + var spritesheet = new Spritesheet(res.texture, resource.data, resource.url); + spritesheet.parse().then(function () { + resource.spritesheet = spritesheet; + resource.textures = spritesheet.textures; + next(); + }); + }); + }; + /** + * Get the spritesheets root path + * @param resource - Resource to check path + * @param baseUrl - Base root url + */ + SpritesheetLoader.getResourcePath = function (resource, baseUrl) { + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) { + return resource.data.meta.image; + } + return url.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image); + }; + /** @ignore */ + SpritesheetLoader.extension = exports.ExtensionType.Loader; + return SpritesheetLoader; + }()); + + /*! + * @pixi/sprite-tiling - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/sprite-tiling is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ - CanvasPrepare.prototype.destroy = function destroy() { - _BasePrepare.prototype.destroy.call(this); - this.ctx = null; - this.canvas = null; - }; + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$a = function(d, b) { + extendStatics$a = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$a(d, b); + }; - return CanvasPrepare; -}(_BasePrepare3.default); + function __extends$a(d, b) { + extendStatics$a(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } -/** - * Built-in hook to upload PIXI.Texture objects to the GPU. - * - * @private - * @param {*} prepare - Instance of CanvasPrepare - * @param {*} item - Item to check - * @return {boolean} If item was uploaded. - */ + var tempPoint$1 = new Point(); + /** + * A tiling sprite is a fast way of rendering a tiling image. + * @memberof PIXI + */ + var TilingSprite = /** @class */ (function (_super) { + __extends$a(TilingSprite, _super); + /** + * @param texture - The texture of the tiling sprite. + * @param width - The width of the tiling sprite. + * @param height - The height of the tiling sprite. + */ + function TilingSprite(texture, width, height) { + if (width === void 0) { width = 100; } + if (height === void 0) { height = 100; } + var _this = _super.call(this, texture) || this; + _this.tileTransform = new Transform(); + // The width of the tiling sprite + _this._width = width; + // The height of the tiling sprite + _this._height = height; + _this.uvMatrix = _this.texture.uvMatrix || new TextureMatrix(texture); + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_render' method. + * @default 'tilingSprite' + */ + _this.pluginName = 'tilingSprite'; + _this.uvRespectAnchor = false; + return _this; + } + Object.defineProperty(TilingSprite.prototype, "clampMargin", { + /** + * Changes frame clamping in corresponding textureTransform, shortcut + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * @default 0.5 + * @member {number} + */ + get: function () { + return this.uvMatrix.clampMargin; + }, + set: function (value) { + this.uvMatrix.clampMargin = value; + this.uvMatrix.update(true); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TilingSprite.prototype, "tileScale", { + /** The scaling of the image that is being tiled. */ + get: function () { + return this.tileTransform.scale; + }, + set: function (value) { + this.tileTransform.scale.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TilingSprite.prototype, "tilePosition", { + /** The offset of the image that is being tiled. */ + get: function () { + return this.tileTransform.position; + }, + set: function (value) { + this.tileTransform.position.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + /** + * @protected + */ + TilingSprite.prototype._onTextureUpdate = function () { + if (this.uvMatrix) { + this.uvMatrix.texture = this._texture; + } + this._cachedTint = 0xFFFFFF; + }; + /** + * Renders the object using the WebGL renderer + * @param renderer - The renderer + */ + TilingSprite.prototype._render = function (renderer) { + // tweak our texture temporarily.. + var texture = this._texture; + if (!texture || !texture.valid) { + return; + } + this.tileTransform.updateLocalTransform(); + this.uvMatrix.update(); + renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + /** Updates the bounds of the tiling sprite. */ + TilingSprite.prototype._calculateBounds = function () { + var minX = this._width * -this._anchor._x; + var minY = this._height * -this._anchor._y; + var maxX = this._width * (1 - this._anchor._x); + var maxY = this._height * (1 - this._anchor._y); + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + }; + /** + * Gets the local bounds of the sprite object. + * @param rect - Optional output rectangle. + * @returns The bounds. + */ + TilingSprite.prototype.getLocalBounds = function (rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._width * -this._anchor._x; + this._bounds.minY = this._height * -this._anchor._y; + this._bounds.maxX = this._width * (1 - this._anchor._x); + this._bounds.maxY = this._height * (1 - this._anchor._y); + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new Rectangle(); + } + rect = this._localBoundsRect; + } + return this._bounds.getRectangle(rect); + } + return _super.prototype.getLocalBounds.call(this, rect); + }; + /** + * Checks if a point is inside this tiling sprite. + * @param point - The point to check. + * @returns Whether or not the sprite contains the point. + */ + TilingSprite.prototype.containsPoint = function (point) { + this.worldTransform.applyInverse(point, tempPoint$1); + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor._x; + if (tempPoint$1.x >= x1 && tempPoint$1.x < x1 + width) { + var y1 = -height * this.anchor._y; + if (tempPoint$1.y >= y1 && tempPoint$1.y < y1 + height) { + return true; + } + } + return false; + }; + /** + * Destroys this sprite and optionally its texture and children + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + TilingSprite.prototype.destroy = function (options) { + _super.prototype.destroy.call(this, options); + this.tileTransform = null; + this.uvMatrix = null; + }; + /** + * Helper function that creates a new tiling sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * @static + * @param {string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {object} options - See {@link PIXI.BaseTexture}'s constructor for options. + * @param {number} options.width - required width of the tiling sprite + * @param {number} options.height - required height of the tiling sprite + * @returns {PIXI.TilingSprite} The newly created texture + */ + TilingSprite.from = function (source, options) { + var texture = (source instanceof Texture) + ? source + : Texture.from(source, options); + return new TilingSprite(texture, options.width, options.height); + }; + Object.defineProperty(TilingSprite.prototype, "width", { + /** The width of the sprite, setting this will actually modify the scale to achieve the value set. */ + get: function () { + return this._width; + }, + set: function (value) { + this._width = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TilingSprite.prototype, "height", { + /** The height of the TilingSprite, setting this will actually modify the scale to achieve the value set. */ + get: function () { + return this._height; + }, + set: function (value) { + this._height = value; + }, + enumerable: false, + configurable: true + }); + return TilingSprite; + }(Sprite)); + + var fragmentSimpleSrc = "#version 100\n#define SHADER_NAME Tiling-Sprite-Simple-100\n\nprecision lowp float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 texSample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = texSample * uColor;\n}\n"; + + var gl1VertexSrc = "#version 100\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n"; + + var gl1FragmentSrc = "#version 100\n#ifdef GL_EXT_shader_texture_lod\n #extension GL_EXT_shader_texture_lod : enable\n#endif\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = vTextureCoord + ceil(uClampOffset - vTextureCoord);\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n vec2 unclamped = coord;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n #ifdef GL_EXT_shader_texture_lod\n vec4 texSample = unclamped == coord\n ? texture2D(uSampler, coord) \n : texture2DLodEXT(uSampler, coord, 0);\n #else\n vec4 texSample = texture2D(uSampler, coord);\n #endif\n\n gl_FragColor = texSample * uColor;\n}\n"; + + var gl2VertexSrc = "#version 300 es\n#define SHADER_NAME Tiling-Sprite-300\n\nprecision lowp float;\n\nin vec2 aVertexPosition;\nin vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nout vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n"; + + var gl2FragmentSrc = "#version 300 es\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nin vec2 vTextureCoord;\n\nout vec4 fragmentColor;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = vTextureCoord + ceil(uClampOffset - vTextureCoord);\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n vec2 unclamped = coord;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 texSample = texture(uSampler, coord, unclamped == coord ? 0.0f : -32.0f);// lod-bias very negative to force lod 0\n\n fragmentColor = texSample * uColor;\n}\n"; + + var tempMat = new Matrix(); + /** + * WebGL renderer plugin for tiling sprites + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + var TilingSpriteRenderer = /** @class */ (function (_super) { + __extends$a(TilingSpriteRenderer, _super); + /** + * constructor for renderer + * @param {PIXI.Renderer} renderer - The renderer this tiling awesomeness works for. + */ + function TilingSpriteRenderer(renderer) { + var _this = _super.call(this, renderer) || this; + // WebGL version is not available during initialization! + renderer.runners.contextChange.add(_this); + _this.quad = new QuadUv(); + /** + * The WebGL state in which this renderer will work. + * @member {PIXI.State} + * @readonly + */ + _this.state = State.for2d(); + return _this; + } + /** Creates shaders when context is initialized. */ + TilingSpriteRenderer.prototype.contextChange = function () { + var renderer = this.renderer; + var uniforms = { globals: renderer.globalUniforms }; + this.simpleShader = Shader.from(gl1VertexSrc, fragmentSimpleSrc, uniforms); + this.shader = renderer.context.webGLVersion > 1 + ? Shader.from(gl2VertexSrc, gl2FragmentSrc, uniforms) + : Shader.from(gl1VertexSrc, gl1FragmentSrc, uniforms); + }; + /** + * @param {PIXI.TilingSprite} ts - tilingSprite to be rendered + */ + TilingSpriteRenderer.prototype.render = function (ts) { + var renderer = this.renderer; + var quad = this.quad; + var vertices = quad.vertices; + vertices[0] = vertices[6] = (ts._width) * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + vertices[2] = vertices[4] = (ts._width) * (1.0 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); + var anchorX = ts.uvRespectAnchor ? ts.anchor.x : 0; + var anchorY = ts.uvRespectAnchor ? ts.anchor.y : 0; + vertices = quad.uvs; + vertices[0] = vertices[6] = -anchorX; + vertices[1] = vertices[3] = -anchorY; + vertices[2] = vertices[4] = 1.0 - anchorX; + vertices[5] = vertices[7] = 1.0 - anchorY; + quad.invalidate(); + var tex = ts._texture; + var baseTex = tex.baseTexture; + var premultiplied = baseTex.alphaMode > 0; + var lt = ts.tileTransform.localTransform; + var uv = ts.uvMatrix; + var isSimple = baseTex.isPowerOfTwo + && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + // auto, force repeat wrapMode for big tiling textures + if (isSimple) { + if (!baseTex._glTextures[renderer.CONTEXT_UID]) { + if (baseTex.wrapMode === exports.WRAP_MODES.CLAMP) { + baseTex.wrapMode = exports.WRAP_MODES.REPEAT; + } + } + else { + isSimple = baseTex.wrapMode !== exports.WRAP_MODES.CLAMP; + } + } + var shader = isSimple ? this.simpleShader : this.shader; + var w = tex.width; + var h = tex.height; + var W = ts._width; + var H = ts._height; + tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + // that part is the same as above: + // tempMat.identity(); + // tempMat.scale(tex.width, tex.height); + // tempMat.prepend(lt); + // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); + tempMat.invert(); + if (isSimple) { + tempMat.prepend(uv.mapCoord); + } + else { + shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); + shader.uniforms.uClampFrame = uv.uClampFrame; + shader.uniforms.uClampOffset = uv.uClampOffset; + } + shader.uniforms.uTransform = tempMat.toArray(true); + shader.uniforms.uColor = premultiplyTintToRgba(ts.tint, ts.worldAlpha, shader.uniforms.uColor, premultiplied); + shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); + shader.uniforms.uSampler = tex; + renderer.shader.bind(shader); + renderer.geometry.bind(quad); + this.state.blendMode = correctBlendMode(ts.blendMode, premultiplied); + renderer.state.set(this.state); + renderer.geometry.draw(this.renderer.gl.TRIANGLES, 6, 0); + }; + /** @ignore */ + TilingSpriteRenderer.extension = { + name: 'tilingSprite', + type: exports.ExtensionType.RendererPlugin, + }; + return TilingSpriteRenderer; + }(ObjectRenderer)); + + /*! + * @pixi/mesh - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/mesh is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$9 = function(d, b) { + extendStatics$9 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$9(d, b); + }; -exports.default = CanvasPrepare; -function uploadBaseTextures(prepare, item) { - if (item instanceof core.BaseTexture) { - var image = item.source; + function __extends$9(d, b) { + extendStatics$9(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } - // Sometimes images (like atlas images) report a size of zero, causing errors on windows phone. - // So if the width or height is equal to zero then use the canvas size - // Otherwise use whatever is smaller, the image dimensions or the canvas dimensions. - var imageWidth = image.width === 0 ? prepare.canvas.width : Math.min(prepare.canvas.width, image.width); - var imageHeight = image.height === 0 ? prepare.canvas.height : Math.min(prepare.canvas.height, image.height); + /** + * Class controls cache for UV mapping from Texture normal space to BaseTexture normal space. + * @memberof PIXI + */ + var MeshBatchUvs = /** @class */ (function () { + /** + * @param uvBuffer - Buffer with normalized uv's + * @param uvMatrix - Material UV matrix + */ + function MeshBatchUvs(uvBuffer, uvMatrix) { + this.uvBuffer = uvBuffer; + this.uvMatrix = uvMatrix; + this.data = null; + this._bufferUpdateId = -1; + this._textureUpdateId = -1; + this._updateID = 0; + } + /** + * Updates + * @param forceUpdate - force the update + */ + MeshBatchUvs.prototype.update = function (forceUpdate) { + if (!forceUpdate + && this._bufferUpdateId === this.uvBuffer._updateID + && this._textureUpdateId === this.uvMatrix._updateID) { + return; + } + this._bufferUpdateId = this.uvBuffer._updateID; + this._textureUpdateId = this.uvMatrix._updateID; + var data = this.uvBuffer.data; + if (!this.data || this.data.length !== data.length) { + this.data = new Float32Array(data.length); + } + this.uvMatrix.multiplyUvs(data, this.data); + this._updateID++; + }; + return MeshBatchUvs; + }()); + + var tempPoint = new Point(); + var tempPolygon = new Polygon(); + /** + * Base mesh class. + * + * This class empowers you to have maximum flexibility to render any kind of WebGL visuals you can think of. + * This class assumes a certain level of WebGL knowledge. + * If you know a bit this should abstract enough away to make your life easier! + * + * Pretty much ALL WebGL can be broken down into the following: + * - Geometry - The structure and data for the mesh. This can include anything from positions, uvs, normals, colors etc.. + * - Shader - This is the shader that PixiJS will render the geometry with (attributes in the shader must match the geometry) + * - State - This is the state of WebGL required to render the mesh. + * + * Through a combination of the above elements you can render anything you want, 2D or 3D! + * @memberof PIXI + */ + var Mesh = /** @class */ (function (_super) { + __extends$9(Mesh, _super); + /** + * @param geometry - The geometry the mesh will use. + * @param {PIXI.MeshMaterial} shader - The shader the mesh will use. + * @param state - The state that the WebGL context is required to be in to render the mesh + * if no state is provided, uses {@link PIXI.State.for2d} to create a 2D state for PixiJS. + * @param drawMode - The drawMode, can be any of the {@link PIXI.DRAW_MODES} constants. + */ + function Mesh(geometry, shader, state, drawMode) { + if (drawMode === void 0) { drawMode = exports.DRAW_MODES.TRIANGLES; } + var _this = _super.call(this) || this; + _this.geometry = geometry; + _this.shader = shader; + _this.state = state || State.for2d(); + _this.drawMode = drawMode; + _this.start = 0; + _this.size = 0; + _this.uvs = null; + _this.indices = null; + _this.vertexData = new Float32Array(1); + _this.vertexDirty = -1; + _this._transformID = -1; + _this._roundPixels = settings.ROUND_PIXELS; + _this.batchUvs = null; + return _this; + } + Object.defineProperty(Mesh.prototype, "geometry", { + /** + * Includes vertex positions, face indices, normals, colors, UVs, and + * custom attributes within buffers, reducing the cost of passing all + * this data to the GPU. Can be shared between multiple Mesh objects. + */ + get: function () { + return this._geometry; + }, + set: function (value) { + if (this._geometry === value) { + return; + } + if (this._geometry) { + this._geometry.refCount--; + if (this._geometry.refCount === 0) { + this._geometry.dispose(); + } + } + this._geometry = value; + if (this._geometry) { + this._geometry.refCount++; + } + this.vertexDirty = -1; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "uvBuffer", { + /** + * To change mesh uv's, change its uvBuffer data and increment its _updateID. + * @readonly + */ + get: function () { + return this.geometry.buffers[1]; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "verticesBuffer", { + /** + * To change mesh vertices, change its uvBuffer data and increment its _updateID. + * Incrementing _updateID is optional because most of Mesh objects do it anyway. + * @readonly + */ + get: function () { + return this.geometry.buffers[0]; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "material", { + get: function () { + return this.shader; + }, + /** Alias for {@link PIXI.Mesh#shader}. */ + set: function (value) { + this.shader = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "blendMode", { + get: function () { + return this.state.blendMode; + }, + /** + * The blend mode to be applied to the Mesh. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * @default PIXI.BLEND_MODES.NORMAL; + */ + set: function (value) { + this.state.blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "roundPixels", { + get: function () { + return this._roundPixels; + }, + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Advantages can include sharper image quality (like text) and faster rendering on canvas. + * The main disadvantage is movement of objects may appear less smooth. + * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} + * @default false + */ + set: function (value) { + if (this._roundPixels !== value) { + this._transformID = -1; + } + this._roundPixels = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "tint", { + /** + * The multiply tint applied to the Mesh. This is a hex value. A value of + * `0xFFFFFF` will remove any tint effect. + * + * Null for non-MeshMaterial shaders + * @default 0xFFFFFF + */ + get: function () { + return 'tint' in this.shader ? this.shader.tint : null; + }, + set: function (value) { + this.shader.tint = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "texture", { + /** The texture that the Mesh uses. Null for non-MeshMaterial shaders */ + get: function () { + return 'texture' in this.shader ? this.shader.texture : null; + }, + set: function (value) { + this.shader.texture = value; + }, + enumerable: false, + configurable: true + }); + /** + * Standard renderer draw. + * @param renderer - Instance to renderer. + */ + Mesh.prototype._render = function (renderer) { + // set properties for batching.. + // TODO could use a different way to grab verts? + var vertices = this.geometry.buffers[0].data; + var shader = this.shader; + // TODO benchmark check for attribute size.. + if (shader.batchable + && this.drawMode === exports.DRAW_MODES.TRIANGLES + && vertices.length < Mesh.BATCHABLE_SIZE * 2) { + this._renderToBatch(renderer); + } + else { + this._renderDefault(renderer); + } + }; + /** + * Standard non-batching way of rendering. + * @param renderer - Instance to renderer. + */ + Mesh.prototype._renderDefault = function (renderer) { + var shader = this.shader; + shader.alpha = this.worldAlpha; + if (shader.update) { + shader.update(); + } + renderer.batch.flush(); + // bind and sync uniforms.. + shader.uniforms.translationMatrix = this.transform.worldTransform.toArray(true); + renderer.shader.bind(shader); + // set state.. + renderer.state.set(this.state); + // bind the geometry... + renderer.geometry.bind(this.geometry, shader); + // then render it + renderer.geometry.draw(this.drawMode, this.size, this.start, this.geometry.instanceCount); + }; + /** + * Rendering by using the Batch system. + * @param renderer - Instance to renderer. + */ + Mesh.prototype._renderToBatch = function (renderer) { + var geometry = this.geometry; + var shader = this.shader; + if (shader.uvMatrix) { + shader.uvMatrix.update(); + this.calculateUvs(); + } + // set properties for batching.. + this.calculateVertices(); + this.indices = geometry.indexBuffer.data; + this._tintRGB = shader._tintRGB; + this._texture = shader.texture; + var pluginName = this.material.pluginName; + renderer.batch.setObjectRenderer(renderer.plugins[pluginName]); + renderer.plugins[pluginName].render(this); + }; + /** Updates vertexData field based on transform and vertices. */ + Mesh.prototype.calculateVertices = function () { + var geometry = this.geometry; + var verticesBuffer = geometry.buffers[0]; + var vertices = verticesBuffer.data; + var vertexDirtyId = verticesBuffer._updateID; + if (vertexDirtyId === this.vertexDirty && this._transformID === this.transform._worldID) { + return; + } + this._transformID = this.transform._worldID; + if (this.vertexData.length !== vertices.length) { + this.vertexData = new Float32Array(vertices.length); + } + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + for (var i = 0; i < vertexData.length / 2; i++) { + var x = vertices[(i * 2)]; + var y = vertices[(i * 2) + 1]; + vertexData[(i * 2)] = (a * x) + (c * y) + tx; + vertexData[(i * 2) + 1] = (b * x) + (d * y) + ty; + } + if (this._roundPixels) { + var resolution = settings.RESOLUTION; + for (var i = 0; i < vertexData.length; ++i) { + vertexData[i] = Math.round((vertexData[i] * resolution | 0) / resolution); + } + } + this.vertexDirty = vertexDirtyId; + }; + /** Updates uv field based on from geometry uv's or batchUvs. */ + Mesh.prototype.calculateUvs = function () { + var geomUvs = this.geometry.buffers[1]; + var shader = this.shader; + if (!shader.uvMatrix.isSimple) { + if (!this.batchUvs) { + this.batchUvs = new MeshBatchUvs(geomUvs, shader.uvMatrix); + } + this.batchUvs.update(); + this.uvs = this.batchUvs.data; + } + else { + this.uvs = geomUvs.data; + } + }; + /** + * Updates the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * there must be a aVertexPosition attribute present in the geometry for bounds to be calculated correctly. + */ + Mesh.prototype._calculateBounds = function () { + this.calculateVertices(); + this._bounds.addVertexData(this.vertexData, 0, this.vertexData.length); + }; + /** + * Tests if a point is inside this mesh. Works only for PIXI.DRAW_MODES.TRIANGLES. + * @param point - The point to test. + * @returns - The result of the test. + */ + Mesh.prototype.containsPoint = function (point) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + this.worldTransform.applyInverse(point, tempPoint); + var vertices = this.geometry.getBuffer('aVertexPosition').data; + var points = tempPolygon.points; + var indices = this.geometry.getIndex().data; + var len = indices.length; + var step = this.drawMode === 4 ? 3 : 1; + for (var i = 0; i + 2 < len; i += step) { + var ind0 = indices[i] * 2; + var ind1 = indices[i + 1] * 2; + var ind2 = indices[i + 2] * 2; + points[0] = vertices[ind0]; + points[1] = vertices[ind0 + 1]; + points[2] = vertices[ind1]; + points[3] = vertices[ind1 + 1]; + points[4] = vertices[ind2]; + points[5] = vertices[ind2 + 1]; + if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + return false; + }; + Mesh.prototype.destroy = function (options) { + _super.prototype.destroy.call(this, options); + if (this._cachedTexture) { + this._cachedTexture.destroy(); + this._cachedTexture = null; + } + this.geometry = null; + this.shader = null; + this.state = null; + this.uvs = null; + this.indices = null; + this.vertexData = null; + }; + /** The maximum number of vertices to consider batchable. Generally, the complexity of the geometry. */ + Mesh.BATCHABLE_SIZE = 100; + return Mesh; + }(Container)); + + var fragment$5 = "varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n"; + + var vertex$2 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTextureMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\n}\n"; - // Only a small subsections is required to be drawn to have the whole texture uploaded to the GPU - // A smaller draw can be faster. - prepare.ctx.drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, prepare.canvas.width, prepare.canvas.height); + /** + * Slightly opinionated default shader for PixiJS 2D objects. + * @memberof PIXI + */ + var MeshMaterial = /** @class */ (function (_super) { + __extends$9(MeshMaterial, _super); + /** + * @param uSampler - Texture that material uses to render. + * @param options - Additional options + * @param {number} [options.alpha=1] - Default alpha. + * @param {number} [options.tint=0xFFFFFF] - Default tint. + * @param {string} [options.pluginName='batch'] - Renderer plugin for batching. + * @param {PIXI.Program} [options.program=0xFFFFFF] - Custom program. + * @param {object} [options.uniforms] - Custom uniforms. + */ + function MeshMaterial(uSampler, options) { + var _this = this; + var uniforms = { + uSampler: uSampler, + alpha: 1, + uTextureMatrix: Matrix.IDENTITY, + uColor: new Float32Array([1, 1, 1, 1]), + }; + // Set defaults + options = Object.assign({ + tint: 0xFFFFFF, + alpha: 1, + pluginName: 'batch', + }, options); + if (options.uniforms) { + Object.assign(uniforms, options.uniforms); + } + _this = _super.call(this, options.program || Program.from(vertex$2, fragment$5), uniforms) || this; + _this._colorDirty = false; + _this.uvMatrix = new TextureMatrix(uSampler); + _this.batchable = options.program === undefined; + _this.pluginName = options.pluginName; + _this.tint = options.tint; + _this.alpha = options.alpha; + return _this; + } + Object.defineProperty(MeshMaterial.prototype, "texture", { + /** Reference to the texture being rendered. */ + get: function () { + return this.uniforms.uSampler; + }, + set: function (value) { + if (this.uniforms.uSampler !== value) { + if (!this.uniforms.uSampler.baseTexture.alphaMode !== !value.baseTexture.alphaMode) { + this._colorDirty = true; + } + this.uniforms.uSampler = value; + this.uvMatrix.texture = value; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(MeshMaterial.prototype, "alpha", { + get: function () { + return this._alpha; + }, + /** + * This gets automatically set by the object using this. + * @default 1 + */ + set: function (value) { + if (value === this._alpha) + { return; } + this._alpha = value; + this._colorDirty = true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(MeshMaterial.prototype, "tint", { + get: function () { + return this._tint; + }, + /** + * Multiply tint for the material. + * @default 0xFFFFFF + */ + set: function (value) { + if (value === this._tint) + { return; } + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + this._colorDirty = true; + }, + enumerable: false, + configurable: true + }); + /** Gets called automatically by the Mesh. Intended to be overridden for custom {@link MeshMaterial} objects. */ + MeshMaterial.prototype.update = function () { + if (this._colorDirty) { + this._colorDirty = false; + var baseTexture = this.texture.baseTexture; + premultiplyTintToRgba(this._tint, this._alpha, this.uniforms.uColor, baseTexture.alphaMode); + } + if (this.uvMatrix.update()) { + this.uniforms.uTextureMatrix = this.uvMatrix.mapCoord; + } + }; + return MeshMaterial; + }(Shader)); - return true; - } + /** + * Standard 2D geometry used in PixiJS. + * + * Geometry can be defined without passing in a style or data if required. + * + * ```js + * const geometry = new PIXI.Geometry(); + * + * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2); + * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1], 2); + * geometry.addIndex([0,1,2,1,3,2]); + * + * ``` + * @memberof PIXI + */ + var MeshGeometry = /** @class */ (function (_super) { + __extends$9(MeshGeometry, _super); + /** + * @param {Float32Array|number[]} [vertices] - Positional data on geometry. + * @param {Float32Array|number[]} [uvs] - Texture UVs. + * @param {Uint16Array|number[]} [index] - IndexBuffer + */ + function MeshGeometry(vertices, uvs, index) { + var _this = _super.call(this) || this; + var verticesBuffer = new Buffer(vertices); + var uvsBuffer = new Buffer(uvs, true); + var indexBuffer = new Buffer(index, true, true); + _this.addAttribute('aVertexPosition', verticesBuffer, 2, false, exports.TYPES.FLOAT) + .addAttribute('aTextureCoord', uvsBuffer, 2, false, exports.TYPES.FLOAT) + .addIndex(indexBuffer); + _this._updateId = -1; + return _this; + } + Object.defineProperty(MeshGeometry.prototype, "vertexDirtyId", { + /** + * If the vertex position is updated. + * @readonly + * @private + */ + get: function () { + return this.buffers[0]._updateID; + }, + enumerable: false, + configurable: true + }); + return MeshGeometry; + }(Geometry)); + + /*! + * @pixi/text-bitmap - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/text-bitmap is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ - return false; -} + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$8 = function(d, b) { + extendStatics$8 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$8(d, b); + }; -core.CanvasRenderer.registerPlugin('prepare', CanvasPrepare); + function __extends$8(d, b) { + extendStatics$8(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } -},{"../../core":65,"../BasePrepare":182}],184:[function(require,module,exports){ -'use strict'; + /* eslint-disable max-len */ + /** + * Normalized parsed data from .fnt files. + * @memberof PIXI + */ + var BitmapFontData = /** @class */ (function () { + function BitmapFontData() { + this.info = []; + this.common = []; + this.page = []; + this.char = []; + this.kerning = []; + this.distanceField = []; + } + return BitmapFontData; + }()); -exports.__esModule = true; + /** + * BitmapFont format that's Text-based. + * @private + */ + var TextFormat = /** @class */ (function () { + function TextFormat() { + } + /** + * Check if resource refers to txt font data. + * @param data + * @returns - True if resource could be treated as font data, false otherwise. + */ + TextFormat.test = function (data) { + return typeof data === 'string' && data.indexOf('info face=') === 0; + }; + /** + * Convert text font data to a javascript object. + * @param txt - Raw string data to be converted + * @returns - Parsed font data + */ + TextFormat.parse = function (txt) { + // Retrieve data item + var items = txt.match(/^[a-z]+\s+.+$/gm); + var rawData = { + info: [], + common: [], + page: [], + char: [], + chars: [], + kerning: [], + kernings: [], + distanceField: [], + }; + for (var i in items) { + // Extract item name + var name = items[i].match(/^[a-z]+/gm)[0]; + // Extract item attribute list as string ex.: "width=10" + var attributeList = items[i].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm); + // Convert attribute list into an object + var itemData = {}; + for (var i_1 in attributeList) { + // Split key-value pairs + var split = attributeList[i_1].split('='); + var key = split[0]; + // Remove eventual quotes from value + var strValue = split[1].replace(/"/gm, ''); + // Try to convert value into float + var floatValue = parseFloat(strValue); + // Use string value case float value is NaN + var value = isNaN(floatValue) ? strValue : floatValue; + itemData[key] = value; + } + // Push current item to the resulting data + rawData[name].push(itemData); + } + var font = new BitmapFontData(); + rawData.info.forEach(function (info) { return font.info.push({ + face: info.face, + size: parseInt(info.size, 10), + }); }); + rawData.common.forEach(function (common) { return font.common.push({ + lineHeight: parseInt(common.lineHeight, 10), + }); }); + rawData.page.forEach(function (page) { return font.page.push({ + id: parseInt(page.id, 10), + file: page.file, + }); }); + rawData.char.forEach(function (char) { return font.char.push({ + id: parseInt(char.id, 10), + page: parseInt(char.page, 10), + x: parseInt(char.x, 10), + y: parseInt(char.y, 10), + width: parseInt(char.width, 10), + height: parseInt(char.height, 10), + xoffset: parseInt(char.xoffset, 10), + yoffset: parseInt(char.yoffset, 10), + xadvance: parseInt(char.xadvance, 10), + }); }); + rawData.kerning.forEach(function (kerning) { return font.kerning.push({ + first: parseInt(kerning.first, 10), + second: parseInt(kerning.second, 10), + amount: parseInt(kerning.amount, 10), + }); }); + rawData.distanceField.forEach(function (df) { return font.distanceField.push({ + distanceRange: parseInt(df.distanceRange, 10), + fieldType: df.fieldType, + }); }); + return font; + }; + return TextFormat; + }()); -var _WebGLPrepare = require('./webgl/WebGLPrepare'); + /** + * BitmapFont format that's XML-based. + * @private + */ + var XMLFormat = /** @class */ (function () { + function XMLFormat() { + } + /** + * Check if resource refers to xml font data. + * @param data + * @returns - True if resource could be treated as font data, false otherwise. + */ + XMLFormat.test = function (data) { + return data instanceof XMLDocument + && data.getElementsByTagName('page').length + && data.getElementsByTagName('info')[0].getAttribute('face') !== null; + }; + /** + * Convert the XML into BitmapFontData that we can use. + * @param xml + * @returns - Data to use for BitmapFont + */ + XMLFormat.parse = function (xml) { + var data = new BitmapFontData(); + var info = xml.getElementsByTagName('info'); + var common = xml.getElementsByTagName('common'); + var page = xml.getElementsByTagName('page'); + var char = xml.getElementsByTagName('char'); + var kerning = xml.getElementsByTagName('kerning'); + var distanceField = xml.getElementsByTagName('distanceField'); + for (var i = 0; i < info.length; i++) { + data.info.push({ + face: info[i].getAttribute('face'), + size: parseInt(info[i].getAttribute('size'), 10), + }); + } + for (var i = 0; i < common.length; i++) { + data.common.push({ + lineHeight: parseInt(common[i].getAttribute('lineHeight'), 10), + }); + } + for (var i = 0; i < page.length; i++) { + data.page.push({ + id: parseInt(page[i].getAttribute('id'), 10) || 0, + file: page[i].getAttribute('file'), + }); + } + for (var i = 0; i < char.length; i++) { + var letter = char[i]; + data.char.push({ + id: parseInt(letter.getAttribute('id'), 10), + page: parseInt(letter.getAttribute('page'), 10) || 0, + x: parseInt(letter.getAttribute('x'), 10), + y: parseInt(letter.getAttribute('y'), 10), + width: parseInt(letter.getAttribute('width'), 10), + height: parseInt(letter.getAttribute('height'), 10), + xoffset: parseInt(letter.getAttribute('xoffset'), 10), + yoffset: parseInt(letter.getAttribute('yoffset'), 10), + xadvance: parseInt(letter.getAttribute('xadvance'), 10), + }); + } + for (var i = 0; i < kerning.length; i++) { + data.kerning.push({ + first: parseInt(kerning[i].getAttribute('first'), 10), + second: parseInt(kerning[i].getAttribute('second'), 10), + amount: parseInt(kerning[i].getAttribute('amount'), 10), + }); + } + for (var i = 0; i < distanceField.length; i++) { + data.distanceField.push({ + fieldType: distanceField[i].getAttribute('fieldType'), + distanceRange: parseInt(distanceField[i].getAttribute('distanceRange'), 10), + }); + } + return data; + }; + return XMLFormat; + }()); -Object.defineProperty(exports, 'webgl', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_WebGLPrepare).default; + /** + * BitmapFont format that's XML-based. + * @private + */ + var XMLStringFormat = /** @class */ (function () { + function XMLStringFormat() { + } + /** + * Check if resource refers to text xml font data. + * @param data + * @returns - True if resource could be treated as font data, false otherwise. + */ + XMLStringFormat.test = function (data) { + if (typeof data === 'string' && data.indexOf('') > -1) { + var xml = new globalThis.DOMParser().parseFromString(data, 'text/xml'); + return XMLFormat.test(xml); + } + return false; + }; + /** + * Convert the text XML into BitmapFontData that we can use. + * @param xmlTxt + * @returns - Data to use for BitmapFont + */ + XMLStringFormat.parse = function (xmlTxt) { + var xml = new globalThis.DOMParser().parseFromString(xmlTxt, 'text/xml'); + return XMLFormat.parse(xml); + }; + return XMLStringFormat; + }()); + + // Registered formats, maybe make this extensible in the future? + var formats = [ + TextFormat, + XMLFormat, + XMLStringFormat ]; + /** + * Auto-detect BitmapFont parsing format based on data. + * @private + * @param {any} data - Data to detect format + * @returns {any} Format or null + */ + function autoDetectFormat(data) { + for (var i = 0; i < formats.length; i++) { + if (formats[i].test(data)) { + return formats[i]; + } + } + return null; } -}); - -var _CanvasPrepare = require('./canvas/CanvasPrepare'); -Object.defineProperty(exports, 'canvas', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_CanvasPrepare).default; + // TODO: Prevent code duplication b/w generateFillStyle & Text#generateFillStyle + /** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * @private + * @param canvas + * @param context + * @param {object} style - The style. + * @param resolution + * @param {string[]} lines - The lines of text. + * @param metrics + * @returns {string|number|CanvasGradient} The fill style + */ + function generateFillStyle(canvas, context, style, resolution, lines, metrics) { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + var fillStyle = style.fill; + if (!Array.isArray(fillStyle)) { + return fillStyle; + } + else if (fillStyle.length === 1) { + return fillStyle[0]; + } + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient; + // a dropshadow will enlarge the canvas and result in the gradient being + // generated with the incorrect dimensions + var dropShadowCorrection = (style.dropShadow) ? style.dropShadowDistance : 0; + // should also take padding into account, padding can offset the gradient + var padding = style.padding || 0; + var width = (canvas.width / resolution) - dropShadowCorrection - (padding * 2); + var height = (canvas.height / resolution) - dropShadowCorrection - (padding * 2); + // make a copy of the style settings, so we can manipulate them later + var fill = fillStyle.slice(); + var fillGradientStops = style.fillGradientStops.slice(); + // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 + if (!fillGradientStops.length) { + var lengthPlus1 = fill.length + 1; + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + // stop the bleeding of the last gradient on the line above to the top gradient of the this line + // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 + fill.unshift(fillStyle[0]); + fillGradientStops.unshift(0); + fill.push(fillStyle[fillStyle.length - 1]); + fillGradientStops.push(1); + if (style.fillGradientType === exports.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = context.createLinearGradient(width / 2, padding, width / 2, height + padding); + // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + // There's potential for floating point precision issues at the seams between gradient repeats. + // The loop below generates the stops in order, so track the last generated one to prevent + // floating point precision from making us go the teeniest bit backwards, resulting in + // the first and last colors getting swapped. + var lastIterationStop = 0; + // Actual height of the text itself, not counting spacing for lineHeight/leading/dropShadow etc + var textHeight = metrics.fontProperties.fontSize + style.strokeThickness; + // textHeight, but as a 0-1 size in global gradient stop space + var gradStopLineHeight = textHeight / height; + for (var i = 0; i < lines.length; i++) { + var thisLineTop = metrics.lineHeight * i; + for (var j = 0; j < fill.length; j++) { + // 0-1 stop point for the current line, multiplied to global space afterwards + var lineStop = 0; + if (typeof fillGradientStops[j] === 'number') { + lineStop = fillGradientStops[j]; + } + else { + lineStop = j / fill.length; + } + var globalStop = (thisLineTop / height) + (lineStop * gradStopLineHeight); + // Prevent color stop generation going backwards from floating point imprecision + var clampedStop = Math.max(lastIterationStop, globalStop); + clampedStop = Math.min(clampedStop, 1); // Cap at 1 as well for safety's sake to avoid a possible throw. + gradient.addColorStop(clampedStop, fill[j]); + lastIterationStop = clampedStop; + } + } + } + else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = context.createLinearGradient(padding, height / 2, width + padding, height / 2); + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + var totalIterations = fill.length + 1; + var currentIteration = 1; + for (var i = 0; i < fill.length; i++) { + var stop = void 0; + if (typeof fillGradientStops[i] === 'number') { + stop = fillGradientStops[i]; + } + else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[i]); + currentIteration++; + } + } + return gradient; } -}); - -var _BasePrepare = require('./BasePrepare'); -Object.defineProperty(exports, 'BasePrepare', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_BasePrepare).default; + // TODO: Prevent code duplication b/w drawGlyph & Text#updateText + /** + * Draws the glyph `metrics.text` on the given canvas. + * + * Ignored because not directly exposed. + * @ignore + * @param {HTMLCanvasElement} canvas + * @param {CanvasRenderingContext2D} context + * @param {TextMetrics} metrics + * @param {number} x + * @param {number} y + * @param {number} resolution + * @param {TextStyle} style + */ + function drawGlyph(canvas, context, metrics, x, y, resolution, style) { + var char = metrics.text; + var fontProperties = metrics.fontProperties; + context.translate(x, y); + context.scale(resolution, resolution); + var tx = style.strokeThickness / 2; + var ty = -(style.strokeThickness / 2); + context.font = style.toFontString(); + context.lineWidth = style.strokeThickness; + context.textBaseline = style.textBaseline; + context.lineJoin = style.lineJoin; + context.miterLimit = style.miterLimit; + // set canvas text styles + context.fillStyle = generateFillStyle(canvas, context, style, resolution, [char], metrics); + context.strokeStyle = style.stroke; + if (style.dropShadow) { + var dropShadowColor = style.dropShadowColor; + var rgb = hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : string2hex(dropShadowColor)); + var dropShadowBlur = style.dropShadowBlur * resolution; + var dropShadowDistance = style.dropShadowDistance * resolution; + context.shadowColor = "rgba(" + rgb[0] * 255 + "," + rgb[1] * 255 + "," + rgb[2] * 255 + "," + style.dropShadowAlpha + ")"; + context.shadowBlur = dropShadowBlur; + context.shadowOffsetX = Math.cos(style.dropShadowAngle) * dropShadowDistance; + context.shadowOffsetY = Math.sin(style.dropShadowAngle) * dropShadowDistance; + } + else { + context.shadowColor = 'black'; + context.shadowBlur = 0; + context.shadowOffsetX = 0; + context.shadowOffsetY = 0; + } + if (style.stroke && style.strokeThickness) { + context.strokeText(char, tx, ty + metrics.lineHeight - fontProperties.descent); + } + if (style.fill) { + context.fillText(char, tx, ty + metrics.lineHeight - fontProperties.descent); + } + context.setTransform(1, 0, 0, 1, 0, 0); // defaults needed for older browsers (e.g. Opera 29) + context.fillStyle = 'rgba(0, 0, 0, 0)'; } -}); - -var _CountLimiter = require('./limiters/CountLimiter'); -Object.defineProperty(exports, 'CountLimiter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_CountLimiter).default; + /** + * Ponyfill for IE because it doesn't support `Array.from` + * @param text + * @private + */ + function splitTextToCharacters(text) { + return Array.from ? Array.from(text) : text.split(''); } -}); - -var _TimeLimiter = require('./limiters/TimeLimiter'); -Object.defineProperty(exports, 'TimeLimiter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_TimeLimiter).default; + /** + * Processes the passed character set data and returns a flattened array of all the characters. + * + * Ignored because not directly exposed. + * @ignore + * @param {string | string[] | string[][] } chars + * @returns {string[]} the flattened array of characters + */ + function resolveCharacters(chars) { + // Split the chars string into individual characters + if (typeof chars === 'string') { + chars = [chars]; + } + // Handle an array of characters+ranges + var result = []; + for (var i = 0, j = chars.length; i < j; i++) { + var item = chars[i]; + // Handle range delimited by start/end chars + if (Array.isArray(item)) { + if (item.length !== 2) { + throw new Error("[BitmapFont]: Invalid character range length, expecting 2 got " + item.length + "."); + } + var startCode = item[0].charCodeAt(0); + var endCode = item[1].charCodeAt(0); + if (endCode < startCode) { + throw new Error('[BitmapFont]: Invalid character range.'); + } + for (var i_1 = startCode, j_1 = endCode; i_1 <= j_1; i_1++) { + result.push(String.fromCharCode(i_1)); + } + } + // Handle a character set string + else { + result.push.apply(result, splitTextToCharacters(item)); + } + } + if (result.length === 0) { + throw new Error('[BitmapFont]: Empty set when resolving characters.'); + } + return result; } -}); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -},{"./BasePrepare":182,"./canvas/CanvasPrepare":183,"./limiters/CountLimiter":185,"./limiters/TimeLimiter":186,"./webgl/WebGLPrepare":187}],185:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * CountLimiter limits the number of items handled by a {@link PIXI.prepare.BasePrepare} to a specified - * number of items per frame. - * - * @class - * @memberof PIXI - */ -var CountLimiter = function () { - /** - * @param {number} maxItemsPerFrame - The maximum number of items that can be prepared each frame. - */ - function CountLimiter(maxItemsPerFrame) { - _classCallCheck(this, CountLimiter); - - /** - * The maximum number of items that can be prepared each frame. - * @private - */ - this.maxItemsPerFrame = maxItemsPerFrame; - /** - * The number of items that can be prepared in the current frame. - * @type {number} - * @private - */ - this.itemsLeft = 0; + /** + * Ponyfill for IE because it doesn't support `codePointAt` + * @param str + * @private + */ + function extractCharCode(str) { + return str.codePointAt ? str.codePointAt(0) : str.charCodeAt(0); } /** - * Resets any counting properties to start fresh on a new frame. + * BitmapFont represents a typeface available for use with the BitmapText class. Use the `install` + * method for adding a font to be used. + * @memberof PIXI */ - - - CountLimiter.prototype.beginFrame = function beginFrame() { - this.itemsLeft = this.maxItemsPerFrame; - }; - + var BitmapFont = /** @class */ (function () { + /** + * @param data + * @param textures + * @param ownsTextures - Setting to `true` will destroy page textures + * when the font is uninstalled. + */ + function BitmapFont(data, textures, ownsTextures) { + var _a, _b; + var info = data.info[0]; + var common = data.common[0]; + var page = data.page[0]; + var distanceField = data.distanceField[0]; + var res = getResolutionOfUrl(page.file); + var pageTextures = {}; + this._ownsTextures = ownsTextures; + this.font = info.face; + this.size = info.size; + this.lineHeight = common.lineHeight / res; + this.chars = {}; + this.pageTextures = pageTextures; + // Convert the input Texture, Textures or object + // into a page Texture lookup by "id" + for (var i = 0; i < data.page.length; i++) { + var _c = data.page[i], id = _c.id, file = _c.file; + pageTextures[id] = textures instanceof Array + ? textures[i] : textures[file]; + // only MSDF and SDF fonts need no-premultiplied-alpha + if ((distanceField === null || distanceField === void 0 ? void 0 : distanceField.fieldType) && distanceField.fieldType !== 'none') { + pageTextures[id].baseTexture.alphaMode = exports.ALPHA_MODES.NO_PREMULTIPLIED_ALPHA; + pageTextures[id].baseTexture.mipmap = exports.MIPMAP_MODES.OFF; + } + } + // parse letters + for (var i = 0; i < data.char.length; i++) { + var _d = data.char[i], id = _d.id, page_1 = _d.page; + var _e = data.char[i], x = _e.x, y = _e.y, width = _e.width, height = _e.height, xoffset = _e.xoffset, yoffset = _e.yoffset, xadvance = _e.xadvance; + x /= res; + y /= res; + width /= res; + height /= res; + xoffset /= res; + yoffset /= res; + xadvance /= res; + var rect = new Rectangle(x + (pageTextures[page_1].frame.x / res), y + (pageTextures[page_1].frame.y / res), width, height); + this.chars[id] = { + xOffset: xoffset, + yOffset: yoffset, + xAdvance: xadvance, + kerning: {}, + texture: new Texture(pageTextures[page_1].baseTexture, rect), + page: page_1, + }; + } + // parse kernings + for (var i = 0; i < data.kerning.length; i++) { + var _f = data.kerning[i], first = _f.first, second = _f.second, amount = _f.amount; + first /= res; + second /= res; + amount /= res; + if (this.chars[second]) { + this.chars[second].kerning[first] = amount; + } + } + // Store distance field information + this.distanceFieldRange = distanceField === null || distanceField === void 0 ? void 0 : distanceField.distanceRange; + this.distanceFieldType = (_b = (_a = distanceField === null || distanceField === void 0 ? void 0 : distanceField.fieldType) === null || _a === void 0 ? void 0 : _a.toLowerCase()) !== null && _b !== void 0 ? _b : 'none'; + } + /** Remove references to created glyph textures. */ + BitmapFont.prototype.destroy = function () { + for (var id in this.chars) { + this.chars[id].texture.destroy(); + this.chars[id].texture = null; + } + for (var id in this.pageTextures) { + if (this._ownsTextures) { + this.pageTextures[id].destroy(true); + } + this.pageTextures[id] = null; + } + // Set readonly null. + this.chars = null; + this.pageTextures = null; + }; + /** + * Register a new bitmap font. + * @param data - The + * characters map that could be provided as xml or raw string. + * @param textures - List of textures for each page. + * @param ownsTextures - Set to `true` to destroy page textures + * when the font is uninstalled. By default fonts created with + * `BitmapFont.from` or from the `BitmapFontLoader` are `true`. + * @returns {PIXI.BitmapFont} Result font object with font, size, lineHeight + * and char fields. + */ + BitmapFont.install = function (data, textures, ownsTextures) { + var fontData; + if (data instanceof BitmapFontData) { + fontData = data; + } + else { + var format = autoDetectFormat(data); + if (!format) { + throw new Error('Unrecognized data format for font.'); + } + fontData = format.parse(data); + } + // Single texture, convert to list + if (textures instanceof Texture) { + textures = [textures]; + } + var font = new BitmapFont(fontData, textures, ownsTextures); + BitmapFont.available[font.font] = font; + return font; + }; + /** + * Remove bitmap font by name. + * @param name - Name of the font to uninstall. + */ + BitmapFont.uninstall = function (name) { + var font = BitmapFont.available[name]; + if (!font) { + throw new Error("No font found named '" + name + "'"); + } + font.destroy(); + delete BitmapFont.available[name]; + }; + /** + * Generates a bitmap-font for the given style and character set. This does not support + * kernings yet. With `style` properties, only the following non-layout properties are used: + * + * - {@link PIXI.TextStyle#dropShadow|dropShadow} + * - {@link PIXI.TextStyle#dropShadowDistance|dropShadowDistance} + * - {@link PIXI.TextStyle#dropShadowColor|dropShadowColor} + * - {@link PIXI.TextStyle#dropShadowBlur|dropShadowBlur} + * - {@link PIXI.TextStyle#dropShadowAngle|dropShadowAngle} + * - {@link PIXI.TextStyle#fill|fill} + * - {@link PIXI.TextStyle#fillGradientStops|fillGradientStops} + * - {@link PIXI.TextStyle#fillGradientType|fillGradientType} + * - {@link PIXI.TextStyle#fontFamily|fontFamily} + * - {@link PIXI.TextStyle#fontSize|fontSize} + * - {@link PIXI.TextStyle#fontVariant|fontVariant} + * - {@link PIXI.TextStyle#fontWeight|fontWeight} + * - {@link PIXI.TextStyle#lineJoin|lineJoin} + * - {@link PIXI.TextStyle#miterLimit|miterLimit} + * - {@link PIXI.TextStyle#stroke|stroke} + * - {@link PIXI.TextStyle#strokeThickness|strokeThickness} + * - {@link PIXI.TextStyle#textBaseline|textBaseline} + * @param name - The name of the custom font to use with BitmapText. + * @param textStyle - Style options to render with BitmapFont. + * @param options - Setup options for font or name of the font. + * @param {string|string[]|string[][]} [options.chars=PIXI.BitmapFont.ALPHANUMERIC] - characters included + * in the font set. You can also use ranges. For example, `[['a', 'z'], ['A', 'Z'], "!@#$%^&*()~{}[] "]`. + * Don't forget to include spaces ' ' in your character set! + * @param {number} [options.resolution=1] - Render resolution for glyphs. + * @param {number} [options.textureWidth=512] - Optional width of atlas, smaller values to reduce memory. + * @param {number} [options.textureHeight=512] - Optional height of atlas, smaller values to reduce memory. + * @param {number} [options.padding=4] - Padding between glyphs on texture atlas. + * @returns Font generated by style options. + * @example + * PIXI.BitmapFont.from("TitleFont", { + * fontFamily: "Arial", + * fontSize: 12, + * strokeThickness: 2, + * fill: "purple" + * }); + * + * const title = new PIXI.BitmapText("This is the title", { fontName: "TitleFont" }); + */ + BitmapFont.from = function (name, textStyle, options) { + if (!name) { + throw new Error('[BitmapFont] Property `name` is required.'); + } + var _a = Object.assign({}, BitmapFont.defaultOptions, options), chars = _a.chars, padding = _a.padding, resolution = _a.resolution, textureWidth = _a.textureWidth, textureHeight = _a.textureHeight; + var charsList = resolveCharacters(chars); + var style = textStyle instanceof TextStyle ? textStyle : new TextStyle(textStyle); + var lineWidth = textureWidth; + var fontData = new BitmapFontData(); + fontData.info[0] = { + face: style.fontFamily, + size: style.fontSize, + }; + fontData.common[0] = { + lineHeight: style.fontSize, + }; + var positionX = 0; + var positionY = 0; + var canvas; + var context; + var baseTexture; + var maxCharHeight = 0; + var textures = []; + for (var i = 0; i < charsList.length; i++) { + if (!canvas) { + canvas = settings.ADAPTER.createCanvas(); + canvas.width = textureWidth; + canvas.height = textureHeight; + context = canvas.getContext('2d'); + baseTexture = new BaseTexture(canvas, { resolution: resolution }); + textures.push(new Texture(baseTexture)); + fontData.page.push({ + id: textures.length - 1, + file: '', + }); + } + // Measure glyph dimensions + var character = charsList[i]; + var metrics = TextMetrics.measureText(character, style, false, canvas); + var width = metrics.width; + var height = Math.ceil(metrics.height); + // This is ugly - but italics are given more space so they don't overlap + var textureGlyphWidth = Math.ceil((style.fontStyle === 'italic' ? 2 : 1) * width); + // Can't fit char anymore: next canvas please! + if (positionY >= textureHeight - (height * resolution)) { + if (positionY === 0) { + // We don't want user debugging an infinite loop (or do we? :) + throw new Error("[BitmapFont] textureHeight " + textureHeight + "px is too small " + + ("(fontFamily: '" + style.fontFamily + "', fontSize: " + style.fontSize + "px, char: '" + character + "')")); + } + --i; + // Create new atlas once current has filled up + canvas = null; + context = null; + baseTexture = null; + positionY = 0; + positionX = 0; + maxCharHeight = 0; + continue; + } + maxCharHeight = Math.max(height + metrics.fontProperties.descent, maxCharHeight); + // Wrap line once full row has been rendered + if ((textureGlyphWidth * resolution) + positionX >= lineWidth) { + if (positionX === 0) { + // Avoid infinite loop (There can be some very wide char like '\uFDFD'!) + throw new Error("[BitmapFont] textureWidth " + textureWidth + "px is too small " + + ("(fontFamily: '" + style.fontFamily + "', fontSize: " + style.fontSize + "px, char: '" + character + "')")); + } + --i; + positionY += maxCharHeight * resolution; + positionY = Math.ceil(positionY); + positionX = 0; + maxCharHeight = 0; + continue; + } + drawGlyph(canvas, context, metrics, positionX, positionY, resolution, style); + // Unique (numeric) ID mapping to this glyph + var id = extractCharCode(metrics.text); + // Create a texture holding just the glyph + fontData.char.push({ + id: id, + page: textures.length - 1, + x: positionX / resolution, + y: positionY / resolution, + width: textureGlyphWidth, + height: height, + xoffset: 0, + yoffset: 0, + xadvance: Math.ceil(width + - (style.dropShadow ? style.dropShadowDistance : 0) + - (style.stroke ? style.strokeThickness : 0)), + }); + positionX += (textureGlyphWidth + (2 * padding)) * resolution; + positionX = Math.ceil(positionX); + } + if (!(options === null || options === void 0 ? void 0 : options.skipKerning)) { + // Brute-force kerning info, this can be expensive b/c it's an O(n²), + // but we're using measureText which is native and fast. + for (var i = 0, len = charsList.length; i < len; i++) { + var first = charsList[i]; + for (var j = 0; j < len; j++) { + var second = charsList[j]; + var c1 = context.measureText(first).width; + var c2 = context.measureText(second).width; + var total = context.measureText(first + second).width; + var amount = total - (c1 + c2); + if (amount) { + fontData.kerning.push({ + first: extractCharCode(first), + second: extractCharCode(second), + amount: amount, + }); + } + } + } + } + var font = new BitmapFont(fontData, textures, true); + // Make it easier to replace a font + if (BitmapFont.available[name] !== undefined) { + BitmapFont.uninstall(name); + } + BitmapFont.available[name] = font; + return font; + }; + /** + * This character set includes all the letters in the alphabet (both lower- and upper- case). + * @type {string[][]} + * @example + * BitmapFont.from("ExampleFont", style, { chars: BitmapFont.ALPHA }) + */ + BitmapFont.ALPHA = [['a', 'z'], ['A', 'Z'], ' ']; + /** + * This character set includes all decimal digits (from 0 to 9). + * @type {string[][]} + * @example + * BitmapFont.from("ExampleFont", style, { chars: BitmapFont.NUMERIC }) + */ + BitmapFont.NUMERIC = [['0', '9']]; + /** + * This character set is the union of `BitmapFont.ALPHA` and `BitmapFont.NUMERIC`. + * @type {string[][]} + */ + BitmapFont.ALPHANUMERIC = [['a', 'z'], ['A', 'Z'], ['0', '9'], ' ']; + /** + * This character set consists of all the ASCII table. + * @member {string[][]} + * @see http://www.asciitable.com/ + */ + BitmapFont.ASCII = [[' ', '~']]; + /** + * Collection of default options when using `BitmapFont.from`. + * @property {number} [resolution=1] - + * @property {number} [textureWidth=512] - + * @property {number} [textureHeight=512] - + * @property {number} [padding=4] - + * @property {string|string[]|string[][]} chars = PIXI.BitmapFont.ALPHANUMERIC + */ + BitmapFont.defaultOptions = { + resolution: 1, + textureWidth: 512, + textureHeight: 512, + padding: 4, + chars: BitmapFont.ALPHANUMERIC, + }; + /** Collection of available/installed fonts. */ + BitmapFont.available = {}; + return BitmapFont; + }()); + + var msdfFrag = "// Pixi texture info\r\nvarying vec2 vTextureCoord;\r\nuniform sampler2D uSampler;\r\n\r\n// Tint\r\nuniform vec4 uColor;\r\n\r\n// on 2D applications fwidth is screenScale / glyphAtlasScale * distanceFieldRange\r\nuniform float uFWidth;\r\n\r\nvoid main(void) {\r\n\r\n // To stack MSDF and SDF we need a non-pre-multiplied-alpha texture.\r\n vec4 texColor = texture2D(uSampler, vTextureCoord);\r\n\r\n // MSDF\r\n float median = texColor.r + texColor.g + texColor.b -\r\n min(texColor.r, min(texColor.g, texColor.b)) -\r\n max(texColor.r, max(texColor.g, texColor.b));\r\n // SDF\r\n median = min(median, texColor.a);\r\n\r\n float screenPxDistance = uFWidth * (median - 0.5);\r\n float alpha = clamp(screenPxDistance + 0.5, 0.0, 1.0);\r\n if (median < 0.01) {\r\n alpha = 0.0;\r\n } else if (median > 0.99) {\r\n alpha = 1.0;\r\n }\r\n\r\n // NPM Textures, NPM outputs\r\n gl_FragColor = vec4(uColor.rgb, uColor.a * alpha);\r\n\r\n}\r\n"; + + var msdfVert = "// Mesh material default fragment\r\nattribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\nuniform mat3 translationMatrix;\r\nuniform mat3 uTextureMatrix;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\r\n}\r\n"; + + // If we ever need more than two pools, please make a Dict or something better. + var pageMeshDataDefaultPageMeshData = []; + var pageMeshDataMSDFPageMeshData = []; + var charRenderDataPool = []; /** - * Checks to see if another item can be uploaded. This should only be called once per item. - * @return {boolean} If the item is allowed to be uploaded. + * A BitmapText object will create a line or multiple lines of text using bitmap font. + * + * The primary advantage of this class over Text is that all of your textures are pre-generated and loading, + * meaning that rendering is fast, and changing text has no performance implications. + * + * Supporting character sets other than latin, such as CJK languages, may be impractical due to the number of characters. + * + * To split a line you can use '\n', '\r' or '\r\n' in your string. + * + * PixiJS can auto-generate fonts on-the-fly using BitmapFont or use fnt files provided by: + * http://www.angelcode.com/products/bmfont/ for Windows or + * http://www.bmglyph.com/ for Mac. + * + * You can also use SDF, MSDF and MTSDF BitmapFonts for vector-like scaling appearance provided by: + * https://github.com/soimy/msdf-bmfont-xml for SDF and MSDF fnt files or + * https://github.com/Chlumsky/msdf-atlas-gen for SDF, MSDF and MTSDF json files + * + * A BitmapText can only be created when the font is loaded. + * + * ```js + * // in this case the font is in a file called 'desyrel.fnt' + * let bitmapText = new PIXI.BitmapText("text using a fancy font!", { + * fontName: "Desyrel", + * fontSize: 35, + * align: "right" + * }); + * ``` + * @memberof PIXI */ + var BitmapText = /** @class */ (function (_super) { + __extends$8(BitmapText, _super); + /** + * @param text - A string that you would like the text to display. + * @param style - The style parameters. + * @param {string} style.fontName - The installed BitmapFont name. + * @param {number} [style.fontSize] - The size of the font in pixels, e.g. 24. If undefined, + *. this will default to the BitmapFont size. + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center', 'right' or 'justify'), + * does not affect single line text. + * @param {number} [style.tint=0xFFFFFF] - The tint color. + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters. + * @param {number} [style.maxWidth=0] - The max width of the text before line wrapping. + */ + function BitmapText(text, style) { + if (style === void 0) { style = {}; } + var _this = _super.call(this) || this; + /** + * Private tracker for the current tint. + * @private + */ + _this._tint = 0xFFFFFF; + // Apply the defaults + var _a = Object.assign({}, BitmapText.styleDefaults, style), align = _a.align, tint = _a.tint, maxWidth = _a.maxWidth, letterSpacing = _a.letterSpacing, fontName = _a.fontName, fontSize = _a.fontSize; + if (!BitmapFont.available[fontName]) { + throw new Error("Missing BitmapFont \"" + fontName + "\""); + } + _this._activePagesMeshData = []; + _this._textWidth = 0; + _this._textHeight = 0; + _this._align = align; + _this._tint = tint; + _this._font = undefined; + _this._fontName = fontName; + _this._fontSize = fontSize; + _this.text = text; + _this._maxWidth = maxWidth; + _this._maxLineHeight = 0; + _this._letterSpacing = letterSpacing; + _this._anchor = new ObservablePoint(function () { _this.dirty = true; }, _this, 0, 0); + _this._roundPixels = settings.ROUND_PIXELS; + _this.dirty = true; + _this._resolution = settings.RESOLUTION; + _this._autoResolution = true; + _this._textureCache = {}; + return _this; + } + /** Renders text and updates it when needed. This should only be called if the BitmapFont is regenerated. */ + BitmapText.prototype.updateText = function () { + var _a; + var data = BitmapFont.available[this._fontName]; + var fontSize = this.fontSize; + var scale = fontSize / data.size; + var pos = new Point(); + var chars = []; + var lineWidths = []; + var lineSpaces = []; + var text = this._text.replace(/(?:\r\n|\r)/g, '\n') || ' '; + var charsInput = splitTextToCharacters(text); + var maxWidth = this._maxWidth * data.size / fontSize; + var pageMeshDataPool = data.distanceFieldType === 'none' + ? pageMeshDataDefaultPageMeshData : pageMeshDataMSDFPageMeshData; + var prevCharCode = null; + var lastLineWidth = 0; + var maxLineWidth = 0; + var line = 0; + var lastBreakPos = -1; + var lastBreakWidth = 0; + var spacesRemoved = 0; + var maxLineHeight = 0; + var spaceCount = 0; + for (var i = 0; i < charsInput.length; i++) { + var char = charsInput[i]; + var charCode = extractCharCode(char); + if ((/(?:\s)/).test(char)) { + lastBreakPos = i; + lastBreakWidth = lastLineWidth; + spaceCount++; + } + if (char === '\r' || char === '\n') { + lineWidths.push(lastLineWidth); + lineSpaces.push(-1); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + ++line; + ++spacesRemoved; + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + spaceCount = 0; + continue; + } + var charData = data.chars[charCode]; + if (!charData) { + continue; + } + if (prevCharCode && charData.kerning[prevCharCode]) { + pos.x += charData.kerning[prevCharCode]; + } + var charRenderData = charRenderDataPool.pop() || { + texture: Texture.EMPTY, + line: 0, + charCode: 0, + prevSpaces: 0, + position: new Point(), + }; + charRenderData.texture = charData.texture; + charRenderData.line = line; + charRenderData.charCode = charCode; + charRenderData.position.x = pos.x + charData.xOffset + (this._letterSpacing / 2); + charRenderData.position.y = pos.y + charData.yOffset; + charRenderData.prevSpaces = spaceCount; + chars.push(charRenderData); + lastLineWidth = charRenderData.position.x + + Math.max(charData.xAdvance - charData.xOffset, charData.texture.orig.width); + pos.x += charData.xAdvance + this._letterSpacing; + maxLineHeight = Math.max(maxLineHeight, (charData.yOffset + charData.texture.height)); + prevCharCode = charCode; + if (lastBreakPos !== -1 && maxWidth > 0 && pos.x > maxWidth) { + ++spacesRemoved; + removeItems(chars, 1 + lastBreakPos - spacesRemoved, 1 + i - lastBreakPos); + i = lastBreakPos; + lastBreakPos = -1; + lineWidths.push(lastBreakWidth); + lineSpaces.push(chars.length > 0 ? chars[chars.length - 1].prevSpaces : 0); + maxLineWidth = Math.max(maxLineWidth, lastBreakWidth); + line++; + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + spaceCount = 0; + } + } + var lastChar = charsInput[charsInput.length - 1]; + if (lastChar !== '\r' && lastChar !== '\n') { + if ((/(?:\s)/).test(lastChar)) { + lastLineWidth = lastBreakWidth; + } + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + lineSpaces.push(-1); + } + var lineAlignOffsets = []; + for (var i = 0; i <= line; i++) { + var alignOffset = 0; + if (this._align === 'right') { + alignOffset = maxLineWidth - lineWidths[i]; + } + else if (this._align === 'center') { + alignOffset = (maxLineWidth - lineWidths[i]) / 2; + } + else if (this._align === 'justify') { + alignOffset = lineSpaces[i] < 0 ? 0 : (maxLineWidth - lineWidths[i]) / lineSpaces[i]; + } + lineAlignOffsets.push(alignOffset); + } + var lenChars = chars.length; + var pagesMeshData = {}; + var newPagesMeshData = []; + var activePagesMeshData = this._activePagesMeshData; + pageMeshDataPool.push.apply(pageMeshDataPool, activePagesMeshData); + for (var i = 0; i < lenChars; i++) { + var texture = chars[i].texture; + var baseTextureUid = texture.baseTexture.uid; + if (!pagesMeshData[baseTextureUid]) { + var pageMeshData = pageMeshDataPool.pop(); + if (!pageMeshData) { + var geometry = new MeshGeometry(); + var material = void 0; + var meshBlendMode = void 0; + if (data.distanceFieldType === 'none') { + material = new MeshMaterial(Texture.EMPTY); + meshBlendMode = exports.BLEND_MODES.NORMAL; + } + else { + material = new MeshMaterial(Texture.EMPTY, { program: Program.from(msdfVert, msdfFrag), uniforms: { uFWidth: 0 } }); + meshBlendMode = exports.BLEND_MODES.NORMAL_NPM; + } + var mesh = new Mesh(geometry, material); + mesh.blendMode = meshBlendMode; + pageMeshData = { + index: 0, + indexCount: 0, + vertexCount: 0, + uvsCount: 0, + total: 0, + mesh: mesh, + vertices: null, + uvs: null, + indices: null, + }; + } + // reset data.. + pageMeshData.index = 0; + pageMeshData.indexCount = 0; + pageMeshData.vertexCount = 0; + pageMeshData.uvsCount = 0; + pageMeshData.total = 0; + // TODO need to get page texture here somehow.. + var _textureCache = this._textureCache; + _textureCache[baseTextureUid] = _textureCache[baseTextureUid] || new Texture(texture.baseTexture); + pageMeshData.mesh.texture = _textureCache[baseTextureUid]; + pageMeshData.mesh.tint = this._tint; + newPagesMeshData.push(pageMeshData); + pagesMeshData[baseTextureUid] = pageMeshData; + } + pagesMeshData[baseTextureUid].total++; + } + // lets find any previously active pageMeshDatas that are no longer required for + // the updated text (if any), removed and return them to the pool. + for (var i = 0; i < activePagesMeshData.length; i++) { + if (newPagesMeshData.indexOf(activePagesMeshData[i]) === -1) { + this.removeChild(activePagesMeshData[i].mesh); + } + } + // next lets add any new meshes, that have not yet been added to this BitmapText + // we only add if its not already a child of this BitmapObject + for (var i = 0; i < newPagesMeshData.length; i++) { + if (newPagesMeshData[i].mesh.parent !== this) { + this.addChild(newPagesMeshData[i].mesh); + } + } + // active page mesh datas are set to be the new pages added. + this._activePagesMeshData = newPagesMeshData; + for (var i in pagesMeshData) { + var pageMeshData = pagesMeshData[i]; + var total = pageMeshData.total; + // lets only allocate new buffers if we can fit the new text in the current ones.. + // unless that is, we will be batching. Currently batching dose not respect the size property of mesh + if (!(((_a = pageMeshData.indices) === null || _a === void 0 ? void 0 : _a.length) > 6 * total) || pageMeshData.vertices.length < Mesh.BATCHABLE_SIZE * 2) { + pageMeshData.vertices = new Float32Array(4 * 2 * total); + pageMeshData.uvs = new Float32Array(4 * 2 * total); + pageMeshData.indices = new Uint16Array(6 * total); + } + else { + var total_1 = pageMeshData.total; + var vertices = pageMeshData.vertices; + // Clear the garbage at the end of the vertices buffer. This will prevent the bounds miscalculation. + for (var i_1 = total_1 * 4 * 2; i_1 < vertices.length; i_1++) { + vertices[i_1] = 0; + } + } + // as a buffer maybe bigger than the current word, we set the size of the meshMaterial + // to match the number of letters needed + pageMeshData.mesh.size = 6 * total; + } + for (var i = 0; i < lenChars; i++) { + var char = chars[i]; + var offset = char.position.x + (lineAlignOffsets[char.line] * (this._align === 'justify' ? char.prevSpaces : 1)); + if (this._roundPixels) { + offset = Math.round(offset); + } + var xPos = offset * scale; + var yPos = char.position.y * scale; + var texture = char.texture; + var pageMesh = pagesMeshData[texture.baseTexture.uid]; + var textureFrame = texture.frame; + var textureUvs = texture._uvs; + var index = pageMesh.index++; + pageMesh.indices[(index * 6) + 0] = 0 + (index * 4); + pageMesh.indices[(index * 6) + 1] = 1 + (index * 4); + pageMesh.indices[(index * 6) + 2] = 2 + (index * 4); + pageMesh.indices[(index * 6) + 3] = 0 + (index * 4); + pageMesh.indices[(index * 6) + 4] = 2 + (index * 4); + pageMesh.indices[(index * 6) + 5] = 3 + (index * 4); + pageMesh.vertices[(index * 8) + 0] = xPos; + pageMesh.vertices[(index * 8) + 1] = yPos; + pageMesh.vertices[(index * 8) + 2] = xPos + (textureFrame.width * scale); + pageMesh.vertices[(index * 8) + 3] = yPos; + pageMesh.vertices[(index * 8) + 4] = xPos + (textureFrame.width * scale); + pageMesh.vertices[(index * 8) + 5] = yPos + (textureFrame.height * scale); + pageMesh.vertices[(index * 8) + 6] = xPos; + pageMesh.vertices[(index * 8) + 7] = yPos + (textureFrame.height * scale); + pageMesh.uvs[(index * 8) + 0] = textureUvs.x0; + pageMesh.uvs[(index * 8) + 1] = textureUvs.y0; + pageMesh.uvs[(index * 8) + 2] = textureUvs.x1; + pageMesh.uvs[(index * 8) + 3] = textureUvs.y1; + pageMesh.uvs[(index * 8) + 4] = textureUvs.x2; + pageMesh.uvs[(index * 8) + 5] = textureUvs.y2; + pageMesh.uvs[(index * 8) + 6] = textureUvs.x3; + pageMesh.uvs[(index * 8) + 7] = textureUvs.y3; + } + this._textWidth = maxLineWidth * scale; + this._textHeight = (pos.y + data.lineHeight) * scale; + for (var i in pagesMeshData) { + var pageMeshData = pagesMeshData[i]; + // apply anchor + if (this.anchor.x !== 0 || this.anchor.y !== 0) { + var vertexCount = 0; + var anchorOffsetX = this._textWidth * this.anchor.x; + var anchorOffsetY = this._textHeight * this.anchor.y; + for (var i_2 = 0; i_2 < pageMeshData.total; i_2++) { + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + } + } + this._maxLineHeight = maxLineHeight * scale; + var vertexBuffer = pageMeshData.mesh.geometry.getBuffer('aVertexPosition'); + var textureBuffer = pageMeshData.mesh.geometry.getBuffer('aTextureCoord'); + var indexBuffer = pageMeshData.mesh.geometry.getIndex(); + vertexBuffer.data = pageMeshData.vertices; + textureBuffer.data = pageMeshData.uvs; + indexBuffer.data = pageMeshData.indices; + vertexBuffer.update(); + textureBuffer.update(); + indexBuffer.update(); + } + for (var i = 0; i < chars.length; i++) { + charRenderDataPool.push(chars[i]); + } + this._font = data; + this.dirty = false; + }; + BitmapText.prototype.updateTransform = function () { + this.validate(); + this.containerUpdateTransform(); + }; + BitmapText.prototype._render = function (renderer) { + if (this._autoResolution && this._resolution !== renderer.resolution) { + this._resolution = renderer.resolution; + this.dirty = true; + } + // Update the uniform + var _a = BitmapFont.available[this._fontName], distanceFieldRange = _a.distanceFieldRange, distanceFieldType = _a.distanceFieldType, size = _a.size; + if (distanceFieldType !== 'none') { + // Inject the shader code with the correct value + var _b = this.worldTransform, a = _b.a, b = _b.b, c = _b.c, d = _b.d; + var dx = Math.sqrt((a * a) + (b * b)); + var dy = Math.sqrt((c * c) + (d * d)); + var worldScale = (Math.abs(dx) + Math.abs(dy)) / 2; + var fontScale = this.fontSize / size; + for (var _i = 0, _c = this._activePagesMeshData; _i < _c.length; _i++) { + var mesh = _c[_i]; + mesh.mesh.shader.uniforms.uFWidth = worldScale * distanceFieldRange * fontScale * this._resolution; + } + } + _super.prototype._render.call(this, renderer); + }; + /** + * Validates text before calling parent's getLocalBounds + * @returns - The rectangular bounding area + */ + BitmapText.prototype.getLocalBounds = function () { + this.validate(); + return _super.prototype.getLocalBounds.call(this); + }; + /** + * Updates text when needed + * @private + */ + BitmapText.prototype.validate = function () { + var font = BitmapFont.available[this._fontName]; + if (!font) { + throw new Error("Missing BitmapFont \"" + this._fontName + "\""); + } + if (this._font !== font) { + this.dirty = true; + } + if (this.dirty) { + this.updateText(); + } + }; + Object.defineProperty(BitmapText.prototype, "tint", { + /** + * The tint of the BitmapText object. + * @default 0xffffff + */ + get: function () { + return this._tint; + }, + set: function (value) { + if (this._tint === value) + { return; } + this._tint = value; + for (var i = 0; i < this._activePagesMeshData.length; i++) { + this._activePagesMeshData[i].mesh.tint = value; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "align", { + /** + * The alignment of the BitmapText object. + * @member {string} + * @default 'left' + */ + get: function () { + return this._align; + }, + set: function (value) { + if (this._align !== value) { + this._align = value; + this.dirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "fontName", { + /** The name of the BitmapFont. */ + get: function () { + return this._fontName; + }, + set: function (value) { + if (!BitmapFont.available[value]) { + throw new Error("Missing BitmapFont \"" + value + "\""); + } + if (this._fontName !== value) { + this._fontName = value; + this.dirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "fontSize", { + /** The size of the font to display. */ + get: function () { + var _a; + return (_a = this._fontSize) !== null && _a !== void 0 ? _a : BitmapFont.available[this._fontName].size; + }, + set: function (value) { + if (this._fontSize !== value) { + this._fontSize = value; + this.dirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "anchor", { + /** + * The anchor sets the origin point of the text. + * + * The default is `(0,0)`, this means the text's origin is the top left. + * + * Setting the anchor to `(0.5,0.5)` means the text's origin is centered. + * + * Setting the anchor to `(1,1)` would mean the text's origin point will be the bottom right corner. + */ + get: function () { + return this._anchor; + }, + set: function (value) { + if (typeof value === 'number') { + this._anchor.set(value); + } + else { + this._anchor.copyFrom(value); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "text", { + /** The text of the BitmapText object. */ + get: function () { + return this._text; + }, + set: function (text) { + text = String(text === null || text === undefined ? '' : text); + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "maxWidth", { + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting the value to 0. + */ + get: function () { + return this._maxWidth; + }, + set: function (value) { + if (this._maxWidth === value) { + return; + } + this._maxWidth = value; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "maxLineHeight", { + /** + * The max line height. This is useful when trying to use the total height of the Text, + * i.e. when trying to vertically align. + * @readonly + */ + get: function () { + this.validate(); + return this._maxLineHeight; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "textWidth", { + /** + * The width of the overall text, different from fontSize, + * which is defined in the style object. + * @readonly + */ + get: function () { + this.validate(); + return this._textWidth; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "letterSpacing", { + /** Additional space between characters. */ + get: function () { + return this._letterSpacing; + }, + set: function (value) { + if (this._letterSpacing !== value) { + this._letterSpacing = value; + this.dirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "roundPixels", { + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Advantages can include sharper image quality (like text) and faster rendering on canvas. + * The main disadvantage is movement of objects may appear less smooth. + * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} + * @default PIXI.settings.ROUND_PIXELS + */ + get: function () { + return this._roundPixels; + }, + set: function (value) { + if (value !== this._roundPixels) { + this._roundPixels = value; + this.dirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "textHeight", { + /** + * The height of the overall text, different from fontSize, + * which is defined in the style object. + * @readonly + */ + get: function () { + this.validate(); + return this._textHeight; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "resolution", { + /** + * The resolution / device pixel ratio of the canvas. + * + * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually. + * @default 1 + */ + get: function () { + return this._resolution; + }, + set: function (value) { + this._autoResolution = false; + if (this._resolution === value) { + return; + } + this._resolution = value; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + BitmapText.prototype.destroy = function (options) { + var _textureCache = this._textureCache; + var data = BitmapFont.available[this._fontName]; + var pageMeshDataPool = data.distanceFieldType === 'none' + ? pageMeshDataDefaultPageMeshData : pageMeshDataMSDFPageMeshData; + pageMeshDataPool.push.apply(pageMeshDataPool, this._activePagesMeshData); + for (var _i = 0, _a = this._activePagesMeshData; _i < _a.length; _i++) { + var pageMeshData = _a[_i]; + this.removeChild(pageMeshData.mesh); + } + this._activePagesMeshData = []; + // Release references to any cached textures in page pool + pageMeshDataPool + .filter(function (page) { return _textureCache[page.mesh.texture.baseTexture.uid]; }) + .forEach(function (page) { + page.mesh.texture = Texture.EMPTY; + }); + for (var id in _textureCache) { + var texture = _textureCache[id]; + texture.destroy(); + delete _textureCache[id]; + } + this._font = null; + this._textureCache = null; + _super.prototype.destroy.call(this, options); + }; + BitmapText.styleDefaults = { + align: 'left', + tint: 0xFFFFFF, + maxWidth: 0, + letterSpacing: 0, + }; + return BitmapText; + }(Container)); + /** + * {@link PIXI.Loader Loader} middleware for loading + * bitmap-based fonts suitable for using with {@link PIXI.BitmapText}. + * @memberof PIXI + */ + var BitmapFontLoader = /** @class */ (function () { + function BitmapFontLoader() { + } + /** + * Called when the plugin is installed. + * @see PIXI.extensions.add + */ + BitmapFontLoader.add = function () { + exports.LoaderResource.setExtensionXhrType('fnt', exports.LoaderResource.XHR_RESPONSE_TYPE.TEXT); + }; + /** + * Called after a resource is loaded. + * @see PIXI.Loader.loaderMiddleware + * @param this + * @param {PIXI.LoaderResource} resource + * @param {Function} next + */ + BitmapFontLoader.use = function (resource, next) { + var format = autoDetectFormat(resource.data); + // Resource was not recognised as any of the expected font data format + if (!format) { + next(); + return; + } + var baseUrl = BitmapFontLoader.getBaseUrl(this, resource); + var data = format.parse(resource.data); + var textures = {}; + // Handle completed, when the number of textures + // load is the same number as references in the fnt file + var completed = function (page) { + textures[page.metadata.pageFile] = page.texture; + if (Object.keys(textures).length === data.page.length) { + resource.bitmapFont = BitmapFont.install(data, textures, true); + next(); + } + }; + for (var i = 0; i < data.page.length; ++i) { + var pageFile = data.page[i].file; + var url = baseUrl + pageFile; + var exists = false; + // incase the image is loaded outside + // using the same loader, resource will be available + for (var name in this.resources) { + var bitmapResource = this.resources[name]; + if (bitmapResource.url === url) { + bitmapResource.metadata.pageFile = pageFile; + if (bitmapResource.texture) { + completed(bitmapResource); + } + else { + bitmapResource.onAfterMiddleware.add(completed); + } + exists = true; + break; + } + } + // texture is not loaded, we'll attempt to add + // it to the load and add the texture to the list + if (!exists) { + // Standard loading options for images + var options = { + crossOrigin: resource.crossOrigin, + loadType: exports.LoaderResource.LOAD_TYPE.IMAGE, + metadata: Object.assign({ pageFile: pageFile }, resource.metadata.imageMetadata), + parentResource: resource, + }; + this.add(url, options, completed); + } + } + }; + /** + * Get folder path from a resource. + * @param loader + * @param resource + */ + BitmapFontLoader.getBaseUrl = function (loader, resource) { + var resUrl = !resource.isDataUrl ? BitmapFontLoader.dirname(resource.url) : ''; + if (resource.isDataUrl) { + if (resUrl === '.') { + resUrl = ''; + } + if (loader.baseUrl && resUrl) { + // if baseurl has a trailing slash then add one to resUrl so the replace works below + if (loader.baseUrl.charAt(loader.baseUrl.length - 1) === '/') { + resUrl += '/'; + } + } + } + // remove baseUrl from resUrl + resUrl = resUrl.replace(loader.baseUrl, ''); + // if there is an resUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. + if (resUrl && resUrl.charAt(resUrl.length - 1) !== '/') { + resUrl += '/'; + } + return resUrl; + }; + /** + * Replacement for NodeJS's path.dirname + * @param {string} url - Path to get directory for + */ + BitmapFontLoader.dirname = function (url) { + var dir = url + .replace(/\\/g, '/') // convert windows notation to UNIX notation, URL-safe because it's a forbidden character + .replace(/\/$/, '') // replace trailing slash + .replace(/\/[^\/]*$/, ''); // remove everything after the last + // File request is relative, use current directory + if (dir === url) { + return '.'; + } + // Started with a slash + else if (dir === '') { + return '/'; + } + return dir; + }; + /** @ignore */ + BitmapFontLoader.extension = exports.ExtensionType.Loader; + return BitmapFontLoader; + }()); + + /*! + * @pixi/filter-alpha - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/filter-alpha is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ - CountLimiter.prototype.allowedToUpload = function allowedToUpload() { - return this.itemsLeft-- > 0; + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$7 = function(d, b) { + extendStatics$7 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$7(d, b); }; - return CountLimiter; -}(); - -exports.default = CountLimiter; + function __extends$7(d, b) { + extendStatics$7(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } -},{}],186:[function(require,module,exports){ -"use strict"; + var fragment$4 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n"; -exports.__esModule = true; + /** + * Simplest filter - applies alpha. + * + * Use this instead of Container's alpha property to avoid visual layering of individual elements. + * AlphaFilter applies alpha evenly across the entire display object and any opaque elements it contains. + * If elements are not opaque, they will blend with each other anyway. + * + * Very handy if you want to use common features of all filters: + * + * 1. Assign a blendMode to this filter, blend all elements inside display object with background. + * + * 2. To use clipping in display coordinates, assign a filterArea to the same container that has this filter. + * @memberof PIXI.filters + */ + var AlphaFilter = /** @class */ (function (_super) { + __extends$7(AlphaFilter, _super); + /** + * @param alpha - Amount of alpha from 0 to 1, where 0 is transparent + */ + function AlphaFilter(alpha) { + if (alpha === void 0) { alpha = 1.0; } + var _this = _super.call(this, defaultVertex$1, fragment$4, { uAlpha: 1 }) || this; + _this.alpha = alpha; + return _this; + } + Object.defineProperty(AlphaFilter.prototype, "alpha", { + /** + * Coefficient for alpha multiplication + * @default 1 + */ + get: function () { + return this.uniforms.uAlpha; + }, + set: function (value) { + this.uniforms.uAlpha = value; + }, + enumerable: false, + configurable: true + }); + return AlphaFilter; + }(Filter)); + + /*! + * @pixi/filter-blur - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/filter-blur is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$6 = function(d, b) { + extendStatics$6 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$6(d, b); + }; -/** - * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified - * number of milliseconds per frame. - * - * @class - * @memberof PIXI - */ -var TimeLimiter = function () { - /** - * @param {number} maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. - */ - function TimeLimiter(maxMilliseconds) { - _classCallCheck(this, TimeLimiter); - - /** - * The maximum milliseconds that can be spent preparing items each frame. - * @private - */ - this.maxMilliseconds = maxMilliseconds; - /** - * The start time of the current frame. - * @type {number} - * @private - */ - this.frameStart = 0; + function __extends$6(d, b) { + extendStatics$6(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } - /** - * Resets any counting properties to start fresh on a new frame. - */ - + var vertTemplate = "\n attribute vec2 aVertexPosition;\n\n uniform mat3 projectionMatrix;\n\n uniform float strength;\n\n varying vec2 vBlurTexCoords[%size%];\n\n uniform vec4 inputSize;\n uniform vec4 outputFrame;\n\n vec4 filterVertexPosition( void )\n {\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n }\n\n vec2 filterTextureCoord( void )\n {\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n }\n\n void main(void)\n {\n gl_Position = filterVertexPosition();\n\n vec2 textureCoord = filterTextureCoord();\n %blur%\n }"; + function generateBlurVertSource(kernelSize, x) { + var halfLength = Math.ceil(kernelSize / 2); + var vertSource = vertTemplate; + var blurLoop = ''; + var template; + if (x) { + template = 'vBlurTexCoords[%index%] = textureCoord + vec2(%sampleIndex% * strength, 0.0);'; + } + else { + template = 'vBlurTexCoords[%index%] = textureCoord + vec2(0.0, %sampleIndex% * strength);'; + } + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i.toString()); + blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + ".0"); + blurLoop += blur; + blurLoop += '\n'; + } + vertSource = vertSource.replace('%blur%', blurLoop); + vertSource = vertSource.replace('%size%', kernelSize.toString()); + return vertSource; + } - TimeLimiter.prototype.beginFrame = function beginFrame() { - this.frameStart = Date.now(); + var GAUSSIAN_VALUES = { + 5: [0.153388, 0.221461, 0.250301], + 7: [0.071303, 0.131514, 0.189879, 0.214607], + 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448], }; + var fragTemplate = [ + 'varying vec2 vBlurTexCoords[%size%];', + 'uniform sampler2D uSampler;', + 'void main(void)', + '{', + ' gl_FragColor = vec4(0.0);', + ' %blur%', + '}' ].join('\n'); + function generateBlurFragSource(kernelSize) { + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; + var fragSource = fragTemplate; + var blurLoop = ''; + var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; + var value; + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i.toString()); + value = i; + if (i >= halfLength) { + value = kernelSize - i - 1; + } + blur = blur.replace('%value%', kernel[value].toString()); + blurLoop += blur; + blurLoop += '\n'; + } + fragSource = fragSource.replace('%blur%', blurLoop); + fragSource = fragSource.replace('%size%', kernelSize.toString()); + return fragSource; + } /** - * Checks to see if another item can be uploaded. This should only be called once per item. - * @return {boolean} If the item is allowed to be uploaded. + * The BlurFilterPass applies a horizontal or vertical Gaussian blur to an object. + * @memberof PIXI.filters */ + var BlurFilterPass = /** @class */ (function (_super) { + __extends$6(BlurFilterPass, _super); + /** + * @param horizontal - Do pass along the x-axis (`true`) or y-axis (`false`). + * @param strength - The strength of the blur filter. + * @param quality - The quality of the blur filter. + * @param resolution - The resolution of the blur filter. + * @param kernelSize - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurFilterPass(horizontal, strength, quality, resolution, kernelSize) { + if (strength === void 0) { strength = 8; } + if (quality === void 0) { quality = 4; } + if (resolution === void 0) { resolution = settings.FILTER_RESOLUTION; } + if (kernelSize === void 0) { kernelSize = 5; } + var _this = this; + var vertSrc = generateBlurVertSource(kernelSize, horizontal); + var fragSrc = generateBlurFragSource(kernelSize); + _this = _super.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc) || this; + _this.horizontal = horizontal; + _this.resolution = resolution; + _this._quality = 0; + _this.quality = quality; + _this.blur = strength; + return _this; + } + /** + * Applies the filter. + * @param filterManager - The manager. + * @param input - The input target. + * @param output - The output target. + * @param clearMode - How to clear + */ + BlurFilterPass.prototype.apply = function (filterManager, input, output, clearMode) { + if (output) { + if (this.horizontal) { + this.uniforms.strength = (1 / output.width) * (output.width / input.width); + } + else { + this.uniforms.strength = (1 / output.height) * (output.height / input.height); + } + } + else { + if (this.horizontal) // eslint-disable-line + { + this.uniforms.strength = (1 / filterManager.renderer.width) * (filterManager.renderer.width / input.width); + } + else { + this.uniforms.strength = (1 / filterManager.renderer.height) * (filterManager.renderer.height / input.height); // eslint-disable-line + } + } + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clearMode); + } + else { + var renderTarget = filterManager.getFilterTexture(); + var renderer = filterManager.renderer; + var flip = input; + var flop = renderTarget; + this.state.blend = false; + filterManager.applyFilter(this, flip, flop, exports.CLEAR_MODES.CLEAR); + for (var i = 1; i < this.passes - 1; i++) { + filterManager.bindAndClear(flip, exports.CLEAR_MODES.BLIT); + this.uniforms.uSampler = flop; + var temp = flop; + flop = flip; + flip = temp; + renderer.shader.bind(this); + renderer.geometry.draw(5); + } + this.state.blend = true; + filterManager.applyFilter(this, flop, output, clearMode); + filterManager.returnFilterTexture(renderTarget); + } + }; + Object.defineProperty(BlurFilterPass.prototype, "blur", { + /** + * Sets the strength of both the blur. + * @default 16 + */ + get: function () { + return this.strength; + }, + set: function (value) { + this.padding = 1 + (Math.abs(value) * 2); + this.strength = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilterPass.prototype, "quality", { + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quality bluring but the lower the performance. + * @default 4 + */ + get: function () { + return this._quality; + }, + set: function (value) { + this._quality = value; + this.passes = value; + }, + enumerable: false, + configurable: true + }); + return BlurFilterPass; + }(Filter)); + /** + * The BlurFilter applies a Gaussian blur to an object. + * + * The strength of the blur can be set for the x-axis and y-axis separately. + * @memberof PIXI.filters + */ + var BlurFilter = /** @class */ (function (_super) { + __extends$6(BlurFilter, _super); + /** + * @param strength - The strength of the blur filter. + * @param quality - The quality of the blur filter. + * @param [resolution=PIXI.settings.FILTER_RESOLUTION] - The resolution of the blur filter. + * @param kernelSize - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurFilter(strength, quality, resolution, kernelSize) { + if (strength === void 0) { strength = 8; } + if (quality === void 0) { quality = 4; } + if (resolution === void 0) { resolution = settings.FILTER_RESOLUTION; } + if (kernelSize === void 0) { kernelSize = 5; } + var _this = _super.call(this) || this; + _this.blurXFilter = new BlurFilterPass(true, strength, quality, resolution, kernelSize); + _this.blurYFilter = new BlurFilterPass(false, strength, quality, resolution, kernelSize); + _this.resolution = resolution; + _this.quality = quality; + _this.blur = strength; + _this.repeatEdgePixels = false; + return _this; + } + /** + * Applies the filter. + * @param filterManager - The manager. + * @param input - The input target. + * @param output - The output target. + * @param clearMode - How to clear + */ + BlurFilter.prototype.apply = function (filterManager, input, output, clearMode) { + var xStrength = Math.abs(this.blurXFilter.strength); + var yStrength = Math.abs(this.blurYFilter.strength); + if (xStrength && yStrength) { + var renderTarget = filterManager.getFilterTexture(); + this.blurXFilter.apply(filterManager, input, renderTarget, exports.CLEAR_MODES.CLEAR); + this.blurYFilter.apply(filterManager, renderTarget, output, clearMode); + filterManager.returnFilterTexture(renderTarget); + } + else if (yStrength) { + this.blurYFilter.apply(filterManager, input, output, clearMode); + } + else { + this.blurXFilter.apply(filterManager, input, output, clearMode); + } + }; + BlurFilter.prototype.updatePadding = function () { + if (this._repeatEdgePixels) { + this.padding = 0; + } + else { + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + }; + Object.defineProperty(BlurFilter.prototype, "blur", { + /** + * Sets the strength of both the blurX and blurY properties simultaneously + * @default 2 + */ + get: function () { + return this.blurXFilter.blur; + }, + set: function (value) { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.updatePadding(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "quality", { + /** + * Sets the number of passes for blur. More passes means higher quality bluring. + * @default 1 + */ + get: function () { + return this.blurXFilter.quality; + }, + set: function (value) { + this.blurXFilter.quality = this.blurYFilter.quality = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "blurX", { + /** + * Sets the strength of the blurX property + * @default 2 + */ + get: function () { + return this.blurXFilter.blur; + }, + set: function (value) { + this.blurXFilter.blur = value; + this.updatePadding(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "blurY", { + /** + * Sets the strength of the blurY property + * @default 2 + */ + get: function () { + return this.blurYFilter.blur; + }, + set: function (value) { + this.blurYFilter.blur = value; + this.updatePadding(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "blendMode", { + /** + * Sets the blendmode of the filter + * @default PIXI.BLEND_MODES.NORMAL + */ + get: function () { + return this.blurYFilter.blendMode; + }, + set: function (value) { + this.blurYFilter.blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "repeatEdgePixels", { + /** + * If set to true the edge of the target will be clamped + * @default false + */ + get: function () { + return this._repeatEdgePixels; + }, + set: function (value) { + this._repeatEdgePixels = value; + this.updatePadding(); + }, + enumerable: false, + configurable: true + }); + return BlurFilter; + }(Filter)); + + /*! + * @pixi/filter-color-matrix - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/filter-color-matrix is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ - TimeLimiter.prototype.allowedToUpload = function allowedToUpload() { - return Date.now() - this.frameStart < this.maxMilliseconds; + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$5 = function(d, b) { + extendStatics$5 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$5(d, b); }; - return TimeLimiter; -}(); - -exports.default = TimeLimiter; - -},{}],187:[function(require,module,exports){ -'use strict'; - -exports.__esModule = true; - -var _core = require('../../core'); - -var core = _interopRequireWildcard(_core); - -var _BasePrepare2 = require('../BasePrepare'); - -var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -/** - * The prepare manager provides functionality to upload content to the GPU. - * - * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare - * - * @class - * @extends PIXI.prepare.BasePrepare - * @memberof PIXI.prepare - */ -var WebGLPrepare = function (_BasePrepare) { - _inherits(WebGLPrepare, _BasePrepare); - - /** - * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer - */ - function WebGLPrepare(renderer) { - _classCallCheck(this, WebGLPrepare); - - var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); - - _this.uploadHookHelper = _this.renderer; - - // Add textures and graphics to upload - _this.registerFindHook(findGraphics); - _this.registerUploadHook(uploadBaseTextures); - _this.registerUploadHook(uploadGraphics); - return _this; - } - - return WebGLPrepare; -}(_BasePrepare3.default); -/** - * Built-in hook to upload PIXI.Texture objects to the GPU. - * - * @private - * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer - * @param {PIXI.DisplayObject} item - Item to check - * @return {boolean} If item was uploaded. - */ - - -exports.default = WebGLPrepare; -function uploadBaseTextures(renderer, item) { - if (item instanceof core.BaseTexture) { - // if the texture already has a GL texture, then the texture has been prepared or rendered - // before now. If the texture changed, then the changer should be calling texture.update() which - // reuploads the texture without need for preparing it again - if (!item._glTextures[renderer.CONTEXT_UID]) { - renderer.textureManager.updateTexture(item); - } - - return true; - } - - return false; -} - -/** - * Built-in hook to upload PIXI.Graphics to the GPU. - * - * @private - * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer - * @param {PIXI.DisplayObject} item - Item to check - * @return {boolean} If item was uploaded. - */ -function uploadGraphics(renderer, item) { - if (item instanceof core.Graphics) { - // if the item is not dirty and already has webgl data, then it got prepared or rendered - // before now and we shouldn't waste time updating it again - if (item.dirty || item.clearDirty || !item._webGL[renderer.plugins.graphics.CONTEXT_UID]) { - renderer.plugins.graphics.updateGraphics(item); - } - - return true; - } - - return false; -} - -/** - * Built-in hook to find graphics. - * - * @private - * @param {PIXI.DisplayObject} item - Display object to check - * @param {Array<*>} queue - Collection of items to upload - * @return {boolean} if a PIXI.Graphics object was found. - */ -function findGraphics(item, queue) { - if (item instanceof core.Graphics) { - queue.push(item); - - return true; - } - - return false; -} - -core.WebGLRenderer.registerPlugin('prepare', WebGLPrepare); - -},{"../../core":65,"../BasePrepare":182}],188:[function(require,module,exports){ -(function (global){ -'use strict'; - -exports.__esModule = true; -exports.loader = exports.prepare = exports.particles = exports.mesh = exports.loaders = exports.interaction = exports.filters = exports.extras = exports.extract = exports.accessibility = undefined; - -var _polyfill = require('./polyfill'); - -Object.keys(_polyfill).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _polyfill[key]; - } - }); -}); - -var _core = require('./core'); + function __extends$5(d, b) { + extendStatics$5(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } -Object.keys(_core).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _core[key]; - } - }); -}); + var fragment$3 = "varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n"; -var _deprecation = require('./deprecation'); + /** + * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA + * color and alpha values of every pixel on your displayObject to produce a result + * with a new set of RGBA color and alpha values. It's pretty powerful! + * + * ```js + * let colorMatrix = new PIXI.filters.ColorMatrixFilter(); + * container.filters = [colorMatrix]; + * colorMatrix.contrast(2); + * ``` + * @author Clément Chenebault + * @memberof PIXI.filters + */ + var ColorMatrixFilter = /** @class */ (function (_super) { + __extends$5(ColorMatrixFilter, _super); + function ColorMatrixFilter() { + var _this = this; + var uniforms = { + m: new Float32Array([1, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0]), + uAlpha: 1, + }; + _this = _super.call(this, defaultFilterVertex, fragment$3, uniforms) || this; + _this.alpha = 1; + return _this; + } + /** + * Transforms current matrix and set the new one + * @param {number[]} matrix - 5x4 matrix + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype._loadMatrix = function (matrix, multiply) { + if (multiply === void 0) { multiply = false; } + var newMatrix = matrix; + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } + // set the new matrix + this.uniforms.m = newMatrix; + }; + /** + * Multiplies two mat5's + * @private + * @param out - 5x4 matrix the receiving matrix + * @param a - 5x4 matrix the first operand + * @param b - 5x4 matrix the second operand + * @returns {number[]} 5x4 matrix + */ + ColorMatrixFilter.prototype._multiply = function (out, a, b) { + // Red Channel + out[0] = (a[0] * b[0]) + (a[1] * b[5]) + (a[2] * b[10]) + (a[3] * b[15]); + out[1] = (a[0] * b[1]) + (a[1] * b[6]) + (a[2] * b[11]) + (a[3] * b[16]); + out[2] = (a[0] * b[2]) + (a[1] * b[7]) + (a[2] * b[12]) + (a[3] * b[17]); + out[3] = (a[0] * b[3]) + (a[1] * b[8]) + (a[2] * b[13]) + (a[3] * b[18]); + out[4] = (a[0] * b[4]) + (a[1] * b[9]) + (a[2] * b[14]) + (a[3] * b[19]) + a[4]; + // Green Channel + out[5] = (a[5] * b[0]) + (a[6] * b[5]) + (a[7] * b[10]) + (a[8] * b[15]); + out[6] = (a[5] * b[1]) + (a[6] * b[6]) + (a[7] * b[11]) + (a[8] * b[16]); + out[7] = (a[5] * b[2]) + (a[6] * b[7]) + (a[7] * b[12]) + (a[8] * b[17]); + out[8] = (a[5] * b[3]) + (a[6] * b[8]) + (a[7] * b[13]) + (a[8] * b[18]); + out[9] = (a[5] * b[4]) + (a[6] * b[9]) + (a[7] * b[14]) + (a[8] * b[19]) + a[9]; + // Blue Channel + out[10] = (a[10] * b[0]) + (a[11] * b[5]) + (a[12] * b[10]) + (a[13] * b[15]); + out[11] = (a[10] * b[1]) + (a[11] * b[6]) + (a[12] * b[11]) + (a[13] * b[16]); + out[12] = (a[10] * b[2]) + (a[11] * b[7]) + (a[12] * b[12]) + (a[13] * b[17]); + out[13] = (a[10] * b[3]) + (a[11] * b[8]) + (a[12] * b[13]) + (a[13] * b[18]); + out[14] = (a[10] * b[4]) + (a[11] * b[9]) + (a[12] * b[14]) + (a[13] * b[19]) + a[14]; + // Alpha Channel + out[15] = (a[15] * b[0]) + (a[16] * b[5]) + (a[17] * b[10]) + (a[18] * b[15]); + out[16] = (a[15] * b[1]) + (a[16] * b[6]) + (a[17] * b[11]) + (a[18] * b[16]); + out[17] = (a[15] * b[2]) + (a[16] * b[7]) + (a[17] * b[12]) + (a[18] * b[17]); + out[18] = (a[15] * b[3]) + (a[16] * b[8]) + (a[17] * b[13]) + (a[18] * b[18]); + out[19] = (a[15] * b[4]) + (a[16] * b[9]) + (a[17] * b[14]) + (a[18] * b[19]) + a[19]; + return out; + }; + /** + * Create a Float32 Array and normalize the offset component to 0-1 + * @param {number[]} matrix - 5x4 matrix + * @returns {number[]} 5x4 matrix with all values between 0-1 + */ + ColorMatrixFilter.prototype._colorMatrix = function (matrix) { + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + return m; + }; + /** + * Adjusts brightness + * @param b - value of the brigthness (0-1, where 0 is black) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.brightness = function (b, multiply) { + var matrix = [ + b, 0, 0, 0, 0, + 0, b, 0, 0, 0, + 0, 0, b, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Sets each channel on the diagonal of the color matrix. + * This can be used to achieve a tinting effect on Containers similar to the tint field of some + * display objects like Sprite, Text, Graphics, and Mesh. + * @param color - Color of the tint. This is a hex value. + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.tint = function (color, multiply) { + var r = (color >> 16) & 0xff; + var g = (color >> 8) & 0xff; + var b = color & 0xff; + var matrix = [ + r / 255, 0, 0, 0, 0, + 0, g / 255, 0, 0, 0, + 0, 0, b / 255, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Set the matrices in grey scales + * @param scale - value of the grey (0-1, where 0 is black) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.greyscale = function (scale, multiply) { + var matrix = [ + scale, scale, scale, 0, 0, + scale, scale, scale, 0, 0, + scale, scale, scale, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Set the black and white matrice. + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.blackAndWhite = function (multiply) { + var matrix = [ + 0.3, 0.6, 0.1, 0, 0, + 0.3, 0.6, 0.1, 0, 0, + 0.3, 0.6, 0.1, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Set the hue property of the color + * @param rotation - in degrees + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.hue = function (rotation, multiply) { + rotation = (rotation || 0) / 180 * Math.PI; + var cosR = Math.cos(rotation); + var sinR = Math.sin(rotation); + var sqrt = Math.sqrt; + /* a good approximation for hue rotation + This matrix is far better than the versions with magic luminance constants + formerly used here, but also used in the starling framework (flash) and known from this + old part of the internet: quasimondo.com/archives/000565.php + + This new matrix is based on rgb cube rotation in space. Look here for a more descriptive + implementation as a shader not a general matrix: + https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js + + This is the source for the code: + see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 + */ + var w = 1 / 3; + var sqrW = sqrt(w); // weight is + var a00 = cosR + ((1.0 - cosR) * w); + var a01 = (w * (1.0 - cosR)) - (sqrW * sinR); + var a02 = (w * (1.0 - cosR)) + (sqrW * sinR); + var a10 = (w * (1.0 - cosR)) + (sqrW * sinR); + var a11 = cosR + (w * (1.0 - cosR)); + var a12 = (w * (1.0 - cosR)) - (sqrW * sinR); + var a20 = (w * (1.0 - cosR)) - (sqrW * sinR); + var a21 = (w * (1.0 - cosR)) + (sqrW * sinR); + var a22 = cosR + (w * (1.0 - cosR)); + var matrix = [ + a00, a01, a02, 0, 0, + a10, a11, a12, 0, 0, + a20, a21, a22, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Set the contrast matrix, increase the separation between dark and bright + * Increase contrast : shadows darker and highlights brighter + * Decrease contrast : bring the shadows up and the highlights down + * @param amount - value of the contrast (0-1) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.contrast = function (amount, multiply) { + var v = (amount || 0) + 1; + var o = -0.5 * (v - 1); + var matrix = [ + v, 0, 0, 0, o, + 0, v, 0, 0, o, + 0, 0, v, 0, o, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Set the saturation matrix, increase the separation between colors + * Increase saturation : increase contrast, brightness, and sharpness + * @param amount - The saturation amount (0-1) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.saturate = function (amount, multiply) { + if (amount === void 0) { amount = 0; } + var x = (amount * 2 / 3) + 1; + var y = ((x - 1) * -0.5); + var matrix = [ + x, y, y, 0, 0, + y, x, y, 0, 0, + y, y, x, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** Desaturate image (remove color) Call the saturate function */ + ColorMatrixFilter.prototype.desaturate = function () { + this.saturate(-1); + }; + /** + * Negative image (inverse of classic rgb matrix) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.negative = function (multiply) { + var matrix = [ + -1, 0, 0, 1, 0, + 0, -1, 0, 1, 0, + 0, 0, -1, 1, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Sepia image + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.sepia = function (multiply) { + var matrix = [ + 0.393, 0.7689999, 0.18899999, 0, 0, + 0.349, 0.6859999, 0.16799999, 0, 0, + 0.272, 0.5339999, 0.13099999, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Color motion picture process invented in 1916 (thanks Dominic Szablewski) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.technicolor = function (multiply) { + var matrix = [ + 1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, + -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, + -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Polaroid filter + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.polaroid = function (multiply) { + var matrix = [ + 1.438, -0.062, -0.062, 0, 0, + -0.122, 1.378, -0.122, 0, 0, + -0.016, -0.016, 1.483, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Filter who transforms : Red -> Blue and Blue -> Red + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.toBGR = function (multiply) { + var matrix = [ + 0, 0, 1, 0, 0, + 0, 1, 0, 0, 0, + 1, 0, 0, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.kodachrome = function (multiply) { + var matrix = [ + 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, + -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, + -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Brown delicious browni filter (thanks Dominic Szablewski) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.browni = function (multiply) { + var matrix = [ + 0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, + -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, + 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Vintage filter (thanks Dominic Szablewski) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.vintage = function (multiply) { + var matrix = [ + 0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, + 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, + 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * We don't know exactly what it does, kind of gradient map, but funny to play with! + * @param desaturation - Tone values. + * @param toned - Tone values. + * @param lightColor - Tone values, example: `0xFFE580` + * @param darkColor - Tone values, example: `0xFFE580` + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.colorTone = function (desaturation, toned, lightColor, darkColor, multiply) { + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 0xFFE580; + darkColor = darkColor || 0x338000; + var lR = ((lightColor >> 16) & 0xFF) / 255; + var lG = ((lightColor >> 8) & 0xFF) / 255; + var lB = (lightColor & 0xFF) / 255; + var dR = ((darkColor >> 16) & 0xFF) / 255; + var dG = ((darkColor >> 8) & 0xFF) / 255; + var dB = (darkColor & 0xFF) / 255; + var matrix = [ + 0.3, 0.59, 0.11, 0, 0, + lR, lG, lB, desaturation, 0, + dR, dG, dB, toned, 0, + lR - dR, lG - dG, lB - dB, 0, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Night effect + * @param intensity - The intensity of the night effect. + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.night = function (intensity, multiply) { + intensity = intensity || 0.1; + var matrix = [ + intensity * (-2.0), -intensity, 0, 0, 0, + -intensity, 0, intensity, 0, 0, + 0, intensity, intensity * 2.0, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Predator effect + * + * Erase the current matrix by setting a new indepent one + * @param amount - how much the predator feels his future victim + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.predator = function (amount, multiply) { + var matrix = [ + // row 1 + 11.224130630493164 * amount, + -4.794486999511719 * amount, + -2.8746118545532227 * amount, + 0 * amount, + 0.40342438220977783 * amount, + // row 2 + -3.6330697536468506 * amount, + 9.193157196044922 * amount, + -2.951810836791992 * amount, + 0 * amount, + -1.316135048866272 * amount, + // row 3 + -3.2184197902679443 * amount, + -4.2375030517578125 * amount, + 7.476448059082031 * amount, + 0 * amount, + 0.8044459223747253 * amount, + // row 4 + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * LSD effect + * + * Multiply the current matrix + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.lsd = function (multiply) { + var matrix = [ + 2, -0.4, 0.5, 0, 0, + -0.5, 2, -0.4, 0, 0, + -0.4, -0.5, 3, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** Erase the current matrix by setting the default one. */ + ColorMatrixFilter.prototype.reset = function () { + var matrix = [ + 1, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, false); + }; + Object.defineProperty(ColorMatrixFilter.prototype, "matrix", { + /** + * The matrix of the color matrix filter + * @member {number[]} + * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + */ + get: function () { + return this.uniforms.m; + }, + set: function (value) { + this.uniforms.m = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ColorMatrixFilter.prototype, "alpha", { + /** + * The opacity value to use when mixing the original and resultant colors. + * + * When the value is 0, the original color is used without modification. + * When the value is 1, the result color is used. + * When in the range (0, 1) the color is interpolated between the original and result by this amount. + * @default 1 + */ + get: function () { + return this.uniforms.uAlpha; + }, + set: function (value) { + this.uniforms.uAlpha = value; + }, + enumerable: false, + configurable: true + }); + return ColorMatrixFilter; + }(Filter)); + // Americanized alias + ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + + /*! + * @pixi/filter-displacement - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/filter-displacement is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ -var _deprecation2 = _interopRequireDefault(_deprecation); + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$4 = function(d, b) { + extendStatics$4 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$4(d, b); + }; -var _accessibility = require('./accessibility'); + function __extends$4(d, b) { + extendStatics$4(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } -var accessibility = _interopRequireWildcard(_accessibility); + var fragment$2 = "varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\nuniform mat2 rotation;\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform highp vec4 inputSize;\nuniform vec4 inputClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy = scale * inputSize.zw * (rotation * map.xy);\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), inputClamp.xy, inputClamp.zw));\n}\n"; -var _extract = require('./extract'); + var vertex$1 = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n\tgl_Position = filterVertexPosition();\n\tvTextureCoord = filterTextureCoord();\n\tvFilterCoord = ( filterMatrix * vec3( vTextureCoord, 1.0) ).xy;\n}\n"; -var extract = _interopRequireWildcard(_extract); + /** + * The DisplacementFilter class uses the pixel values from the specified texture + * (called the displacement map) to perform a displacement of an object. + * + * You can use this filter to apply all manor of crazy warping effects. + * Currently the `r` property of the texture is used to offset the `x` + * and the `g` property of the texture is used to offset the `y`. + * + * The way it works is it uses the values of the displacement map to look up the + * correct pixels to output. This means it's not technically moving the original. + * Instead, it's starting at the output and asking "which pixel from the original goes here". + * For example, if a displacement map pixel has `red = 1` and the filter scale is `20`, + * this filter will output the pixel approximately 20 pixels to the right of the original. + * @memberof PIXI.filters + */ + var DisplacementFilter = /** @class */ (function (_super) { + __extends$4(DisplacementFilter, _super); + /** + * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) + * @param scale - The scale of the displacement + */ + function DisplacementFilter(sprite, scale) { + var _this = this; + var maskMatrix = new Matrix(); + sprite.renderable = false; + _this = _super.call(this, vertex$1, fragment$2, { + mapSampler: sprite._texture, + filterMatrix: maskMatrix, + scale: { x: 1, y: 1 }, + rotation: new Float32Array([1, 0, 0, 1]), + }) || this; + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + if (scale === null || scale === undefined) { + scale = 20; + } + /** + * scaleX, scaleY for displacements + * @member {PIXI.Point} + */ + _this.scale = new Point(scale, scale); + return _this; + } + /** + * Applies the filter. + * @param filterManager - The manager. + * @param input - The input target. + * @param output - The output target. + * @param clearMode - clearMode. + */ + DisplacementFilter.prototype.apply = function (filterManager, input, output, clearMode) { + // fill maskMatrix with _normalized sprite texture coords_ + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x; + this.uniforms.scale.y = this.scale.y; + // Extract rotation from world transform + var wt = this.maskSprite.worldTransform; + var lenX = Math.sqrt((wt.a * wt.a) + (wt.b * wt.b)); + var lenY = Math.sqrt((wt.c * wt.c) + (wt.d * wt.d)); + if (lenX !== 0 && lenY !== 0) { + this.uniforms.rotation[0] = wt.a / lenX; + this.uniforms.rotation[1] = wt.b / lenX; + this.uniforms.rotation[2] = wt.c / lenY; + this.uniforms.rotation[3] = wt.d / lenY; + } + // draw the filter... + filterManager.applyFilter(this, input, output, clearMode); + }; + Object.defineProperty(DisplacementFilter.prototype, "map", { + /** The texture used for the displacement map. Must be power of 2 sized texture. */ + get: function () { + return this.uniforms.mapSampler; + }, + set: function (value) { + this.uniforms.mapSampler = value; + }, + enumerable: false, + configurable: true + }); + return DisplacementFilter; + }(Filter)); + + /*! + * @pixi/filter-fxaa - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/filter-fxaa is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ -var _extras = require('./extras'); + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$3 = function(d, b) { + extendStatics$3 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$3(d, b); + }; -var extras = _interopRequireWildcard(_extras); + function __extends$3(d, b) { + extendStatics$3(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } -var _filters = require('./filters'); + var vertex = "\nattribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvoid texcoords(vec2 fragCoord, vec2 inverseVP,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = filterVertexPosition();\n\n vFragCoord = aVertexPosition * outputFrame.zw;\n\n texcoords(vFragCoord, inputSize.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}\n"; -var filters = _interopRequireWildcard(_filters); + var fragment$1 = "varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\nuniform sampler2D uSampler;\nuniform highp vec4 inputSize;\n\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it's\n unsupported by WebGL.\n\n --\n\n From:\n https://github.com/mitsuhiko/webgl-meincraft\n\n Copyright (c) 2011 by Armin Ronacher.\n\n Some rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n\n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 inverseVP,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n\n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n\n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec4 color;\n\n color = fxaa(uSampler, vFragCoord, inputSize.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n"; -var _interaction = require('./interaction'); + /** + * Basic FXAA (Fast Approximate Anti-Aliasing) implementation based on the code on geeks3d.com + * with the modification that the texture2DLod stuff was removed since it is unsupported by WebGL. + * @see https://github.com/mitsuhiko/webgl-meincraft + * @memberof PIXI.filters + */ + var FXAAFilter = /** @class */ (function (_super) { + __extends$3(FXAAFilter, _super); + function FXAAFilter() { + // TODO - needs work + return _super.call(this, vertex, fragment$1) || this; + } + return FXAAFilter; + }(Filter)); -var interaction = _interopRequireWildcard(_interaction); + /*! + * @pixi/filter-noise - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/filter-noise is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ -var _loaders = require('./loaders'); + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$2 = function(d, b) { + extendStatics$2 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$2(d, b); + }; -var loaders = _interopRequireWildcard(_loaders); + function __extends$2(d, b) { + extendStatics$2(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } -var _mesh = require('./mesh'); + var fragment = "precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n"; -var mesh = _interopRequireWildcard(_mesh); + /** + * A Noise effect filter. + * + * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + * @memberof PIXI.filters + * @author Vico @vicocotea + */ + var NoiseFilter = /** @class */ (function (_super) { + __extends$2(NoiseFilter, _super); + /** + * @param {number} [noise=0.5] - The noise intensity, should be a normalized value in the range [0, 1]. + * @param {number} [seed] - A random seed for the noise generation. Default is `Math.random()`. + */ + function NoiseFilter(noise, seed) { + if (noise === void 0) { noise = 0.5; } + if (seed === void 0) { seed = Math.random(); } + var _this = _super.call(this, defaultFilterVertex, fragment, { + uNoise: 0, + uSeed: 0, + }) || this; + _this.noise = noise; + _this.seed = seed; + return _this; + } + Object.defineProperty(NoiseFilter.prototype, "noise", { + /** + * The amount of noise to apply, this value should be in the range (0, 1]. + * @default 0.5 + */ + get: function () { + return this.uniforms.uNoise; + }, + set: function (value) { + this.uniforms.uNoise = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NoiseFilter.prototype, "seed", { + /** A seed value to apply to the random noise generation. `Math.random()` is a good value to use. */ + get: function () { + return this.uniforms.uSeed; + }, + set: function (value) { + this.uniforms.uSeed = value; + }, + enumerable: false, + configurable: true + }); + return NoiseFilter; + }(Filter)); + + /*! + * @pixi/mixin-cache-as-bitmap - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/mixin-cache-as-bitmap is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ -var _particles = require('./particles'); + var _tempMatrix = new Matrix(); + DisplayObject.prototype._cacheAsBitmap = false; + DisplayObject.prototype._cacheData = null; + DisplayObject.prototype._cacheAsBitmapResolution = null; + DisplayObject.prototype._cacheAsBitmapMultisample = exports.MSAA_QUALITY.NONE; + // figured there's no point adding ALL the extra variables to prototype. + // this model can hold the information needed. This can also be generated on demand as + // most objects are not cached as bitmaps. + /** + * @class + * @ignore + * @private + */ + var CacheData = /** @class */ (function () { + function CacheData() { + this.textureCacheId = null; + this.originalRender = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + this.originalUpdateTransform = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.originalContainsPoint = null; + this.sprite = null; + } + return CacheData; + }()); + Object.defineProperties(DisplayObject.prototype, { + /** + * The resolution to use for cacheAsBitmap. By default this will use the renderer's resolution + * but can be overriden for performance. Lower values will reduce memory usage at the expense + * of render quality. A falsey value of `null` or `0` will default to the renderer's resolution. + * If `cacheAsBitmap` is set to `true`, this will re-render with the new resolution. + * @member {number} cacheAsBitmapResolution + * @memberof PIXI.DisplayObject# + * @default null + */ + cacheAsBitmapResolution: { + get: function () { + return this._cacheAsBitmapResolution; + }, + set: function (resolution) { + if (resolution === this._cacheAsBitmapResolution) { + return; + } + this._cacheAsBitmapResolution = resolution; + if (this.cacheAsBitmap) { + // Toggle to re-render at the new resolution + this.cacheAsBitmap = false; + this.cacheAsBitmap = true; + } + }, + }, + /** + * The number of samples to use for cacheAsBitmap. If set to `null`, the renderer's + * sample count is used. + * If `cacheAsBitmap` is set to `true`, this will re-render with the new number of samples. + * @member {number} cacheAsBitmapMultisample + * @memberof PIXI.DisplayObject# + * @default PIXI.MSAA_QUALITY.NONE + */ + cacheAsBitmapMultisample: { + get: function () { + return this._cacheAsBitmapMultisample; + }, + set: function (multisample) { + if (multisample === this._cacheAsBitmapMultisample) { + return; + } + this._cacheAsBitmapMultisample = multisample; + if (this.cacheAsBitmap) { + // Toggle to re-render with new multisample + this.cacheAsBitmap = false; + this.cacheAsBitmap = true; + } + }, + }, + /** + * Set this to true if you want this display object to be cached as a bitmap. + * This basically takes a snap shot of the display object as it is at that moment. It can + * provide a performance benefit for complex static displayObjects. + * To remove simply set this property to `false` + * + * IMPORTANT GOTCHA - Make sure that all your textures are preloaded BEFORE setting this property to true + * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + cacheAsBitmap: { + get: function () { + return this._cacheAsBitmap; + }, + set: function (value) { + if (this._cacheAsBitmap === value) { + return; + } + this._cacheAsBitmap = value; + var data; + if (value) { + if (!this._cacheData) { + this._cacheData = new CacheData(); + } + data = this._cacheData; + data.originalRender = this.render; + data.originalRenderCanvas = this.renderCanvas; + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this.calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + data.originalDestroy = this.destroy; + data.originalContainsPoint = this.containsPoint; + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + this.render = this._renderCached; + this.renderCanvas = this._renderCachedCanvas; + this.destroy = this._cacheAsBitmapDestroy; + } + else { + data = this._cacheData; + if (data.sprite) { + this._destroyCachedDisplayObject(); + } + this.render = data.originalRender; + this.renderCanvas = data.originalRenderCanvas; + this.calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + this.destroy = data.originalDestroy; + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + }, + }, + }); + /** + * Renders a cached version of the sprite with WebGL + * @private + * @method _renderCached + * @memberof PIXI.DisplayObject# + * @param {PIXI.Renderer} renderer - the WebGL renderer + */ + DisplayObject.prototype._renderCached = function _renderCached(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + this._initCachedDisplayObject(renderer); + this._cacheData.sprite.transform._worldID = this.transform._worldID; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._render(renderer); + }; + /** + * Prepares the WebGL renderer to cache the sprite + * @private + * @method _initCachedDisplayObject + * @memberof PIXI.DisplayObject# + * @param {PIXI.Renderer} renderer - the WebGL renderer + */ + DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { + var _a; + if (this._cacheData && this._cacheData.sprite) { + return; + } + // make sure alpha is set to 1 otherwise it will get rendered as invisible! + var cacheAlpha = this.alpha; + this.alpha = 1; + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.batch.flush(); + // this.filters= []; + // next we find the dimensions of the untransformed object + // this function also calls updatetransform on all its children as part of the measuring. + // This means we don't need to update the transform again in this function + // TODO pass an object to clone too? saves having to create a new one each time! + var bounds = this.getLocalBounds(null, true).clone(); + // add some padding! + if (this.filters && this.filters.length) { + var padding = this.filters[0].padding; + bounds.pad(padding); + } + bounds.ceil(settings.RESOLUTION); + // for now we cache the current renderTarget that the WebGL renderer is currently using. + // this could be more elegant.. + var cachedRenderTexture = renderer.renderTexture.current; + var cachedSourceFrame = renderer.renderTexture.sourceFrame.clone(); + var cachedDestinationFrame = renderer.renderTexture.destinationFrame.clone(); + var cachedProjectionTransform = renderer.projection.transform; + // We also store the filter stack - I will definitely look to change how this works a little later down the line. + // const stack = renderer.filterManager.filterStack; + // this renderTexture will be used to store the cached DisplayObject + var renderTexture = RenderTexture.create({ + width: bounds.width, + height: bounds.height, + resolution: this.cacheAsBitmapResolution || renderer.resolution, + multisample: (_a = this.cacheAsBitmapMultisample) !== null && _a !== void 0 ? _a : renderer.multisample, + }); + var textureCacheId = "cacheAsBitmap_" + uid(); + this._cacheData.textureCacheId = textureCacheId; + BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId); + Texture.addToCache(renderTexture, textureCacheId); + // need to set // + var m = this.transform.localTransform.copyTo(_tempMatrix).invert().translate(-bounds.x, -bounds.y); + // set all properties to there original so we can render to a texture + this.render = this._cacheData.originalRender; + renderer.render(this, { renderTexture: renderTexture, clear: true, transform: m, skipUpdateTransform: false }); + renderer.framebuffer.blit(); + // now restore the state be setting the new properties + renderer.projection.transform = cachedProjectionTransform; + renderer.renderTexture.bind(cachedRenderTexture, cachedSourceFrame, cachedDestinationFrame); + // renderer.filterManager.filterStack = stack; + this.render = this._renderCached; + // the rest is the same as for Canvas + this.updateTransform = this.displayObjectUpdateTransform; + this.calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + this._mask = null; + this.filterArea = null; + this.alpha = cacheAlpha; + // create our cached sprite + var cachedSprite = new Sprite(renderTexture); + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + this._cacheData.sprite = cachedSprite; + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + if (!this.parent) { + this.enableTempParent(); + this.updateTransform(); + this.disableTempParent(null); + } + else { + this.updateTransform(); + } + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); + }; + /** + * Renders a cached version of the sprite with canvas + * @private + * @method _renderCachedCanvas + * @memberof PIXI.DisplayObject# + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ + DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + this._initCachedDisplayObjectCanvas(renderer); + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderCanvas(renderer); + }; + // TODO this can be the same as the WebGL version.. will need to do a little tweaking first though.. + /** + * Prepares the Canvas renderer to cache the sprite + * @private + * @method _initCachedDisplayObjectCanvas + * @memberof PIXI.DisplayObject# + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ + DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + // get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(null, true); + var cacheAlpha = this.alpha; + this.alpha = 1; + var cachedRenderTarget = renderer.context; + var cachedProjectionTransform = renderer._projTransform; + bounds.ceil(settings.RESOLUTION); + var renderTexture = RenderTexture.create({ width: bounds.width, height: bounds.height }); + var textureCacheId = "cacheAsBitmap_" + uid(); + this._cacheData.textureCacheId = textureCacheId; + BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId); + Texture.addToCache(renderTexture, textureCacheId); + // need to set // + var m = _tempMatrix; + this.transform.localTransform.copyTo(m); + m.invert(); + m.tx -= bounds.x; + m.ty -= bounds.y; + // m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; + renderer.render(this, { renderTexture: renderTexture, clear: true, transform: m, skipUpdateTransform: false }); + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; + renderer._projTransform = cachedProjectionTransform; + this.renderCanvas = this._renderCachedCanvas; + // the rest is the same as for WebGL + this.updateTransform = this.displayObjectUpdateTransform; + this.calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + this._mask = null; + this.filterArea = null; + this.alpha = cacheAlpha; + // create our cached sprite + var cachedSprite = new Sprite(renderTexture); + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + this._cacheData.sprite = cachedSprite; + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } + else { + this.updateTransform(); + } + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); + }; + /** + * Calculates the bounds of the cached sprite + * @private + * @method + */ + DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { + this._bounds.clear(); + this._cacheData.sprite.transform._worldID = this.transform._worldID; + this._cacheData.sprite._calculateBounds(); + this._bounds.updateID = this._boundsID; + }; + /** + * Gets the bounds of the cached sprite. + * @private + * @method + * @returns {Rectangle} The local bounds. + */ + DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { + return this._cacheData.sprite.getLocalBounds(null); + }; + /** + * Destroys the cached sprite. + * @private + * @method + */ + DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; + BaseTexture.removeFromCache(this._cacheData.textureCacheId); + Texture.removeFromCache(this._cacheData.textureCacheId); + this._cacheData.textureCacheId = null; + }; + /** + * Destroys the cached object. + * @private + * @method + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value. + * Used when destroying containers, see the Container.destroy method. + */ + DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) { + this.cacheAsBitmap = false; + this.destroy(options); + }; -var particles = _interopRequireWildcard(_particles); + /*! + * @pixi/mixin-get-child-by-name - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/mixin-get-child-by-name is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ -var _prepare = require('./prepare'); + /** + * The instance name of the object. + * @memberof PIXI.DisplayObject# + * @member {string} name + */ + DisplayObject.prototype.name = null; + /** + * Returns the display object in the container. + * + * Recursive searches are done in a preorder traversal. + * @method getChildByName + * @memberof PIXI.Container# + * @param {string} name - Instance name. + * @param {boolean}[deep=false] - Whether to search recursively + * @returns {PIXI.DisplayObject} The child with the specified name. + */ + Container.prototype.getChildByName = function getChildByName(name, deep) { + for (var i = 0, j = this.children.length; i < j; i++) { + if (this.children[i].name === name) { + return this.children[i]; + } + } + if (deep) { + for (var i = 0, j = this.children.length; i < j; i++) { + var child = this.children[i]; + if (!child.getChildByName) { + continue; + } + var target = child.getChildByName(name, true); + if (target) { + return target; + } + } + } + return null; + }; -var prepare = _interopRequireWildcard(_prepare); + /*! + * @pixi/mixin-get-global-position - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/mixin-get-global-position is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + /** + * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. + * @method getGlobalPosition + * @memberof PIXI.DisplayObject# + * @param {PIXI.Point} [point=new PIXI.Point()] - The point to write the global value to. + * @param {boolean} [skipUpdate=false] - Setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost. + * @returns {PIXI.Point} The updated point. + */ + DisplayObject.prototype.getGlobalPosition = function getGlobalPosition(point, skipUpdate) { + if (point === void 0) { point = new Point(); } + if (skipUpdate === void 0) { skipUpdate = false; } + if (this.parent) { + this.parent.toGlobal(this.position, point, skipUpdate); + } + else { + point.x = this.position.x; + point.y = this.position.y; + } + return point; + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /*! + * @pixi/app - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/app is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ -// export core -_core.utils.mixins.performMixins(); + /** + * Middleware for for Application's resize functionality + * @private + * @class + */ + var ResizePlugin = /** @class */ (function () { + function ResizePlugin() { + } + /** + * Initialize the plugin with scope of application instance + * @static + * @private + * @param {object} [options] - See application options + */ + ResizePlugin.init = function (options) { + var _this = this; + Object.defineProperty(this, 'resizeTo', + /** + * The HTML element or window to automatically resize the + * renderer's view element to match width and height. + * @member {Window|HTMLElement} + * @name resizeTo + * @memberof PIXI.Application# + */ + { + set: function (dom) { + globalThis.removeEventListener('resize', this.queueResize); + this._resizeTo = dom; + if (dom) { + globalThis.addEventListener('resize', this.queueResize); + this.resize(); + } + }, + get: function () { + return this._resizeTo; + }, + }); + /** + * Resize is throttled, so it's safe to call this multiple times per frame and it'll + * only be called once. + * @memberof PIXI.Application# + * @method queueResize + * @private + */ + this.queueResize = function () { + if (!_this._resizeTo) { + return; + } + _this.cancelResize(); + // // Throttle resize events per raf + _this._resizeId = requestAnimationFrame(function () { return _this.resize(); }); + }; + /** + * Cancel the resize queue. + * @memberof PIXI.Application# + * @method cancelResize + * @private + */ + this.cancelResize = function () { + if (_this._resizeId) { + cancelAnimationFrame(_this._resizeId); + _this._resizeId = null; + } + }; + /** + * Execute an immediate resize on the renderer, this is not + * throttled and can be expensive to call many times in a row. + * Will resize only if `resizeTo` property is set. + * @memberof PIXI.Application# + * @method resize + */ + this.resize = function () { + if (!_this._resizeTo) { + return; + } + // clear queue resize + _this.cancelResize(); + var width; + var height; + // Resize to the window + if (_this._resizeTo === globalThis.window) { + width = globalThis.innerWidth; + height = globalThis.innerHeight; + } + // Resize to other HTML entities + else { + var _a = _this._resizeTo, clientWidth = _a.clientWidth, clientHeight = _a.clientHeight; + width = clientWidth; + height = clientHeight; + } + _this.renderer.resize(width, height); + }; + // On resize + this._resizeId = null; + this._resizeTo = null; + this.resizeTo = options.resizeTo || null; + }; + /** + * Clean up the ticker, scoped to application + * @static + * @private + */ + ResizePlugin.destroy = function () { + globalThis.removeEventListener('resize', this.queueResize); + this.cancelResize(); + this.cancelResize = null; + this.queueResize = null; + this.resizeTo = null; + this.resize = null; + }; + /** @ignore */ + ResizePlugin.extension = exports.ExtensionType.Application; + return ResizePlugin; + }()); -/** - * Alias for {@link PIXI.loaders.shared}. - * @name loader - * @memberof PIXI - * @type {PIXI.loader.Loader} - */ + /** + * Convenience class to create a new PIXI application. + * + * This class automatically creates the renderer, ticker and root container. + * @example + * // Create the application + * const app = new PIXI.Application(); + * + * // Add the view to the DOM + * document.body.appendChild(app.view); + * + * // ex, add display objects + * app.stage.addChild(PIXI.Sprite.from('something.png')); + * @class + * @memberof PIXI + */ + var Application = /** @class */ (function () { + /** + * @param {PIXI.IApplicationOptions} [options] - The optional application and renderer parameters. + * @param {boolean} [options.antialias=false] - + * **WebGL Only.** Whether to enable anti-aliasing. This may affect performance. + * @param {boolean} [options.autoDensity=false] - + * Whether the CSS dimensions of the renderer's view should be resized automatically. + * @param {boolean} [options.autoStart=true] - Automatically starts the rendering after the construction. + * **Note**: Setting this parameter to false does NOT stop the shared ticker even if you set + * `options.sharedTicker` to `true` in case that it is already started. Stop it by your own. + * @param {number} [options.backgroundAlpha=1] - + * Transparency of the background color, value from `0` (fully transparent) to `1` (fully opaque). + * @param {number} [options.backgroundColor=0x000000] - + * The background color used to clear the canvas. It accepts hex numbers (e.g. `0xff0000`). + * @param {boolean} [options.clearBeforeRender=true] - Whether to clear the canvas before new render passes. + * @param {PIXI.IRenderingContext} [options.context] - **WebGL Only.** User-provided WebGL rendering context object. + * @param {boolean} [options.forceCanvas=false] - + * Force using {@link PIXI.CanvasRenderer}, even if WebGL is available. This option only is available when + * using **pixi.js-legacy** or **@pixi/canvas-renderer** packages, otherwise it is ignored. + * @param {number} [options.height=600] - The height of the renderer's view. + * @param {string} [options.powerPreference] - + * **WebGL Only.** A hint indicating what configuration of GPU is suitable for the WebGL context, + * can be `'default'`, `'high-performance'` or `'low-power'`. + * Setting to `'high-performance'` will prioritize rendering performance over power consumption, + * while setting to `'low-power'` will prioritize power saving over rendering performance. + * @param {boolean} [options.premultipliedAlpha=true] - + * **WebGL Only.** Whether the compositor will assume the drawing buffer contains colors with premultiplied alpha. + * @param {boolean} [options.preserveDrawingBuffer=false] - + * **WebGL Only.** Whether to enable drawing buffer preservation. If enabled, the drawing buffer will preserve + * its value until cleared or overwritten. Enable this if you need to call `toDataUrl` on the WebGL context. + * @param {Window|HTMLElement} [options.resizeTo] - Element to automatically resize stage to. + * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - + * The resolution / device pixel ratio of the renderer. + * @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.Loader.shared, `false` to create new Loader. + * @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.Ticker.shared, `false` to create new ticker. + * If set to `false`, you cannot register a handler to occur before anything that runs on the shared ticker. + * The system ticker will always run before both the shared ticker and the app ticker. + * @param {boolean} [options.transparent] - + * **Deprecated since 6.0.0, Use `backgroundAlpha` instead.** \ + * `true` sets `backgroundAlpha` to `0`, `false` sets `backgroundAlpha` to `1`. + * @param {boolean|'notMultiplied'} [options.useContextAlpha=true] - + * Pass-through value for canvas' context attribute `alpha`. This option is for cases where the + * canvas needs to be opaque, possibly for performance reasons on some older devices. + * If you want to set transparency, please use `backgroundAlpha`. \ + * **WebGL Only:** When set to `'notMultiplied'`, the canvas' context attribute `alpha` will be + * set to `true` and `premultipliedAlpha` will be to `false`. + * @param {HTMLCanvasElement} [options.view=null] - + * The canvas to use as the view. If omitted, a new canvas will be created. + * @param {number} [options.width=800] - The width of the renderer's view. + */ + function Application(options) { + var _this = this; + /** + * The root display container that's rendered. + * @member {PIXI.Container} + */ + this.stage = new Container(); + // The default options + options = Object.assign({ + forceCanvas: false, + }, options); + this.renderer = autoDetectRenderer(options); + // install plugins here + Application._plugins.forEach(function (plugin) { + plugin.init.call(_this, options); + }); + } + /** + * Use the {@link PIXI.extensions.add} API to register plugins. + * @deprecated since 6.5.0 + * @static + * @param {PIXI.IApplicationPlugin} plugin - Plugin being installed + */ + Application.registerPlugin = function (plugin) { + deprecation('6.5.0', 'Application.registerPlugin() is deprecated, use extensions.add()'); + extensions.add({ + type: exports.ExtensionType.Application, + ref: plugin, + }); + }; + /** Render the current stage. */ + Application.prototype.render = function () { + this.renderer.render(this.stage); + }; + Object.defineProperty(Application.prototype, "view", { + /** + * Reference to the renderer's canvas element. + * @member {HTMLCanvasElement} + * @readonly + */ + get: function () { + return this.renderer.view; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Application.prototype, "screen", { + /** + * Reference to the renderer's screen rectangle. Its safe to use as `filterArea` or `hitArea` for the whole screen. + * @member {PIXI.Rectangle} + * @readonly + */ + get: function () { + return this.renderer.screen; + }, + enumerable: false, + configurable: true + }); + /** + * Destroy and don't use after this. + * @param {boolean} [removeView=false] - Automatically remove canvas from DOM. + * @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy + * method called as well. 'stageOptions' will be passed on to those calls. + * @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set + * to true. Should it destroy the texture of the child sprite + * @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set + * to true. Should it destroy the base texture of the child sprite + */ + Application.prototype.destroy = function (removeView, stageOptions) { + var _this = this; + // Destroy plugins in the opposite order + // which they were constructed + var plugins = Application._plugins.slice(0); + plugins.reverse(); + plugins.forEach(function (plugin) { + plugin.destroy.call(_this); + }); + this.stage.destroy(stageOptions); + this.stage = null; + this.renderer.destroy(removeView); + this.renderer = null; + }; + /** Collection of installed plugins. */ + Application._plugins = []; + return Application; + }()); + extensions.handleByList(exports.ExtensionType.Application, Application._plugins); + + extensions.add(ResizePlugin); + + /*! + * @pixi/mesh-extras - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/mesh-extras is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$1 = function(d, b) { + extendStatics$1 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$1(d, b); + }; -// handle mixins now, after all code has been added, including deprecation + function __extends$1(d, b) { + extendStatics$1(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + /** + * @memberof PIXI + */ + var PlaneGeometry = /** @class */ (function (_super) { + __extends$1(PlaneGeometry, _super); + /** + * @param width - The width of the plane. + * @param height - The height of the plane. + * @param segWidth - Number of horizontal segments. + * @param segHeight - Number of vertical segments. + */ + function PlaneGeometry(width, height, segWidth, segHeight) { + if (width === void 0) { width = 100; } + if (height === void 0) { height = 100; } + if (segWidth === void 0) { segWidth = 10; } + if (segHeight === void 0) { segHeight = 10; } + var _this = _super.call(this) || this; + _this.segWidth = segWidth; + _this.segHeight = segHeight; + _this.width = width; + _this.height = height; + _this.build(); + return _this; + } + /** + * Refreshes plane coordinates + * @private + */ + PlaneGeometry.prototype.build = function () { + var total = this.segWidth * this.segHeight; + var verts = []; + var uvs = []; + var indices = []; + var segmentsX = this.segWidth - 1; + var segmentsY = this.segHeight - 1; + var sizeX = (this.width) / segmentsX; + var sizeY = (this.height) / segmentsY; + for (var i = 0; i < total; i++) { + var x = (i % this.segWidth); + var y = ((i / this.segWidth) | 0); + verts.push(x * sizeX, y * sizeY); + uvs.push(x / segmentsX, y / segmentsY); + } + var totalSub = segmentsX * segmentsY; + for (var i = 0; i < totalSub; i++) { + var xpos = i % segmentsX; + var ypos = (i / segmentsX) | 0; + var value = (ypos * this.segWidth) + xpos; + var value2 = (ypos * this.segWidth) + xpos + 1; + var value3 = ((ypos + 1) * this.segWidth) + xpos; + var value4 = ((ypos + 1) * this.segWidth) + xpos + 1; + indices.push(value, value2, value3, value2, value4, value3); + } + this.buffers[0].data = new Float32Array(verts); + this.buffers[1].data = new Float32Array(uvs); + this.indexBuffer.data = new Uint16Array(indices); + // ensure that the changes are uploaded + this.buffers[0].update(); + this.buffers[1].update(); + this.indexBuffer.update(); + }; + return PlaneGeometry; + }(MeshGeometry)); -// export libs -// import polyfills. Done as an export to make sure polyfills are imported first -var loader = loaders.shared || null; + /** + * RopeGeometry allows you to draw a geometry across several points and then manipulate these points. + * + * ```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * const rope = new PIXI.RopeGeometry(100, points); + * ``` + * @memberof PIXI + */ + var RopeGeometry = /** @class */ (function (_super) { + __extends$1(RopeGeometry, _super); + /** + * @param width - The width (i.e., thickness) of the rope. + * @param points - An array of {@link PIXI.Point} objects to construct this rope. + * @param textureScale - By default the rope texture will be stretched to match + * rope length. If textureScale is positive this value will be treated as a scaling + * factor and the texture will preserve its aspect ratio instead. To create a tiling rope + * set baseTexture.wrapMode to {@link PIXI.WRAP_MODES.REPEAT} and use a power of two texture, + * then set textureScale=1 to keep the original texture pixel size. + * In order to reduce alpha channel artifacts provide a larger texture and downsample - + * i.e. set textureScale=0.5 to scale it down twice. + */ + function RopeGeometry(width, points, textureScale) { + if (width === void 0) { width = 200; } + if (textureScale === void 0) { textureScale = 0; } + var _this = _super.call(this, new Float32Array(points.length * 4), new Float32Array(points.length * 4), new Uint16Array((points.length - 1) * 6)) || this; + _this.points = points; + _this._width = width; + _this.textureScale = textureScale; + _this.build(); + return _this; + } + Object.defineProperty(RopeGeometry.prototype, "width", { + /** + * The width (i.e., thickness) of the rope. + * @readonly + */ + get: function () { + return this._width; + }, + enumerable: false, + configurable: true + }); + /** Refreshes Rope indices and uvs */ + RopeGeometry.prototype.build = function () { + var points = this.points; + if (!points) + { return; } + var vertexBuffer = this.getBuffer('aVertexPosition'); + var uvBuffer = this.getBuffer('aTextureCoord'); + var indexBuffer = this.getIndex(); + // if too little points, or texture hasn't got UVs set yet just move on. + if (points.length < 1) { + return; + } + // if the number of points has changed we will need to recreate the arraybuffers + if (vertexBuffer.data.length / 4 !== points.length) { + vertexBuffer.data = new Float32Array(points.length * 4); + uvBuffer.data = new Float32Array(points.length * 4); + indexBuffer.data = new Uint16Array((points.length - 1) * 6); + } + var uvs = uvBuffer.data; + var indices = indexBuffer.data; + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + var amount = 0; + var prev = points[0]; + var textureWidth = this._width * this.textureScale; + var total = points.length; // - 1; + for (var i = 0; i < total; i++) { + // time to do some smart drawing! + var index = i * 4; + if (this.textureScale > 0) { + // calculate pixel distance from previous point + var dx = prev.x - points[i].x; + var dy = prev.y - points[i].y; + var distance = Math.sqrt((dx * dx) + (dy * dy)); + prev = points[i]; + amount += distance / textureWidth; + } + else { + // stretch texture + amount = i / (total - 1); + } + uvs[index] = amount; + uvs[index + 1] = 0; + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + var indexCount = 0; + for (var i = 0; i < total - 1; i++) { + var index = i * 2; + indices[indexCount++] = index; + indices[indexCount++] = index + 1; + indices[indexCount++] = index + 2; + indices[indexCount++] = index + 2; + indices[indexCount++] = index + 1; + indices[indexCount++] = index + 3; + } + // ensure that the changes are uploaded + uvBuffer.update(); + indexBuffer.update(); + this.updateVertices(); + }; + /** refreshes vertices of Rope mesh */ + RopeGeometry.prototype.updateVertices = function () { + var points = this.points; + if (points.length < 1) { + return; + } + var lastPoint = points[0]; + var nextPoint; + var perpX = 0; + var perpY = 0; + var vertices = this.buffers[0].data; + var total = points.length; + for (var i = 0; i < total; i++) { + var point = points[i]; + var index = i * 4; + if (i < points.length - 1) { + nextPoint = points[i + 1]; + } + else { + nextPoint = point; + } + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + var perpLength = Math.sqrt((perpX * perpX) + (perpY * perpY)); + var num = this.textureScale > 0 ? this.textureScale * this._width / 2 : this._width / 2; + perpX /= perpLength; + perpY /= perpLength; + perpX *= num; + perpY *= num; + vertices[index] = point.x + perpX; + vertices[index + 1] = point.y + perpY; + vertices[index + 2] = point.x - perpX; + vertices[index + 3] = point.y - perpY; + lastPoint = point; + } + this.buffers[0].update(); + }; + RopeGeometry.prototype.update = function () { + if (this.textureScale > 0) { + this.build(); // we need to update UVs + } + else { + this.updateVertices(); + } + }; + return RopeGeometry; + }(MeshGeometry)); -exports.accessibility = accessibility; -exports.extract = extract; -exports.extras = extras; -exports.filters = filters; -exports.interaction = interaction; -exports.loaders = loaders; -exports.mesh = mesh; -exports.particles = particles; -exports.prepare = prepare; -exports.loader = loader; + /** + * The rope allows you to draw a texture across several points and then manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let rope = new PIXI.SimpleRope(PIXI.Texture.from("snake.png"), points); + * ``` + * @memberof PIXI + */ + var SimpleRope = /** @class */ (function (_super) { + __extends$1(SimpleRope, _super); + /** + * @param texture - The texture to use on the rope. + * @param points - An array of {@link PIXI.Point} objects to construct this rope. + * @param {number} textureScale - Optional. Positive values scale rope texture + * keeping its aspect ratio. You can reduce alpha channel artifacts by providing a larger texture + * and downsampling here. If set to zero, texture will be stretched instead. + */ + function SimpleRope(texture, points, textureScale) { + if (textureScale === void 0) { textureScale = 0; } + var _this = this; + var ropeGeometry = new RopeGeometry(texture.height, points, textureScale); + var meshMaterial = new MeshMaterial(texture); + if (textureScale > 0) { + // attempt to set UV wrapping, will fail on non-power of two textures + texture.baseTexture.wrapMode = exports.WRAP_MODES.REPEAT; + } + _this = _super.call(this, ropeGeometry, meshMaterial) || this; + /** + * re-calculate vertices by rope points each frame + * @member {boolean} + */ + _this.autoUpdate = true; + return _this; + } + SimpleRope.prototype._render = function (renderer) { + var geometry = this.geometry; + if (this.autoUpdate || geometry._width !== this.shader.texture.height) { + geometry._width = this.shader.texture.height; + geometry.update(); + } + _super.prototype._render.call(this, renderer); + }; + return SimpleRope; + }(Mesh)); -// Apply the deprecations + /** + * The SimplePlane allows you to draw a texture across several points and then manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let SimplePlane = new PIXI.SimplePlane(PIXI.Texture.from("snake.png"), points); + * ``` + * @memberof PIXI + */ + var SimplePlane = /** @class */ (function (_super) { + __extends$1(SimplePlane, _super); + /** + * @param texture - The texture to use on the SimplePlane. + * @param verticesX - The number of vertices in the x-axis + * @param verticesY - The number of vertices in the y-axis + */ + function SimplePlane(texture, verticesX, verticesY) { + var _this = this; + var planeGeometry = new PlaneGeometry(texture.width, texture.height, verticesX, verticesY); + var meshMaterial = new MeshMaterial(Texture.WHITE); + _this = _super.call(this, planeGeometry, meshMaterial) || this; + // lets call the setter to ensure all necessary updates are performed + _this.texture = texture; + _this.autoResize = true; + return _this; + } + /** + * Method used for overrides, to do something in case texture frame was changed. + * Meshes based on plane can override it and change more details based on texture. + */ + SimplePlane.prototype.textureUpdated = function () { + this._textureID = this.shader.texture._updateID; + var geometry = this.geometry; + var _a = this.shader.texture, width = _a.width, height = _a.height; + if (this.autoResize && (geometry.width !== width || geometry.height !== height)) { + geometry.width = this.shader.texture.width; + geometry.height = this.shader.texture.height; + geometry.build(); + } + }; + Object.defineProperty(SimplePlane.prototype, "texture", { + get: function () { + return this.shader.texture; + }, + set: function (value) { + // Track texture same way sprite does. + // For generated meshes like NineSlicePlane it can change the geometry. + // Unfortunately, this method might not work if you directly change texture in material. + if (this.shader.texture === value) { + return; + } + this.shader.texture = value; + this._textureID = -1; + if (value.baseTexture.valid) { + this.textureUpdated(); + } + else { + value.once('update', this.textureUpdated, this); + } + }, + enumerable: false, + configurable: true + }); + SimplePlane.prototype._render = function (renderer) { + if (this._textureID !== this.shader.texture._updateID) { + this.textureUpdated(); + } + _super.prototype._render.call(this, renderer); + }; + SimplePlane.prototype.destroy = function (options) { + this.shader.texture.off('update', this.textureUpdated, this); + _super.prototype.destroy.call(this, options); + }; + return SimplePlane; + }(Mesh)); -if (typeof _deprecation2.default === 'function') { - (0, _deprecation2.default)(exports); -} + /** + * The Simple Mesh class mimics Mesh in PixiJS v4, providing easy-to-use constructor arguments. + * For more robust customization, use {@link PIXI.Mesh}. + * @memberof PIXI + */ + var SimpleMesh = /** @class */ (function (_super) { + __extends$1(SimpleMesh, _super); + /** + * @param texture - The texture to use + * @param {Float32Array} [vertices] - if you want to specify the vertices + * @param {Float32Array} [uvs] - if you want to specify the uvs + * @param {Uint16Array} [indices] - if you want to specify the indices + * @param drawMode - the drawMode, can be any of the Mesh.DRAW_MODES consts + */ + function SimpleMesh(texture, vertices, uvs, indices, drawMode) { + if (texture === void 0) { texture = Texture.EMPTY; } + var _this = this; + var geometry = new MeshGeometry(vertices, uvs, indices); + geometry.getBuffer('aVertexPosition').static = false; + var meshMaterial = new MeshMaterial(texture); + _this = _super.call(this, geometry, meshMaterial, null, drawMode) || this; + _this.autoUpdate = true; + return _this; + } + Object.defineProperty(SimpleMesh.prototype, "vertices", { + /** + * Collection of vertices data. + * @type {Float32Array} + */ + get: function () { + return this.geometry.getBuffer('aVertexPosition').data; + }, + set: function (value) { + this.geometry.getBuffer('aVertexPosition').data = value; + }, + enumerable: false, + configurable: true + }); + SimpleMesh.prototype._render = function (renderer) { + if (this.autoUpdate) { + this.geometry.getBuffer('aVertexPosition').update(); + } + _super.prototype._render.call(this, renderer); + }; + return SimpleMesh; + }(Mesh)); -// Always export PixiJS globally. -global.PIXI = exports; // eslint-disable-line + var DEFAULT_BORDER_SIZE = 10; + /** + * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful + * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically + * + *```js + * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.from('BoxWithRoundedCorners.png'), 15, 15, 15, 15); + * ``` + *
+   *      A                          B
+   *    +---+----------------------+---+
+   *  C | 1 |          2           | 3 |
+   *    +---+----------------------+---+
+   *    |   |                      |   |
+   *    | 4 |          5           | 6 |
+   *    |   |                      |   |
+   *    +---+----------------------+---+
+   *  D | 7 |          8           | 9 |
+   *    +---+----------------------+---+
+   *  When changing this objects width and/or height:
+   *     areas 1 3 7 and 9 will remain unscaled.
+   *     areas 2 and 8 will be stretched horizontally
+   *     areas 4 and 6 will be stretched vertically
+   *     area 5 will be stretched both horizontally and vertically
+   * 
+ * @memberof PIXI + */ + var NineSlicePlane = /** @class */ (function (_super) { + __extends$1(NineSlicePlane, _super); + /** + * @param texture - The texture to use on the NineSlicePlane. + * @param {number} [leftWidth=10] - size of the left vertical bar (A) + * @param {number} [topHeight=10] - size of the top horizontal bar (C) + * @param {number} [rightWidth=10] - size of the right vertical bar (B) + * @param {number} [bottomHeight=10] - size of the bottom horizontal bar (D) + */ + function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { + if (leftWidth === void 0) { leftWidth = DEFAULT_BORDER_SIZE; } + if (topHeight === void 0) { topHeight = DEFAULT_BORDER_SIZE; } + if (rightWidth === void 0) { rightWidth = DEFAULT_BORDER_SIZE; } + if (bottomHeight === void 0) { bottomHeight = DEFAULT_BORDER_SIZE; } + var _this = _super.call(this, Texture.WHITE, 4, 4) || this; + _this._origWidth = texture.orig.width; + _this._origHeight = texture.orig.height; + /** The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */ + _this._width = _this._origWidth; + /** The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */ + _this._height = _this._origHeight; + _this._leftWidth = leftWidth; + _this._rightWidth = rightWidth; + _this._topHeight = topHeight; + _this._bottomHeight = bottomHeight; + // lets call the setter to ensure all necessary updates are performed + _this.texture = texture; + return _this; + } + NineSlicePlane.prototype.textureUpdated = function () { + this._textureID = this.shader.texture._updateID; + this._refresh(); + }; + Object.defineProperty(NineSlicePlane.prototype, "vertices", { + get: function () { + return this.geometry.getBuffer('aVertexPosition').data; + }, + set: function (value) { + this.geometry.getBuffer('aVertexPosition').data = value; + }, + enumerable: false, + configurable: true + }); + /** Updates the horizontal vertices. */ + NineSlicePlane.prototype.updateHorizontalVertices = function () { + var vertices = this.vertices; + var scale = this._getMinScale(); + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight * scale; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - (this._bottomHeight * scale); + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; + }; + /** Updates the vertical vertices. */ + NineSlicePlane.prototype.updateVerticalVertices = function () { + var vertices = this.vertices; + var scale = this._getMinScale(); + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth * scale; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - (this._rightWidth * scale); + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; + }; + /** + * Returns the smaller of a set of vertical and horizontal scale of nine slice corners. + * @returns Smaller number of vertical and horizontal scale. + */ + NineSlicePlane.prototype._getMinScale = function () { + var w = this._leftWidth + this._rightWidth; + var scaleW = this._width > w ? 1.0 : this._width / w; + var h = this._topHeight + this._bottomHeight; + var scaleH = this._height > h ? 1.0 : this._height / h; + var scale = Math.min(scaleW, scaleH); + return scale; + }; + Object.defineProperty(NineSlicePlane.prototype, "width", { + /** The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */ + get: function () { + return this._width; + }, + set: function (value) { + this._width = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "height", { + /** The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */ + get: function () { + return this._height; + }, + set: function (value) { + this._height = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "leftWidth", { + /** The width of the left column. */ + get: function () { + return this._leftWidth; + }, + set: function (value) { + this._leftWidth = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "rightWidth", { + /** The width of the right column. */ + get: function () { + return this._rightWidth; + }, + set: function (value) { + this._rightWidth = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "topHeight", { + /** The height of the top row. */ + get: function () { + return this._topHeight; + }, + set: function (value) { + this._topHeight = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "bottomHeight", { + /** The height of the bottom row. */ + get: function () { + return this._bottomHeight; + }, + set: function (value) { + this._bottomHeight = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + /** Refreshes NineSlicePlane coords. All of them. */ + NineSlicePlane.prototype._refresh = function () { + var texture = this.texture; + var uvs = this.geometry.buffers[1].data; + this._origWidth = texture.orig.width; + this._origHeight = texture.orig.height; + var _uvw = 1.0 / this._origWidth; + var _uvh = 1.0 / this._origHeight; + uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0; + uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0; + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - (_uvw * this._rightWidth); + uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - (_uvh * this._bottomHeight); + this.updateHorizontalVertices(); + this.updateVerticalVertices(); + this.geometry.buffers[0].update(); + this.geometry.buffers[1].update(); + }; + return NineSlicePlane; + }(SimplePlane)); + + /*! + * @pixi/sprite-animated - v6.5.10 + * Compiled Thu, 06 Jul 2023 15:25:11 UTC + * + * @pixi/sprite-animated is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); + }; -},{"./accessibility":42,"./core":65,"./deprecation":130,"./extract":132,"./extras":141,"./filters":152,"./interaction":159,"./loaders":162,"./mesh":171,"./particles":174,"./polyfill":180,"./prepare":184}]},{},[188])(188) -}); + function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + /** + * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. + * + * ```js + * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; + * let textureArray = []; + * + * for (let i=0; i < 4; i++) + * { + * let texture = PIXI.Texture.from(alienImages[i]); + * textureArray.push(texture); + * }; + * + * let animatedSprite = new PIXI.AnimatedSprite(textureArray); + * ``` + * + * The more efficient and simpler way to create an animated sprite is using a {@link PIXI.Spritesheet} + * containing the animation definitions: + * + * ```js + * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet; + * animatedSprite = new PIXI.AnimatedSprite(sheet.animations["image_sequence"]); + * ... + * } + * ``` + * @memberof PIXI + */ + var AnimatedSprite = /** @class */ (function (_super) { + __extends(AnimatedSprite, _super); + /** + * @param textures - An array of {@link PIXI.Texture} or frame + * objects that make up the animation. + * @param {boolean} [autoUpdate=true] - Whether to use PIXI.Ticker.shared to auto update animation time. + */ + function AnimatedSprite(textures, autoUpdate) { + if (autoUpdate === void 0) { autoUpdate = true; } + var _this = _super.call(this, textures[0] instanceof Texture ? textures[0] : textures[0].texture) || this; + _this._textures = null; + _this._durations = null; + _this._autoUpdate = autoUpdate; + _this._isConnectedToTicker = false; + _this.animationSpeed = 1; + _this.loop = true; + _this.updateAnchor = false; + _this.onComplete = null; + _this.onFrameChange = null; + _this.onLoop = null; + _this._currentTime = 0; + _this._playing = false; + _this._previousFrame = null; + _this.textures = textures; + return _this; + } + /** Stops the AnimatedSprite. */ + AnimatedSprite.prototype.stop = function () { + if (!this._playing) { + return; + } + this._playing = false; + if (this._autoUpdate && this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + }; + /** Plays the AnimatedSprite. */ + AnimatedSprite.prototype.play = function () { + if (this._playing) { + return; + } + this._playing = true; + if (this._autoUpdate && !this._isConnectedToTicker) { + Ticker.shared.add(this.update, this, exports.UPDATE_PRIORITY.HIGH); + this._isConnectedToTicker = true; + } + }; + /** + * Stops the AnimatedSprite and goes to a specific frame. + * @param frameNumber - Frame index to stop at. + */ + AnimatedSprite.prototype.gotoAndStop = function (frameNumber) { + this.stop(); + var previousFrame = this.currentFrame; + this._currentTime = frameNumber; + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; + /** + * Goes to a specific frame and begins playing the AnimatedSprite. + * @param frameNumber - Frame index to start at. + */ + AnimatedSprite.prototype.gotoAndPlay = function (frameNumber) { + var previousFrame = this.currentFrame; + this._currentTime = frameNumber; + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + this.play(); + }; + /** + * Updates the object transform for rendering. + * @param deltaTime - Time since last tick. + */ + AnimatedSprite.prototype.update = function (deltaTime) { + if (!this._playing) { + return; + } + var elapsed = this.animationSpeed * deltaTime; + var previousFrame = this.currentFrame; + if (this._durations !== null) { + var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + lag += elapsed / 60 * 1000; + while (lag < 0) { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + var sign = Math.sign(this.animationSpeed * deltaTime); + this._currentTime = Math.floor(this._currentTime); + while (lag >= this._durations[this.currentFrame]) { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + this._currentTime += lag / this._durations[this.currentFrame]; + } + else { + this._currentTime += elapsed; + } + if (this._currentTime < 0 && !this.loop) { + this.gotoAndStop(0); + if (this.onComplete) { + this.onComplete(); + } + } + else if (this._currentTime >= this._textures.length && !this.loop) { + this.gotoAndStop(this._textures.length - 1); + if (this.onComplete) { + this.onComplete(); + } + } + else if (previousFrame !== this.currentFrame) { + if (this.loop && this.onLoop) { + if (this.animationSpeed > 0 && this.currentFrame < previousFrame) { + this.onLoop(); + } + else if (this.animationSpeed < 0 && this.currentFrame > previousFrame) { + this.onLoop(); + } + } + this.updateTexture(); + } + }; + /** Updates the displayed texture to match the current frame index. */ + AnimatedSprite.prototype.updateTexture = function () { + var currentFrame = this.currentFrame; + if (this._previousFrame === currentFrame) { + return; + } + this._previousFrame = currentFrame; + this._texture = this._textures[currentFrame]; + this._textureID = -1; + this._textureTrimmedID = -1; + this._cachedTint = 0xFFFFFF; + this.uvs = this._texture._uvs.uvsFloat32; + if (this.updateAnchor) { + this._anchor.copyFrom(this._texture.defaultAnchor); + } + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + }; + /** + * Stops the AnimatedSprite and destroys it. + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value. + * @param {boolean} [options.children=false] - If set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well. + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well. + */ + AnimatedSprite.prototype.destroy = function (options) { + this.stop(); + _super.prototype.destroy.call(this, options); + this.onComplete = null; + this.onFrameChange = null; + this.onLoop = null; + }; + /** + * A short hand way of creating an AnimatedSprite from an array of frame ids. + * @param frames - The array of frames ids the AnimatedSprite will use as its texture frames. + * @returns - The new animated sprite with the specified frames. + */ + AnimatedSprite.fromFrames = function (frames) { + var textures = []; + for (var i = 0; i < frames.length; ++i) { + textures.push(Texture.from(frames[i])); + } + return new AnimatedSprite(textures); + }; + /** + * A short hand way of creating an AnimatedSprite from an array of image ids. + * @param images - The array of image urls the AnimatedSprite will use as its texture frames. + * @returns The new animate sprite with the specified images as frames. + */ + AnimatedSprite.fromImages = function (images) { + var textures = []; + for (var i = 0; i < images.length; ++i) { + textures.push(Texture.from(images[i])); + } + return new AnimatedSprite(textures); + }; + Object.defineProperty(AnimatedSprite.prototype, "totalFrames", { + /** + * The total number of frames in the AnimatedSprite. This is the same as number of textures + * assigned to the AnimatedSprite. + * @readonly + * @default 0 + */ + get: function () { + return this._textures.length; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AnimatedSprite.prototype, "textures", { + /** The array of textures used for this AnimatedSprite. */ + get: function () { + return this._textures; + }, + set: function (value) { + if (value[0] instanceof Texture) { + this._textures = value; + this._durations = null; + } + else { + this._textures = []; + this._durations = []; + for (var i = 0; i < value.length; i++) { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + this._previousFrame = null; + this.gotoAndStop(0); + this.updateTexture(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AnimatedSprite.prototype, "currentFrame", { + /** + * The AnimatedSprites current frame index. + * @readonly + */ + get: function () { + var currentFrame = Math.floor(this._currentTime) % this._textures.length; + if (currentFrame < 0) { + currentFrame += this._textures.length; + } + return currentFrame; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AnimatedSprite.prototype, "playing", { + /** + * Indicates if the AnimatedSprite is currently playing. + * @readonly + */ + get: function () { + return this._playing; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AnimatedSprite.prototype, "autoUpdate", { + /** Whether to use PIXI.Ticker.shared to auto update animation time. */ + get: function () { + return this._autoUpdate; + }, + set: function (value) { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + if (!this._autoUpdate && this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + else if (this._autoUpdate && !this._isConnectedToTicker && this._playing) { + Ticker.shared.add(this.update, this); + this._isConnectedToTicker = true; + } + } + }, + enumerable: false, + configurable: true + }); + return AnimatedSprite; + }(Sprite)); + + extensions.add( + // Install renderer plugins + AccessibilityManager, Extract, InteractionManager, ParticleRenderer, Prepare, BatchRenderer, TilingSpriteRenderer, + // Install loader plugins + BitmapFontLoader, CompressedTextureLoader, DDSLoader, KTXLoader, SpritesheetLoader, + // Install application plugins + TickerPlugin, AppLoaderPlugin); + /** + * This namespace contains WebGL-only display filters that can be applied + * to DisplayObjects using the {@link PIXI.DisplayObject#filters filters} property. + * + * Since PixiJS only had a handful of built-in filters, additional filters + * can be downloaded {@link https://github.com/pixijs/pixi-filters here} from the + * PixiJS Filters repository. + * + * All filters must extend {@link PIXI.Filter}. + * @example + * // Create a new application + * const app = new PIXI.Application(); + * + * // Draw a green rectangle + * const rect = new PIXI.Graphics() + * .beginFill(0x00ff00) + * .drawRect(40, 40, 200, 200); + * + * // Add a blur filter + * rect.filters = [new PIXI.filters.BlurFilter()]; + * + * // Display rectangle + * app.stage.addChild(rect); + * document.body.appendChild(app.view); + * @namespace PIXI.filters + */ + var filters = { + AlphaFilter: AlphaFilter, + BlurFilter: BlurFilter, + BlurFilterPass: BlurFilterPass, + ColorMatrixFilter: ColorMatrixFilter, + DisplacementFilter: DisplacementFilter, + FXAAFilter: FXAAFilter, + NoiseFilter: NoiseFilter, + }; + exports.AbstractBatchRenderer = AbstractBatchRenderer; + exports.AbstractMultiResource = AbstractMultiResource; + exports.AbstractRenderer = AbstractRenderer; + exports.AccessibilityManager = AccessibilityManager; + exports.AnimatedSprite = AnimatedSprite; + exports.AppLoaderPlugin = AppLoaderPlugin; + exports.Application = Application; + exports.ArrayResource = ArrayResource; + exports.Attribute = Attribute; + exports.BaseImageResource = BaseImageResource; + exports.BasePrepare = BasePrepare; + exports.BaseRenderTexture = BaseRenderTexture; + exports.BaseTexture = BaseTexture; + exports.BatchDrawCall = BatchDrawCall; + exports.BatchGeometry = BatchGeometry; + exports.BatchPluginFactory = BatchPluginFactory; + exports.BatchRenderer = BatchRenderer; + exports.BatchShaderGenerator = BatchShaderGenerator; + exports.BatchSystem = BatchSystem; + exports.BatchTextureArray = BatchTextureArray; + exports.BitmapFont = BitmapFont; + exports.BitmapFontData = BitmapFontData; + exports.BitmapFontLoader = BitmapFontLoader; + exports.BitmapText = BitmapText; + exports.BlobResource = BlobResource; + exports.Bounds = Bounds; + exports.BrowserAdapter = BrowserAdapter; + exports.Buffer = Buffer; + exports.BufferResource = BufferResource; + exports.CanvasResource = CanvasResource; + exports.Circle = Circle; + exports.CompressedTextureLoader = CompressedTextureLoader; + exports.CompressedTextureResource = CompressedTextureResource; + exports.Container = Container; + exports.ContextSystem = ContextSystem; + exports.CountLimiter = CountLimiter; + exports.CubeResource = CubeResource; + exports.DDSLoader = DDSLoader; + exports.DEG_TO_RAD = DEG_TO_RAD; + exports.DisplayObject = DisplayObject; + exports.Ellipse = Ellipse; + exports.Extract = Extract; + exports.FORMATS_TO_COMPONENTS = FORMATS_TO_COMPONENTS; + exports.FillStyle = FillStyle; + exports.Filter = Filter; + exports.FilterState = FilterState; + exports.FilterSystem = FilterSystem; + exports.Framebuffer = Framebuffer; + exports.FramebufferSystem = FramebufferSystem; + exports.GLFramebuffer = GLFramebuffer; + exports.GLProgram = GLProgram; + exports.GLTexture = GLTexture; + exports.GRAPHICS_CURVES = GRAPHICS_CURVES; + exports.Geometry = Geometry; + exports.GeometrySystem = GeometrySystem; + exports.Graphics = Graphics; + exports.GraphicsData = GraphicsData; + exports.GraphicsGeometry = GraphicsGeometry; + exports.IGLUniformData = IGLUniformData; + exports.INSTALLED = INSTALLED; + exports.INTERNAL_FORMAT_TO_BYTES_PER_PIXEL = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL; + exports.ImageBitmapResource = ImageBitmapResource; + exports.ImageResource = ImageResource; + exports.InteractionData = InteractionData; + exports.InteractionEvent = InteractionEvent; + exports.InteractionManager = InteractionManager; + exports.InteractionTrackingData = InteractionTrackingData; + exports.KTXLoader = KTXLoader; + exports.LineStyle = LineStyle; + exports.Loader = Loader; + exports.MaskData = MaskData; + exports.MaskSystem = MaskSystem; + exports.Matrix = Matrix; + exports.Mesh = Mesh; + exports.MeshBatchUvs = MeshBatchUvs; + exports.MeshGeometry = MeshGeometry; + exports.MeshMaterial = MeshMaterial; + exports.NineSlicePlane = NineSlicePlane; + exports.ObjectRenderer = ObjectRenderer; + exports.ObservablePoint = ObservablePoint; + exports.PI_2 = PI_2; + exports.ParticleContainer = ParticleContainer; + exports.ParticleRenderer = ParticleRenderer; + exports.PlaneGeometry = PlaneGeometry; + exports.Point = Point; + exports.Polygon = Polygon; + exports.Prepare = Prepare; + exports.Program = Program; + exports.ProjectionSystem = ProjectionSystem; + exports.Quad = Quad; + exports.QuadUv = QuadUv; + exports.RAD_TO_DEG = RAD_TO_DEG; + exports.Rectangle = Rectangle; + exports.RenderTexture = RenderTexture; + exports.RenderTexturePool = RenderTexturePool; + exports.RenderTextureSystem = RenderTextureSystem; + exports.Renderer = Renderer; + exports.ResizePlugin = ResizePlugin; + exports.Resource = Resource; + exports.RopeGeometry = RopeGeometry; + exports.RoundedRectangle = RoundedRectangle; + exports.Runner = Runner; + exports.SVGResource = SVGResource; + exports.ScissorSystem = ScissorSystem; + exports.Shader = Shader; + exports.ShaderSystem = ShaderSystem; + exports.SimpleMesh = SimpleMesh; + exports.SimplePlane = SimplePlane; + exports.SimpleRope = SimpleRope; + exports.Sprite = Sprite; + exports.SpriteMaskFilter = SpriteMaskFilter; + exports.Spritesheet = Spritesheet; + exports.SpritesheetLoader = SpritesheetLoader; + exports.State = State; + exports.StateSystem = StateSystem; + exports.StencilSystem = StencilSystem; + exports.System = System; + exports.TYPES_TO_BYTES_PER_COMPONENT = TYPES_TO_BYTES_PER_COMPONENT; + exports.TYPES_TO_BYTES_PER_PIXEL = TYPES_TO_BYTES_PER_PIXEL; + exports.TemporaryDisplayObject = TemporaryDisplayObject; + exports.Text = Text; + exports.TextFormat = TextFormat; + exports.TextMetrics = TextMetrics; + exports.TextStyle = TextStyle; + exports.Texture = Texture; + exports.TextureGCSystem = TextureGCSystem; + exports.TextureLoader = TextureLoader; + exports.TextureMatrix = TextureMatrix; + exports.TextureSystem = TextureSystem; + exports.TextureUvs = TextureUvs; + exports.Ticker = Ticker; + exports.TickerPlugin = TickerPlugin; + exports.TilingSprite = TilingSprite; + exports.TilingSpriteRenderer = TilingSpriteRenderer; + exports.TimeLimiter = TimeLimiter; + exports.Transform = Transform; + exports.UniformGroup = UniformGroup; + exports.VERSION = VERSION; + exports.VideoResource = VideoResource; + exports.ViewableBuffer = ViewableBuffer; + exports.XMLFormat = XMLFormat; + exports.XMLStringFormat = XMLStringFormat; + exports.accessibleTarget = accessibleTarget; + exports.autoDetectFormat = autoDetectFormat; + exports.autoDetectRenderer = autoDetectRenderer; + exports.autoDetectResource = autoDetectResource; + exports.checkMaxIfStatementsInShader = checkMaxIfStatementsInShader; + exports.createUBOElements = createUBOElements; + exports.defaultFilterVertex = defaultFilterVertex; + exports.defaultVertex = defaultVertex$1; + exports.extensions = extensions; + exports.filters = filters; + exports.generateProgram = generateProgram; + exports.generateUniformBufferSync = generateUniformBufferSync; + exports.getTestContext = getTestContext; + exports.getUBOData = getUBOData; + exports.graphicsUtils = graphicsUtils; + exports.groupD8 = groupD8; + exports.interactiveTarget = interactiveTarget; + exports.isMobile = isMobile; + exports.parseDDS = parseDDS; + exports.parseKTX = parseKTX; + exports.resources = resources; + exports.settings = settings; + exports.systems = systems; + exports.uniformParsers = uniformParsers; + exports.utils = utils; + + Object.defineProperty(exports, '__esModule', { value: true }); + + return exports; + +})({}); //# sourceMappingURL=pixi.js.map From 5a3733ce85c61f28b4e78066d45383ab5a788ce1 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Wed, 23 Aug 2023 13:58:26 -0500 Subject: [PATCH 062/188] Scope: pixi fixed initialisation for v6 (this is still backwards compatible) --- IDE/frontend-dev/scope-src/scope-browser.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/IDE/frontend-dev/scope-src/scope-browser.js b/IDE/frontend-dev/scope-src/scope-browser.js index b2fda3978..59ba4d6f8 100644 --- a/IDE/frontend-dev/scope-src/scope-browser.js +++ b/IDE/frontend-dev/scope-src/scope-browser.js @@ -21,7 +21,11 @@ var Model = require('./Model'); var settings = new Model(); // Pixi.js renderer and stage -var renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight, {transparent: true}); +var renderer = PIXI.autoDetectRenderer({ + width: window.innerWidth, + heigh: window.innerHeight, + transparent: true, +}); renderer.view.style.position = "absolute"; renderer.view.style.display = "block"; renderer.autoResize = true; From 7aca8a5913a6e3f37489912ec057a66c89027bd1 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Wed, 23 Aug 2023 14:08:05 -0500 Subject: [PATCH 063/188] frontend-dev: do not exit on scope-browserify error. Also re-enable livereload --- IDE/frontend-dev/gulpfile.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/IDE/frontend-dev/gulpfile.js b/IDE/frontend-dev/gulpfile.js index 090103833..cf071fe81 100644 --- a/IDE/frontend-dev/gulpfile.js +++ b/IDE/frontend-dev/gulpfile.js @@ -132,7 +132,6 @@ gulp.task('scope-browserify', () => { .on('error', function(error){ console.error(error); this.emit('end'); - exit(1); }) .pipe(source('bundle.js')) .pipe(buffer()) @@ -150,7 +149,7 @@ gulp.task('sass', () => { }); gulp.task('watch-local', () => { - //livereload.listen(); + livereload.listen(); // when the browser js changes, browserify it gulp.watch(['./src/**'], ['browserify']); // when the scope browser js changes, browserify it From 4face1c3ebdcb49b993d6ec8c9a8ff3fa0bae4a0 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Wed, 23 Aug 2023 14:08:40 -0500 Subject: [PATCH 064/188] Scope: antialias --- IDE/frontend-dev/scope-src/scope-browser.js | 3 +++ IDE/public/scope/js/bundle.js | 9 ++++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/IDE/frontend-dev/scope-src/scope-browser.js b/IDE/frontend-dev/scope-src/scope-browser.js index 59ba4d6f8..4ee8aa067 100644 --- a/IDE/frontend-dev/scope-src/scope-browser.js +++ b/IDE/frontend-dev/scope-src/scope-browser.js @@ -25,6 +25,9 @@ var renderer = PIXI.autoDetectRenderer({ width: window.innerWidth, heigh: window.innerHeight, transparent: true, + antialias: true, + autoDensity: true, // somehow makes CSS compensate for increased resolution. Not sure it's needed for us + //resolution: 2, // sort of oversampling for antialias }); renderer.view.style.position = "absolute"; renderer.view.style.display = "block"; diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index 4bd9b9f91..8e14fbf76 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -1391,7 +1391,14 @@ var Model = require('./Model'); var settings = new Model(); // Pixi.js renderer and stage -var renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight, { transparent: true }); +var renderer = PIXI.autoDetectRenderer({ + width: window.innerWidth, + heigh: window.innerHeight, + transparent: true, + antialias: true, + autoDensity: true // somehow makes CSS compensate for increased resolution. Not sure it's needed for us + //resolution: 2, // sort of oversampling for antialias +}); renderer.view.style.position = "absolute"; renderer.view.style.display = "block"; renderer.autoResize = true; From e7e929cec63ad1358e27f63c3964b18bce528c30 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Wed, 23 Aug 2023 14:09:01 -0500 Subject: [PATCH 065/188] Scope: added (disabled) load test that doesn't require a Bela program to be running --- IDE/public/scope/js/scope-worker.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/IDE/public/scope/js/scope-worker.js b/IDE/public/scope/js/scope-worker.js index 6d36b06c7..ce15bc7de 100644 --- a/IDE/public/scope/js/scope-worker.js +++ b/IDE/public/scope/js/scope-worker.js @@ -157,3 +157,26 @@ var ws_onmessage = function(ws, e){ }, [outArray.buffer]); }; + +// load test +/* +let testArray = new Float32Array(0); +let testPtr = 0; +setInterval(() => { + if(testArray.length != outArrayWidth) { + testArray = new Float32Array(outArrayWidth); + for(let n = 0; n < outFrameWidth ; ++n) { + for(let c = 0; c < numChannels ; ++c) { + testArray[c * outFrameWidth + n] = (n + testPtr) / outFrameWidth* 150 + c * 150; + } + } + testPtr += 10; + if(testPtr >= outFrameWidth) + testPtr = 0; + } + postMessage({ + outArray: testArray, + oldDataSeparator: -1, + }, [testArray.buffer]); +}, 20); +//*/ From 469957c22e5e93c16950bbee09aecf153daa3c4b Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 24 Aug 2023 11:18:03 -0500 Subject: [PATCH 066/188] Scope: allow to disable individual websockets with controlDisabled= and dataDisabled= --- IDE/frontend-dev/scope-src/scope-browser.js | 22 ++++++++++++--------- IDE/public/scope/js/bundle.js | 22 ++++++++++++--------- 2 files changed, 26 insertions(+), 18 deletions(-) diff --git a/IDE/frontend-dev/scope-src/scope-browser.js b/IDE/frontend-dev/scope-src/scope-browser.js index 4ee8aa067..50aa19355 100644 --- a/IDE/frontend-dev/scope-src/scope-browser.js +++ b/IDE/frontend-dev/scope-src/scope-browser.js @@ -4,12 +4,13 @@ let remoteHost = location.hostname + ":5432"; let qs = new URLSearchParams(location.search); let qsRemoteHost = qs.get("remoteHost"); -let qsControlOnly = qs.get("controlOnly"); +let controlDisabled = qs.get("controlDisabled"); +let dataDisabled = qs.get("dataDisabled"); if(qsRemoteHost) remoteHost = qsRemoteHost var wsRemote = "ws://" + remoteHost + "/"; var worker = new Worker("js/scope-worker.js"); -if(!qsControlOnly) { +if(!dataDisabled) { worker.postMessage({ event: 'wsConnect', remote: wsRemote, @@ -87,7 +88,7 @@ var ws_onmessage = function(msg){ console.log('could not stringify settings:', e); return; } - if (ws.readyState === 1) ws.send(out); + if (ws && ws.readyState === 1) ws.send(out); } else if (data.event == 'set-slider'){ sliderView.emit('set-slider', data); } else if (data.event == 'set-setting'){ @@ -102,10 +103,13 @@ function setWsCbs(ws) { ws.onmessage = ws_onmessage; } -// scope websocket let wsUrl = wsRemote + "scope_control"; -var ws = new WebSocket(wsUrl); -setWsCbs(ws); +// scope websocket +let ws; +if(!controlDisabled) { + ws = new WebSocket(wsUrl); + setWsCbs(ws); +} var paused = false, oneShot = false; @@ -141,7 +145,7 @@ controlView.on('settings-event', (key, value) => { console.log('error creating settings JSON', e); return; } - if (ws.readyState === 1) ws.send(out); + if (ws && ws.readyState === 1) ws.send(out); settings.setKey(key, value); }); @@ -196,7 +200,7 @@ sliderView.on('slider-value', (slider, value) => { console.log('could not stringify slider json:', e); return; } - if (ws.readyState === 1) ws.send(out) + if (ws && ws.readyState === 1) ws.send(out) }); belaSocket.on('cpu-usage', CPU); @@ -214,7 +218,7 @@ settings.on('set', (data, changedKeys) => { console.log('unable to stringify framewidth', e); return; } - if (ws.readyState === 1) ws.send(out); + if (ws && ws.readyState === 1) ws.send(out); } else { worker.postMessage({ event : 'settings', diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index 8e14fbf76..48c78aa2b 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -1375,11 +1375,12 @@ function _defineProperty(obj, key, value) { if (key in obj) { Object.definePrope var remoteHost = location.hostname + ":5432"; var qs = new URLSearchParams(location.search); var qsRemoteHost = qs.get("remoteHost"); -var qsControlOnly = qs.get("controlOnly"); +var controlDisabled = qs.get("controlDisabled"); +var dataDisabled = qs.get("dataDisabled"); if (qsRemoteHost) remoteHost = qsRemoteHost; var wsRemote = "ws://" + remoteHost + "/"; var worker = new Worker("js/scope-worker.js"); -if (!qsControlOnly) { +if (!dataDisabled) { worker.postMessage({ event: 'wsConnect', remote: wsRemote @@ -1454,7 +1455,7 @@ var ws_onmessage = function ws_onmessage(msg) { console.log('could not stringify settings:', e); return; } - if (ws.readyState === 1) ws.send(out); + if (ws && ws.readyState === 1) ws.send(out); } else if (data.event == 'set-slider') { sliderView.emit('set-slider', data); } else if (data.event == 'set-setting') { @@ -1469,10 +1470,13 @@ function setWsCbs(ws) { ws.onmessage = ws_onmessage; } -// scope websocket var wsUrl = wsRemote + "scope_control"; -var ws = new WebSocket(wsUrl); -setWsCbs(ws); +// scope websocket +var ws = void 0; +if (!controlDisabled) { + ws = new WebSocket(wsUrl); + setWsCbs(ws); +} var paused = false, oneShot = false; @@ -1508,7 +1512,7 @@ controlView.on('settings-event', function (key, value) { console.log('error creating settings JSON', e); return; } - if (ws.readyState === 1) ws.send(out); + if (ws && ws.readyState === 1) ws.send(out); settings.setKey(key, value); }); @@ -1561,7 +1565,7 @@ sliderView.on('slider-value', function (slider, value) { console.log('could not stringify slider json:', e); return; } - if (ws.readyState === 1) ws.send(out); + if (ws && ws.readyState === 1) ws.send(out); }); belaSocket.on('cpu-usage', CPU); @@ -1578,7 +1582,7 @@ settings.on('set', function (data, changedKeys) { console.log('unable to stringify framewidth', e); return; } - if (ws.readyState === 1) ws.send(out); + if (ws && ws.readyState === 1) ws.send(out); } else { worker.postMessage({ event: 'settings', From a045e6c12d05d53a8ff1d4e137839a833bea9575 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 24 Aug 2023 14:07:50 -0500 Subject: [PATCH 067/188] Scope: pixi-legacy v7.2.4 --- IDE/frontend-dev/scope-src/scope-browser.js | 2 +- IDE/public/scope/js/bundle.js | 2 +- IDE/public/scope/js/pixi-legacy.js | 27334 ++++++++++++ IDE/public/scope/js/pixi.js | 38831 ------------------ 4 files changed, 27336 insertions(+), 38833 deletions(-) create mode 100644 IDE/public/scope/js/pixi-legacy.js delete mode 100644 IDE/public/scope/js/pixi.js diff --git a/IDE/frontend-dev/scope-src/scope-browser.js b/IDE/frontend-dev/scope-src/scope-browser.js index 50aa19355..0a45973eb 100644 --- a/IDE/frontend-dev/scope-src/scope-browser.js +++ b/IDE/frontend-dev/scope-src/scope-browser.js @@ -25,7 +25,7 @@ var settings = new Model(); var renderer = PIXI.autoDetectRenderer({ width: window.innerWidth, heigh: window.innerHeight, - transparent: true, + backgroundAlpha: 0, antialias: true, autoDensity: true, // somehow makes CSS compensate for increased resolution. Not sure it's needed for us //resolution: 2, // sort of oversampling for antialias diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index 48c78aa2b..fe6397e30 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -1395,7 +1395,7 @@ var settings = new Model(); var renderer = PIXI.autoDetectRenderer({ width: window.innerWidth, heigh: window.innerHeight, - transparent: true, + backgroundAlpha: 0, antialias: true, autoDensity: true // somehow makes CSS compensate for increased resolution. Not sure it's needed for us //resolution: 2, // sort of oversampling for antialias diff --git a/IDE/public/scope/js/pixi-legacy.js b/IDE/public/scope/js/pixi-legacy.js new file mode 100644 index 000000000..01566f9bd --- /dev/null +++ b/IDE/public/scope/js/pixi-legacy.js @@ -0,0 +1,27334 @@ +/*! + * pixi.js-legacy - v7.2.4 + * Compiled Thu, 06 Apr 2023 19:36:45 UTC + * + * pixi.js-legacy is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +var PIXI = (function (exports) { + 'use strict'; + + var ENV = /* @__PURE__ */ ((ENV2) => { + ENV2[ENV2["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; + ENV2[ENV2["WEBGL"] = 1] = "WEBGL"; + ENV2[ENV2["WEBGL2"] = 2] = "WEBGL2"; + return ENV2; + })(ENV || {}); + var RENDERER_TYPE = /* @__PURE__ */ ((RENDERER_TYPE2) => { + RENDERER_TYPE2[RENDERER_TYPE2["UNKNOWN"] = 0] = "UNKNOWN"; + RENDERER_TYPE2[RENDERER_TYPE2["WEBGL"] = 1] = "WEBGL"; + RENDERER_TYPE2[RENDERER_TYPE2["CANVAS"] = 2] = "CANVAS"; + return RENDERER_TYPE2; + })(RENDERER_TYPE || {}); + var BUFFER_BITS = /* @__PURE__ */ ((BUFFER_BITS2) => { + BUFFER_BITS2[BUFFER_BITS2["COLOR"] = 16384] = "COLOR"; + BUFFER_BITS2[BUFFER_BITS2["DEPTH"] = 256] = "DEPTH"; + BUFFER_BITS2[BUFFER_BITS2["STENCIL"] = 1024] = "STENCIL"; + return BUFFER_BITS2; + })(BUFFER_BITS || {}); + var BLEND_MODES = /* @__PURE__ */ ((BLEND_MODES2) => { + BLEND_MODES2[BLEND_MODES2["NORMAL"] = 0] = "NORMAL"; + BLEND_MODES2[BLEND_MODES2["ADD"] = 1] = "ADD"; + BLEND_MODES2[BLEND_MODES2["MULTIPLY"] = 2] = "MULTIPLY"; + BLEND_MODES2[BLEND_MODES2["SCREEN"] = 3] = "SCREEN"; + BLEND_MODES2[BLEND_MODES2["OVERLAY"] = 4] = "OVERLAY"; + BLEND_MODES2[BLEND_MODES2["DARKEN"] = 5] = "DARKEN"; + BLEND_MODES2[BLEND_MODES2["LIGHTEN"] = 6] = "LIGHTEN"; + BLEND_MODES2[BLEND_MODES2["COLOR_DODGE"] = 7] = "COLOR_DODGE"; + BLEND_MODES2[BLEND_MODES2["COLOR_BURN"] = 8] = "COLOR_BURN"; + BLEND_MODES2[BLEND_MODES2["HARD_LIGHT"] = 9] = "HARD_LIGHT"; + BLEND_MODES2[BLEND_MODES2["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; + BLEND_MODES2[BLEND_MODES2["DIFFERENCE"] = 11] = "DIFFERENCE"; + BLEND_MODES2[BLEND_MODES2["EXCLUSION"] = 12] = "EXCLUSION"; + BLEND_MODES2[BLEND_MODES2["HUE"] = 13] = "HUE"; + BLEND_MODES2[BLEND_MODES2["SATURATION"] = 14] = "SATURATION"; + BLEND_MODES2[BLEND_MODES2["COLOR"] = 15] = "COLOR"; + BLEND_MODES2[BLEND_MODES2["LUMINOSITY"] = 16] = "LUMINOSITY"; + BLEND_MODES2[BLEND_MODES2["NORMAL_NPM"] = 17] = "NORMAL_NPM"; + BLEND_MODES2[BLEND_MODES2["ADD_NPM"] = 18] = "ADD_NPM"; + BLEND_MODES2[BLEND_MODES2["SCREEN_NPM"] = 19] = "SCREEN_NPM"; + BLEND_MODES2[BLEND_MODES2["NONE"] = 20] = "NONE"; + BLEND_MODES2[BLEND_MODES2["SRC_OVER"] = 0] = "SRC_OVER"; + BLEND_MODES2[BLEND_MODES2["SRC_IN"] = 21] = "SRC_IN"; + BLEND_MODES2[BLEND_MODES2["SRC_OUT"] = 22] = "SRC_OUT"; + BLEND_MODES2[BLEND_MODES2["SRC_ATOP"] = 23] = "SRC_ATOP"; + BLEND_MODES2[BLEND_MODES2["DST_OVER"] = 24] = "DST_OVER"; + BLEND_MODES2[BLEND_MODES2["DST_IN"] = 25] = "DST_IN"; + BLEND_MODES2[BLEND_MODES2["DST_OUT"] = 26] = "DST_OUT"; + BLEND_MODES2[BLEND_MODES2["DST_ATOP"] = 27] = "DST_ATOP"; + BLEND_MODES2[BLEND_MODES2["ERASE"] = 26] = "ERASE"; + BLEND_MODES2[BLEND_MODES2["SUBTRACT"] = 28] = "SUBTRACT"; + BLEND_MODES2[BLEND_MODES2["XOR"] = 29] = "XOR"; + return BLEND_MODES2; + })(BLEND_MODES || {}); + var DRAW_MODES = /* @__PURE__ */ ((DRAW_MODES2) => { + DRAW_MODES2[DRAW_MODES2["POINTS"] = 0] = "POINTS"; + DRAW_MODES2[DRAW_MODES2["LINES"] = 1] = "LINES"; + DRAW_MODES2[DRAW_MODES2["LINE_LOOP"] = 2] = "LINE_LOOP"; + DRAW_MODES2[DRAW_MODES2["LINE_STRIP"] = 3] = "LINE_STRIP"; + DRAW_MODES2[DRAW_MODES2["TRIANGLES"] = 4] = "TRIANGLES"; + DRAW_MODES2[DRAW_MODES2["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; + DRAW_MODES2[DRAW_MODES2["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; + return DRAW_MODES2; + })(DRAW_MODES || {}); + var FORMATS = /* @__PURE__ */ ((FORMATS2) => { + FORMATS2[FORMATS2["RGBA"] = 6408] = "RGBA"; + FORMATS2[FORMATS2["RGB"] = 6407] = "RGB"; + FORMATS2[FORMATS2["RG"] = 33319] = "RG"; + FORMATS2[FORMATS2["RED"] = 6403] = "RED"; + FORMATS2[FORMATS2["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER"; + FORMATS2[FORMATS2["RGB_INTEGER"] = 36248] = "RGB_INTEGER"; + FORMATS2[FORMATS2["RG_INTEGER"] = 33320] = "RG_INTEGER"; + FORMATS2[FORMATS2["RED_INTEGER"] = 36244] = "RED_INTEGER"; + FORMATS2[FORMATS2["ALPHA"] = 6406] = "ALPHA"; + FORMATS2[FORMATS2["LUMINANCE"] = 6409] = "LUMINANCE"; + FORMATS2[FORMATS2["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; + FORMATS2[FORMATS2["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; + FORMATS2[FORMATS2["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; + return FORMATS2; + })(FORMATS || {}); + var TARGETS = /* @__PURE__ */ ((TARGETS2) => { + TARGETS2[TARGETS2["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; + TARGETS2[TARGETS2["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; + TARGETS2[TARGETS2["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; + TARGETS2[TARGETS2["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; + TARGETS2[TARGETS2["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; + TARGETS2[TARGETS2["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; + TARGETS2[TARGETS2["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; + TARGETS2[TARGETS2["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; + TARGETS2[TARGETS2["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; + return TARGETS2; + })(TARGETS || {}); + var TYPES = /* @__PURE__ */ ((TYPES2) => { + TYPES2[TYPES2["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + TYPES2[TYPES2["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + TYPES2[TYPES2["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; + TYPES2[TYPES2["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; + TYPES2[TYPES2["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; + TYPES2[TYPES2["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; + TYPES2[TYPES2["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV"; + TYPES2[TYPES2["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV"; + TYPES2[TYPES2["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8"; + TYPES2[TYPES2["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV"; + TYPES2[TYPES2["BYTE"] = 5120] = "BYTE"; + TYPES2[TYPES2["SHORT"] = 5122] = "SHORT"; + TYPES2[TYPES2["INT"] = 5124] = "INT"; + TYPES2[TYPES2["FLOAT"] = 5126] = "FLOAT"; + TYPES2[TYPES2["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV"; + TYPES2[TYPES2["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; + return TYPES2; + })(TYPES || {}); + var SAMPLER_TYPES = /* @__PURE__ */ ((SAMPLER_TYPES2) => { + SAMPLER_TYPES2[SAMPLER_TYPES2["FLOAT"] = 0] = "FLOAT"; + SAMPLER_TYPES2[SAMPLER_TYPES2["INT"] = 1] = "INT"; + SAMPLER_TYPES2[SAMPLER_TYPES2["UINT"] = 2] = "UINT"; + return SAMPLER_TYPES2; + })(SAMPLER_TYPES || {}); + var SCALE_MODES = /* @__PURE__ */ ((SCALE_MODES2) => { + SCALE_MODES2[SCALE_MODES2["NEAREST"] = 0] = "NEAREST"; + SCALE_MODES2[SCALE_MODES2["LINEAR"] = 1] = "LINEAR"; + return SCALE_MODES2; + })(SCALE_MODES || {}); + var WRAP_MODES = /* @__PURE__ */ ((WRAP_MODES2) => { + WRAP_MODES2[WRAP_MODES2["CLAMP"] = 33071] = "CLAMP"; + WRAP_MODES2[WRAP_MODES2["REPEAT"] = 10497] = "REPEAT"; + WRAP_MODES2[WRAP_MODES2["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; + return WRAP_MODES2; + })(WRAP_MODES || {}); + var MIPMAP_MODES = /* @__PURE__ */ ((MIPMAP_MODES2) => { + MIPMAP_MODES2[MIPMAP_MODES2["OFF"] = 0] = "OFF"; + MIPMAP_MODES2[MIPMAP_MODES2["POW2"] = 1] = "POW2"; + MIPMAP_MODES2[MIPMAP_MODES2["ON"] = 2] = "ON"; + MIPMAP_MODES2[MIPMAP_MODES2["ON_MANUAL"] = 3] = "ON_MANUAL"; + return MIPMAP_MODES2; + })(MIPMAP_MODES || {}); + var ALPHA_MODES = /* @__PURE__ */ ((ALPHA_MODES2) => { + ALPHA_MODES2[ALPHA_MODES2["NPM"] = 0] = "NPM"; + ALPHA_MODES2[ALPHA_MODES2["UNPACK"] = 1] = "UNPACK"; + ALPHA_MODES2[ALPHA_MODES2["PMA"] = 2] = "PMA"; + ALPHA_MODES2[ALPHA_MODES2["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; + ALPHA_MODES2[ALPHA_MODES2["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; + ALPHA_MODES2[ALPHA_MODES2["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA"; + return ALPHA_MODES2; + })(ALPHA_MODES || {}); + var CLEAR_MODES = /* @__PURE__ */ ((CLEAR_MODES2) => { + CLEAR_MODES2[CLEAR_MODES2["NO"] = 0] = "NO"; + CLEAR_MODES2[CLEAR_MODES2["YES"] = 1] = "YES"; + CLEAR_MODES2[CLEAR_MODES2["AUTO"] = 2] = "AUTO"; + CLEAR_MODES2[CLEAR_MODES2["BLEND"] = 0] = "BLEND"; + CLEAR_MODES2[CLEAR_MODES2["CLEAR"] = 1] = "CLEAR"; + CLEAR_MODES2[CLEAR_MODES2["BLIT"] = 2] = "BLIT"; + return CLEAR_MODES2; + })(CLEAR_MODES || {}); + var GC_MODES = /* @__PURE__ */ ((GC_MODES2) => { + GC_MODES2[GC_MODES2["AUTO"] = 0] = "AUTO"; + GC_MODES2[GC_MODES2["MANUAL"] = 1] = "MANUAL"; + return GC_MODES2; + })(GC_MODES || {}); + var PRECISION = /* @__PURE__ */ ((PRECISION2) => { + PRECISION2["LOW"] = "lowp"; + PRECISION2["MEDIUM"] = "mediump"; + PRECISION2["HIGH"] = "highp"; + return PRECISION2; + })(PRECISION || {}); + var MASK_TYPES = /* @__PURE__ */ ((MASK_TYPES2) => { + MASK_TYPES2[MASK_TYPES2["NONE"] = 0] = "NONE"; + MASK_TYPES2[MASK_TYPES2["SCISSOR"] = 1] = "SCISSOR"; + MASK_TYPES2[MASK_TYPES2["STENCIL"] = 2] = "STENCIL"; + MASK_TYPES2[MASK_TYPES2["SPRITE"] = 3] = "SPRITE"; + MASK_TYPES2[MASK_TYPES2["COLOR"] = 4] = "COLOR"; + return MASK_TYPES2; + })(MASK_TYPES || {}); + var COLOR_MASK_BITS = /* @__PURE__ */ ((COLOR_MASK_BITS2) => { + COLOR_MASK_BITS2[COLOR_MASK_BITS2["RED"] = 1] = "RED"; + COLOR_MASK_BITS2[COLOR_MASK_BITS2["GREEN"] = 2] = "GREEN"; + COLOR_MASK_BITS2[COLOR_MASK_BITS2["BLUE"] = 4] = "BLUE"; + COLOR_MASK_BITS2[COLOR_MASK_BITS2["ALPHA"] = 8] = "ALPHA"; + return COLOR_MASK_BITS2; + })(COLOR_MASK_BITS || {}); + var MSAA_QUALITY = /* @__PURE__ */ ((MSAA_QUALITY2) => { + MSAA_QUALITY2[MSAA_QUALITY2["NONE"] = 0] = "NONE"; + MSAA_QUALITY2[MSAA_QUALITY2["LOW"] = 2] = "LOW"; + MSAA_QUALITY2[MSAA_QUALITY2["MEDIUM"] = 4] = "MEDIUM"; + MSAA_QUALITY2[MSAA_QUALITY2["HIGH"] = 8] = "HIGH"; + return MSAA_QUALITY2; + })(MSAA_QUALITY || {}); + var BUFFER_TYPE = /* @__PURE__ */ ((BUFFER_TYPE2) => { + BUFFER_TYPE2[BUFFER_TYPE2["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER"; + BUFFER_TYPE2[BUFFER_TYPE2["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER"; + BUFFER_TYPE2[BUFFER_TYPE2["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER"; + return BUFFER_TYPE2; + })(BUFFER_TYPE || {}); + + const BrowserAdapter = { + createCanvas: (width, height) => { + const canvas = document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + return canvas; + }, + getCanvasRenderingContext2D: () => CanvasRenderingContext2D, + getWebGLRenderingContext: () => WebGLRenderingContext, + getNavigator: () => navigator, + getBaseUrl: () => document.baseURI ?? window.location.href, + getFontFaceSet: () => document.fonts, + fetch: (url, options) => fetch(url, options), + parseXML: (xml) => { + const parser = new DOMParser(); + return parser.parseFromString(xml, "text/xml"); + } + }; + + const settings = { + ADAPTER: BrowserAdapter, + RESOLUTION: 1, + CREATE_IMAGE_BITMAP: false, + ROUND_PIXELS: false + }; + + var appleIphone = /iPhone/i; + var appleIpod = /iPod/i; + var appleTablet = /iPad/i; + var appleUniversal = /\biOS-universal(?:.+)Mac\b/i; + var androidPhone = /\bAndroid(?:.+)Mobile\b/i; + var androidTablet = /Android/i; + var amazonPhone = /(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i; + var amazonTablet = /Silk/i; + var windowsPhone = /Windows Phone/i; + var windowsTablet = /\bWindows(?:.+)ARM\b/i; + var otherBlackBerry = /BlackBerry/i; + var otherBlackBerry10 = /BB10/i; + var otherOpera = /Opera Mini/i; + var otherChrome = /\b(CriOS|Chrome)(?:.+)Mobile/i; + var otherFirefox = /Mobile(?:.+)Firefox\b/i; + var isAppleTabletOnIos13 = function (navigator) { + return (typeof navigator !== 'undefined' && + navigator.platform === 'MacIntel' && + typeof navigator.maxTouchPoints === 'number' && + navigator.maxTouchPoints > 1 && + typeof MSStream === 'undefined'); + }; + function createMatch(userAgent) { + return function (regex) { return regex.test(userAgent); }; + } + function isMobile$1(param) { + var nav = { + userAgent: '', + platform: '', + maxTouchPoints: 0 + }; + if (!param && typeof navigator !== 'undefined') { + nav = { + userAgent: navigator.userAgent, + platform: navigator.platform, + maxTouchPoints: navigator.maxTouchPoints || 0 + }; + } + else if (typeof param === 'string') { + nav.userAgent = param; + } + else if (param && param.userAgent) { + nav = { + userAgent: param.userAgent, + platform: param.platform, + maxTouchPoints: param.maxTouchPoints || 0 + }; + } + var userAgent = nav.userAgent; + var tmp = userAgent.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + userAgent = tmp[0]; + } + tmp = userAgent.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + userAgent = tmp[0]; + } + var match = createMatch(userAgent); + var result = { + apple: { + phone: match(appleIphone) && !match(windowsPhone), + ipod: match(appleIpod), + tablet: !match(appleIphone) && + (match(appleTablet) || isAppleTabletOnIos13(nav)) && + !match(windowsPhone), + universal: match(appleUniversal), + device: (match(appleIphone) || + match(appleIpod) || + match(appleTablet) || + match(appleUniversal) || + isAppleTabletOnIos13(nav)) && + !match(windowsPhone) + }, + amazon: { + phone: match(amazonPhone), + tablet: !match(amazonPhone) && match(amazonTablet), + device: match(amazonPhone) || match(amazonTablet) + }, + android: { + phone: (!match(windowsPhone) && match(amazonPhone)) || + (!match(windowsPhone) && match(androidPhone)), + tablet: !match(windowsPhone) && + !match(amazonPhone) && + !match(androidPhone) && + (match(amazonTablet) || match(androidTablet)), + device: (!match(windowsPhone) && + (match(amazonPhone) || + match(amazonTablet) || + match(androidPhone) || + match(androidTablet))) || + match(/\bokhttp\b/i) + }, + windows: { + phone: match(windowsPhone), + tablet: match(windowsTablet), + device: match(windowsPhone) || match(windowsTablet) + }, + other: { + blackberry: match(otherBlackBerry), + blackberry10: match(otherBlackBerry10), + opera: match(otherOpera), + firefox: match(otherFirefox), + chrome: match(otherChrome), + device: match(otherBlackBerry) || + match(otherBlackBerry10) || + match(otherOpera) || + match(otherFirefox) || + match(otherChrome) + }, + any: false, + phone: false, + tablet: false + }; + result.any = + result.apple.device || + result.android.device || + result.windows.device || + result.other.device; + result.phone = + result.apple.phone || result.android.phone || result.windows.phone; + result.tablet = + result.apple.tablet || result.android.tablet || result.windows.tablet; + return result; + } + + const isMobileCall = isMobile$1.default ?? isMobile$1; + const isMobile = isMobileCall(globalThis.navigator); + + settings.RETINA_PREFIX = /@([0-9\.]+)x/; + settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT = false; + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; + } + + function createCommonjsModule(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function (path, base) { + return commonjsRequire(path, (base === undefined || base === null) ? module.path : base); + } + }, fn(module, module.exports), module.exports; + } + + function getDefaultExportFromNamespaceIfPresent (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n; + } + + function getDefaultExportFromNamespaceIfNotNamed (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n; + } + + function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var a = Object.defineProperty({}, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; + } + + function commonjsRequire () { + throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); + } + + var eventemitter3 = createCommonjsModule(function (module) { + 'use strict'; + + var has = Object.prototype.hasOwnProperty + , prefix = '~'; + + /** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ + function Events() {} + + // + // We try to not inherit from `Object.prototype`. In some engines creating an + // instance in this way is faster than calling `Object.create(null)` directly. + // If `Object.create(null)` is not supported we prefix the event names with a + // character to make sure that the built-in object properties are not + // overridden or used as an attack vector. + // + if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; + } + + /** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ + function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; + } + + /** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ + function addListener(emitter, event, fn, context, once) { + if (typeof fn !== 'function') { + throw new TypeError('The listener must be a function'); + } + + var listener = new EE(fn, context || emitter, once) + , evt = prefix ? prefix + event : event; + + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; + + return emitter; + } + + /** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ + function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; + } + + /** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ + function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; + } + + /** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ + EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; + }; + + /** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ + EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; + + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; + + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } + + return ee; + }; + + /** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ + EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; + + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; + }; + + /** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ + EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; + }; + + /** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); + }; + + /** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); + }; + + /** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + clearEvent(this, evt); + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } + + return this; + }; + + /** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; + }; + + // + // Alias methods names because people roll like that. + // + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + EventEmitter.prototype.addListener = EventEmitter.prototype.on; + + // + // Expose the prefix. + // + EventEmitter.prefixed = prefix; + + // + // Allow `EventEmitter` to be imported as module namespace. + // + EventEmitter.EventEmitter = EventEmitter; + + // + // Expose the module. + // + if ('undefined' !== 'object') { + module.exports = EventEmitter; + } + }); + + 'use strict'; + + var earcut_1 = earcut; + var _default = earcut; + + function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode || outerNode.next === outerNode.prev) return triangles; + + var minX, minY, maxX, maxY, x, y, invSize; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 32767 / invSize : 0; + } + + earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); + + return triangles; + } + + // create a circular doubly linked list from polygon points in the specified winding order + function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; + } + + // eliminate colinear or duplicate points + function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) break; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; + } + + // main ear slicing loop which triangulates a polygon (given as a linked list) + function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && invSize) indexCurve(ear, minX, minY, invSize); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim | 0); + triangles.push(ear.i / dim | 0); + triangles.push(next.i / dim | 0); + + removeNode(ear); + + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(filterPoints(ear), triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + + break; + } + } + } + + // check whether a polygon node forms a valid ear with adjacent nodes + function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + var x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx), + y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy), + x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx), + y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy); + + var p = c.next; + while (p !== a) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; + } + + function isEarHashed(ear, minX, minY, invSize) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + var x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx), + y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy), + x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx), + y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy); + + // z-order range for the current triangle bbox; + var minZ = zOrder(x0, y0, minX, minY, invSize), + maxZ = zOrder(x1, y1, minX, minY, invSize); + + var p = ear.prevZ, + n = ear.nextZ; + + // look for points inside the triangle in both directions + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + // look for remaining points in decreasing z-order + while (p && p.z >= minZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + // look for remaining points in increasing z-order + while (n && n.z <= maxZ) { + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + return true; + } + + // go through all polygon nodes and cure small local self-intersections + function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim | 0); + triangles.push(p.i / dim | 0); + triangles.push(b.i / dim | 0); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return filterPoints(p); + } + + // try splitting polygon into two and triangulate them independently + function splitEarcut(start, triangles, dim, minX, minY, invSize) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, invSize, 0); + earcutLinked(c, triangles, dim, minX, minY, invSize, 0); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); + } + + // link every hole into the outer loop, producing a single-ring polygon without holes + function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + outerNode = eliminateHole(queue[i], outerNode); + } + + return outerNode; + } + + function compareX(a, b) { + return a.x - b.x; + } + + // find a bridge between vertices that connects hole with an outer ring and and link it + function eliminateHole(hole, outerNode) { + var bridge = findHoleBridge(hole, outerNode); + if (!bridge) { + return outerNode; + } + + var bridgeReverse = splitPolygon(bridge, hole); + + // filter collinear points around the cuts + filterPoints(bridgeReverse, bridgeReverse.next); + return filterPoints(bridge, bridge.next); + } + + // David Eberly's algorithm for finding a bridge between hole and outer polygon + function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m; + + do { + if (hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if (locallyInside(p, hole) && + (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } while (p !== stop); + + return m; + } + + // whether sector in vertex m contains sector in vertex p in the same coordinates + function sectorContainsSector(m, p) { + return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; + } + + // interlink polygon nodes in z-order + function indexCurve(start, minX, minY, invSize) { + var p = start; + do { + if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); + } + + // Simon Tatham's linked list merge sort algorithm + // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html + function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; + } + + // z-order of a point given coords and inverse of the longer side of data bbox + function zOrder(x, y, minX, minY, invSize) { + // coords are transformed into non-negative 15-bit integer range + x = (x - minX) * invSize | 0; + y = (y - minY) * invSize | 0; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); + } + + // find the leftmost node of a polygon ring + function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; + } + + // check if a point lies within a convex triangle + function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) >= (ax - px) * (cy - py) && + (ax - px) * (by - py) >= (bx - px) * (ay - py) && + (bx - px) * (cy - py) >= (cx - px) * (by - py); + } + + // check if a diagonal between two polygon nodes is valid (lies in polygon interior) + function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges + (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible + (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors + equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case + } + + // signed area of a triangle + function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); + } + + // check if two points are equal + function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; + } + + // check if two segments intersect + function intersects(p1, q1, p2, q2) { + var o1 = sign$1(area(p1, q1, p2)); + var o2 = sign$1(area(p1, q1, q2)); + var o3 = sign$1(area(p2, q2, p1)); + var o4 = sign$1(area(p2, q2, q1)); + + if (o1 !== o2 && o3 !== o4) return true; // general case + + if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 + if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 + if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 + if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 + + return false; + } + + // for collinear points p, q, r, check if point q lies on segment pr + function onSegment(p, q, r) { + return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); + } + + function sign$1(num) { + return num > 0 ? 1 : num < 0 ? -1 : 0; + } + + // check if a polygon diagonal intersects any polygon segments + function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; + } + + // check if a polygon diagonal is locally inside the polygon + function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; + } + + // check if the middle point of a polygon diagonal is inside the polygon + function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && + (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; + } + + // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; + // if one belongs to the outer ring and another to a hole, it merges it into a single ring + function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; + } + + // create a node and optionally link it with previous one (in a circular doubly linked list) + function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; + } + + function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; + } + + function Node(i, x, y) { + // vertex index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertex nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = 0; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; + } + + // return a percentage difference between the polygon area and its triangulation area; + // used to verify correctness of triangulation + earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); + }; + + function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; + } + + // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts + earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; + }; + earcut_1.default = _default; + + var punycode = createCommonjsModule(function (module, exports) { + /*! https://mths.be/punycode v1.3.2 by @mathias */ + ;(function(root) { + + /** Detect free variables */ + var freeExports = 'object' == 'object' && exports && + !exports.nodeType && exports; + var freeModule = 'object' == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * http://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.3.2', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof undefined == 'function' && + typeof undefined.amd == 'object' && + undefined.amd + ) { + undefined('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { // in Rhino or a web browser + root.punycode = punycode; + } + + }(commonjsGlobal)); + }); + + 'use strict'; + + var util = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } + }; + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + // If obj.hasOwnProperty has been overridden, then calling + // obj.hasOwnProperty(prop) will break. + // See: https://github.com/joyent/node/issues/1707 + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var decode = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (Array.isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; + }; + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } + }; + + var encode = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return Object.keys(obj).map(function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (Array.isArray(obj[k])) { + return obj[k].map(function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); + }; + + var querystring = createCommonjsModule(function (module, exports) { + 'use strict'; + + exports.decode = exports.parse = decode; + exports.encode = exports.stringify = encode; + }); + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + + + + var parse = urlParse; + var resolve = urlResolve; + var resolveObject = urlResolveObject; + var format = urlFormat; + + var Url_1 = Url; + + function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; + } + + // Reference: RFC 3986, RFC 1808, RFC 2396 + + // define these here so at least they only have to be + // compiled once on the first module load. + var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }; + + function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; + } + + Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; + }; + + // format a parsed object into a url string + function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); + } + + Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; + }; + + function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); + } + + Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); + }; + + function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); + } + + Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + }; + + Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; + }; + + var url$1 = { + parse: parse, + resolve: resolve, + resolveObject: resolveObject, + format: format, + Url: Url_1 + }; + + const url = { + parse: parse, + format: format, + resolve: resolve + }; + + function assertPath(path2) { + if (typeof path2 !== "string") { + throw new TypeError(`Path must be a string. Received ${JSON.stringify(path2)}`); + } + } + function removeUrlParams(url) { + const re = url.split("?")[0]; + return re.split("#")[0]; + } + function escapeRegExp(string) { + return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + } + function replaceAll(str, find, replace) { + return str.replace(new RegExp(escapeRegExp(find), "g"), replace); + } + function normalizeStringPosix(path2, allowAboveRoot) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let code = -1; + for (let i = 0; i <= path2.length; ++i) { + if (i < path2.length) { + code = path2.charCodeAt(i); + } else if (code === 47) { + break; + } else { + code = 47; + } + if (code === 47) { + if (lastSlash === i - 1 || dots === 1) { + } else if (lastSlash !== i - 1 && dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 || res.charCodeAt(res.length - 2) !== 46) { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf("/"); + if (lastSlashIndex !== res.length - 1) { + if (lastSlashIndex === -1) { + res = ""; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); + } + lastSlash = i; + dots = 0; + continue; + } + } else if (res.length === 2 || res.length === 1) { + res = ""; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + if (res.length > 0) { + res += "/.."; + } else { + res = ".."; + } + lastSegmentLength = 2; + } + } else { + if (res.length > 0) { + res += `/${path2.slice(lastSlash + 1, i)}`; + } else { + res = path2.slice(lastSlash + 1, i); + } + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } else if (code === 46 && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; + } + const path = { + toPosix(path2) { + return replaceAll(path2, "\\", "/"); + }, + isUrl(path2) { + return /^https?:/.test(this.toPosix(path2)); + }, + isDataUrl(path2) { + return /^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(path2); + }, + hasProtocol(path2) { + return /^[^/:]+:\//.test(this.toPosix(path2)); + }, + getProtocol(path2) { + assertPath(path2); + path2 = this.toPosix(path2); + let protocol = ""; + const isFile = /^file:\/\/\//.exec(path2); + const isHttp = /^[^/:]+:\/\//.exec(path2); + const isWindows = /^[^/:]+:\//.exec(path2); + if (isFile || isHttp || isWindows) { + const arr = isFile?.[0] || isHttp?.[0] || isWindows?.[0]; + protocol = arr; + path2 = path2.slice(arr.length); + } + return protocol; + }, + toAbsolute(url, customBaseUrl, customRootUrl) { + if (this.isDataUrl(url)) + return url; + const baseUrl = removeUrlParams(this.toPosix(customBaseUrl ?? settings.ADAPTER.getBaseUrl())); + const rootUrl = removeUrlParams(this.toPosix(customRootUrl ?? this.rootname(baseUrl))); + assertPath(url); + url = this.toPosix(url); + if (url.startsWith("/")) { + return path.join(rootUrl, url.slice(1)); + } + const absolutePath = this.isAbsolute(url) ? url : this.join(baseUrl, url); + return absolutePath; + }, + normalize(path2) { + path2 = this.toPosix(path2); + assertPath(path2); + if (path2.length === 0) + return "."; + let protocol = ""; + const isAbsolute = path2.startsWith("/"); + if (this.hasProtocol(path2)) { + protocol = this.rootname(path2); + path2 = path2.slice(protocol.length); + } + const trailingSeparator = path2.endsWith("/"); + path2 = normalizeStringPosix(path2, false); + if (path2.length > 0 && trailingSeparator) + path2 += "/"; + if (isAbsolute) + return `/${path2}`; + return protocol + path2; + }, + isAbsolute(path2) { + assertPath(path2); + path2 = this.toPosix(path2); + if (this.hasProtocol(path2)) + return true; + return path2.startsWith("/"); + }, + join(...segments) { + if (segments.length === 0) { + return "."; + } + let joined; + for (let i = 0; i < segments.length; ++i) { + const arg = segments[i]; + assertPath(arg); + if (arg.length > 0) { + if (joined === void 0) + joined = arg; + else { + const prevArg = segments[i - 1] ?? ""; + if (this.extname(prevArg)) { + joined += `/../${arg}`; + } else { + joined += `/${arg}`; + } + } + } + } + if (joined === void 0) { + return "."; + } + return this.normalize(joined); + }, + dirname(path2) { + assertPath(path2); + if (path2.length === 0) + return "."; + path2 = this.toPosix(path2); + let code = path2.charCodeAt(0); + const hasRoot = code === 47; + let end = -1; + let matchedSlash = true; + const proto = this.getProtocol(path2); + const origpath = path2; + path2 = path2.slice(proto.length); + for (let i = path2.length - 1; i >= 1; --i) { + code = path2.charCodeAt(i); + if (code === 47) { + if (!matchedSlash) { + end = i; + break; + } + } else { + matchedSlash = false; + } + } + if (end === -1) + return hasRoot ? "/" : this.isUrl(origpath) ? proto + path2 : proto; + if (hasRoot && end === 1) + return "//"; + return proto + path2.slice(0, end); + }, + rootname(path2) { + assertPath(path2); + path2 = this.toPosix(path2); + let root = ""; + if (path2.startsWith("/")) + root = "/"; + else { + root = this.getProtocol(path2); + } + if (this.isUrl(path2)) { + const index = path2.indexOf("/", root.length); + if (index !== -1) { + root = path2.slice(0, index); + } else + root = path2; + if (!root.endsWith("/")) + root += "/"; + } + return root; + }, + basename(path2, ext) { + assertPath(path2); + if (ext) + assertPath(ext); + path2 = removeUrlParams(this.toPosix(path2)); + let start = 0; + let end = -1; + let matchedSlash = true; + let i; + if (ext !== void 0 && ext.length > 0 && ext.length <= path2.length) { + if (ext.length === path2.length && ext === path2) + return ""; + let extIdx = ext.length - 1; + let firstNonSlashEnd = -1; + for (i = path2.length - 1; i >= 0; --i) { + const code = path2.charCodeAt(i); + if (code === 47) { + if (!matchedSlash) { + start = i + 1; + break; + } + } else { + if (firstNonSlashEnd === -1) { + matchedSlash = false; + firstNonSlashEnd = i + 1; + } + if (extIdx >= 0) { + if (code === ext.charCodeAt(extIdx)) { + if (--extIdx === -1) { + end = i; + } + } else { + extIdx = -1; + end = firstNonSlashEnd; + } + } + } + } + if (start === end) + end = firstNonSlashEnd; + else if (end === -1) + end = path2.length; + return path2.slice(start, end); + } + for (i = path2.length - 1; i >= 0; --i) { + if (path2.charCodeAt(i) === 47) { + if (!matchedSlash) { + start = i + 1; + break; + } + } else if (end === -1) { + matchedSlash = false; + end = i + 1; + } + } + if (end === -1) + return ""; + return path2.slice(start, end); + }, + extname(path2) { + assertPath(path2); + path2 = removeUrlParams(this.toPosix(path2)); + let startDot = -1; + let startPart = 0; + let end = -1; + let matchedSlash = true; + let preDotState = 0; + for (let i = path2.length - 1; i >= 0; --i) { + const code = path2.charCodeAt(i); + if (code === 47) { + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + matchedSlash = false; + end = i + 1; + } + if (code === 46) { + if (startDot === -1) + startDot = i; + else if (preDotState !== 1) + preDotState = 1; + } else if (startDot !== -1) { + preDotState = -1; + } + } + if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + return ""; + } + return path2.slice(startDot, end); + }, + parse(path2) { + assertPath(path2); + const ret = { root: "", dir: "", base: "", ext: "", name: "" }; + if (path2.length === 0) + return ret; + path2 = removeUrlParams(this.toPosix(path2)); + let code = path2.charCodeAt(0); + const isAbsolute = this.isAbsolute(path2); + let start; + const protocol = ""; + ret.root = this.rootname(path2); + if (isAbsolute || this.hasProtocol(path2)) { + start = 1; + } else { + start = 0; + } + let startDot = -1; + let startPart = 0; + let end = -1; + let matchedSlash = true; + let i = path2.length - 1; + let preDotState = 0; + for (; i >= start; --i) { + code = path2.charCodeAt(i); + if (code === 47) { + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + matchedSlash = false; + end = i + 1; + } + if (code === 46) { + if (startDot === -1) + startDot = i; + else if (preDotState !== 1) + preDotState = 1; + } else if (startDot !== -1) { + preDotState = -1; + } + } + if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + if (end !== -1) { + if (startPart === 0 && isAbsolute) + ret.base = ret.name = path2.slice(1, end); + else + ret.base = ret.name = path2.slice(startPart, end); + } + } else { + if (startPart === 0 && isAbsolute) { + ret.name = path2.slice(1, startDot); + ret.base = path2.slice(1, end); + } else { + ret.name = path2.slice(startPart, startDot); + ret.base = path2.slice(startPart, end); + } + ret.ext = path2.slice(startDot, end); + } + ret.dir = this.dirname(path2); + if (protocol) + ret.dir = protocol + ret.dir; + return ret; + }, + sep: "/", + delimiter: ":" + }; + + const warnings = {}; + function deprecation$1(version, message, ignoreDepth = 3) { + if (warnings[message]) { + return; + } + let stack = new Error().stack; + if (typeof stack === "undefined") { + console.warn("PixiJS Deprecation Warning: ", `${message} +Deprecated since v${version}`); + } else { + stack = stack.split("\n").splice(ignoreDepth).join("\n"); + if (console.groupCollapsed) { + console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s", "color:#614108;background:#fffbe6", "font-weight:normal;color:#614108;background:#fffbe6", `${message} +Deprecated since v${version}`); + console.warn(stack); + console.groupEnd(); + } else { + console.warn("PixiJS Deprecation Warning: ", `${message} +Deprecated since v${version}`); + console.warn(stack); + } + } + warnings[message] = true; + } + + function skipHello() { + deprecation$1("7.0.0", "skipHello is deprecated, please use settings.RENDER_OPTIONS.hello"); + } + function sayHello() { + deprecation$1("7.0.0", `sayHello is deprecated, please use Renderer's "hello" option`); + } + + let supported; + function isWebGLSupported() { + if (typeof supported === "undefined") { + supported = function supported2() { + const contextOptions = { + stencil: true, + failIfMajorPerformanceCaveat: settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT + }; + try { + if (!settings.ADAPTER.getWebGLRenderingContext()) { + return false; + } + const canvas = settings.ADAPTER.createCanvas(); + let gl = canvas.getContext("webgl", contextOptions) || canvas.getContext("experimental-webgl", contextOptions); + const success = !!gl?.getContextAttributes()?.stencil; + if (gl) { + const loseContext = gl.getExtension("WEBGL_lose_context"); + if (loseContext) { + loseContext.loseContext(); + } + } + gl = null; + return success; + } catch (e) { + return false; + } + }(); + } + return supported; + } + + var r={grad:.9,turn:360,rad:360/(2*Math.PI)},t=function(r){return "string"==typeof r?r.length>0:"number"==typeof r},n=function(r,t,n){return void 0===t&&(t=0),void 0===n&&(n=Math.pow(10,t)),Math.round(n*r)/n+0},e=function(r,t,n){return void 0===t&&(t=0),void 0===n&&(n=1),r>n?n:r>t?r:t},u=function(r){return (r=isFinite(r)?r%360:0)>0?r:r+360},a=function(r){return {r:e(r.r,0,255),g:e(r.g,0,255),b:e(r.b,0,255),a:e(r.a)}},o=function(r){return {r:n(r.r),g:n(r.g),b:n(r.b),a:n(r.a,3)}},i=/^#([0-9a-f]{3,8})$/i,s=function(r){var t=r.toString(16);return t.length<2?"0"+t:t},h=function(r){var t=r.r,n=r.g,e=r.b,u=r.a,a=Math.max(t,n,e),o=a-Math.min(t,n,e),i=o?a===t?(n-e)/o:a===n?2+(e-t)/o:4+(t-n)/o:0;return {h:60*(i<0?i+6:i),s:a?o/a*100:0,v:a/255*100,a:u}},b=function(r){var t=r.h,n=r.s,e=r.v,u=r.a;t=t/360*6,n/=100,e/=100;var a=Math.floor(t),o=e*(1-n),i=e*(1-(t-a)*n),s=e*(1-(1-t+a)*n),h=a%6;return {r:255*[e,i,o,o,s,e][h],g:255*[s,e,e,i,o,o][h],b:255*[o,o,s,e,e,i][h],a:u}},g=function(r){return {h:u(r.h),s:e(r.s,0,100),l:e(r.l,0,100),a:e(r.a)}},d=function(r){return {h:n(r.h),s:n(r.s),l:n(r.l),a:n(r.a,3)}},f=function(r){return b((n=(t=r).s,{h:t.h,s:(n*=((e=t.l)<50?e:100-e)/100)>0?2*n/(e+n)*100:0,v:e+n,a:t.a}));var t,n,e;},c=function(r){return {h:(t=h(r)).h,s:(u=(200-(n=t.s))*(e=t.v)/100)>0&&u<200?n*e/100/(u<=100?u:200-u)*100:0,l:u/2,a:t.a};var t,n,e,u;},l=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,p=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,v=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,m=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,y={string:[[function(r){var t=i.exec(r);return t?(r=t[1]).length<=4?{r:parseInt(r[0]+r[0],16),g:parseInt(r[1]+r[1],16),b:parseInt(r[2]+r[2],16),a:4===r.length?n(parseInt(r[3]+r[3],16)/255,2):1}:6===r.length||8===r.length?{r:parseInt(r.substr(0,2),16),g:parseInt(r.substr(2,2),16),b:parseInt(r.substr(4,2),16),a:8===r.length?n(parseInt(r.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(r){var t=v.exec(r)||m.exec(r);return t?t[2]!==t[4]||t[4]!==t[6]?null:a({r:Number(t[1])/(t[2]?100/255:1),g:Number(t[3])/(t[4]?100/255:1),b:Number(t[5])/(t[6]?100/255:1),a:void 0===t[7]?1:Number(t[7])/(t[8]?100:1)}):null},"rgb"],[function(t){var n=l.exec(t)||p.exec(t);if(!n)return null;var e,u,a=g({h:(e=n[1],u=n[2],void 0===u&&(u="deg"),Number(e)*(r[u]||1)),s:Number(n[3]),l:Number(n[4]),a:void 0===n[5]?1:Number(n[5])/(n[6]?100:1)});return f(a)},"hsl"]],object:[[function(r){var n=r.r,e=r.g,u=r.b,o=r.a,i=void 0===o?1:o;return t(n)&&t(e)&&t(u)?a({r:Number(n),g:Number(e),b:Number(u),a:Number(i)}):null},"rgb"],[function(r){var n=r.h,e=r.s,u=r.l,a=r.a,o=void 0===a?1:a;if(!t(n)||!t(e)||!t(u))return null;var i=g({h:Number(n),s:Number(e),l:Number(u),a:Number(o)});return f(i)},"hsl"],[function(r){var n=r.h,a=r.s,o=r.v,i=r.a,s=void 0===i?1:i;if(!t(n)||!t(a)||!t(o))return null;var h=function(r){return {h:u(r.h),s:e(r.s,0,100),v:e(r.v,0,100),a:e(r.a)}}({h:Number(n),s:Number(a),v:Number(o),a:Number(s)});return b(h)},"hsv"]]},N=function(r,t){for(var n=0;n=.5},r.prototype.toHex=function(){return r=o(this.rgba),t=r.r,e=r.g,u=r.b,i=(a=r.a)<1?s(n(255*a)):"","#"+s(t)+s(e)+s(u)+i;var r,t,e,u,a,i;},r.prototype.toRgb=function(){return o(this.rgba)},r.prototype.toRgbString=function(){return r=o(this.rgba),t=r.r,n=r.g,e=r.b,(u=r.a)<1?"rgba("+t+", "+n+", "+e+", "+u+")":"rgb("+t+", "+n+", "+e+")";var r,t,n,e,u;},r.prototype.toHsl=function(){return d(c(this.rgba))},r.prototype.toHslString=function(){return r=d(c(this.rgba)),t=r.h,n=r.s,e=r.l,(u=r.a)<1?"hsla("+t+", "+n+"%, "+e+"%, "+u+")":"hsl("+t+", "+n+"%, "+e+"%)";var r,t,n,e,u;},r.prototype.toHsv=function(){return r=h(this.rgba),{h:n(r.h),s:n(r.s),v:n(r.v),a:n(r.a,3)};var r;},r.prototype.invert=function(){return w({r:255-(r=this.rgba).r,g:255-r.g,b:255-r.b,a:r.a});var r;},r.prototype.saturate=function(r){return void 0===r&&(r=.1),w(M(this.rgba,r))},r.prototype.desaturate=function(r){return void 0===r&&(r=.1),w(M(this.rgba,-r))},r.prototype.grayscale=function(){return w(M(this.rgba,-1))},r.prototype.lighten=function(r){return void 0===r&&(r=.1),w($(this.rgba,r))},r.prototype.darken=function(r){return void 0===r&&(r=.1),w($(this.rgba,-r))},r.prototype.rotate=function(r){return void 0===r&&(r=15),this.hue(this.hue()+r)},r.prototype.alpha=function(r){return "number"==typeof r?w({r:(t=this.rgba).r,g:t.g,b:t.b,a:r}):n(this.rgba.a,3);var t;},r.prototype.hue=function(r){var t=c(this.rgba);return "number"==typeof r?w({h:r,s:t.s,l:t.l,a:t.a}):n(t.h)},r.prototype.isEqual=function(r){return this.toHex()===w(r).toHex()},r}(),w=function(r){return r instanceof j?r:new j(r)},S=[],k=function(r){r.forEach(function(r){S.indexOf(r)<0&&(r(j,y),S.push(r));});},E=function(){return new j({r:255*Math.random(),g:255*Math.random(),b:255*Math.random()})}; + + function namesPlugin(e,f){var a={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},r={};for(var d in a)r[a[d]]=d;var l={};e.prototype.toName=function(f){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return "transparent";var d,i,n=r[this.toHex()];if(n)return n;if(null==f?void 0:f.closest){var o=this.toRgb(),t=1/0,b="black";if(!l.length)for(var c in a)l[c]=new e(a[c]).toRgb();for(var g in a){var u=(d=o,i=l[g],Math.pow(d.r-i.r,2)+Math.pow(d.g-i.g,2)+Math.pow(d.b-i.b,2));u v === value2[i]); + } else if (value1 !== null && value2 !== null) { + const keys1 = Object.keys(value1); + const keys2 = Object.keys(value2); + if (keys1.length !== keys2.length) { + return false; + } + return keys1.every((key) => value1[key] === value2[key]); + } + return value1 === value2; + } + toRgba() { + const [r, g, b, a] = this._components; + return { r, g, b, a }; + } + toRgb() { + const [r, g, b] = this._components; + return { r, g, b }; + } + toRgbaString() { + const [r, g, b] = this.toUint8RgbArray(); + return `rgba(${r},${g},${b},${this.alpha})`; + } + toUint8RgbArray(out) { + const [r, g, b] = this._components; + out = out ?? []; + out[0] = Math.round(r * 255); + out[1] = Math.round(g * 255); + out[2] = Math.round(b * 255); + return out; + } + toRgbArray(out) { + out = out ?? []; + const [r, g, b] = this._components; + out[0] = r; + out[1] = g; + out[2] = b; + return out; + } + toNumber() { + return this._int; + } + toLittleEndianNumber() { + const value = this._int; + return (value >> 16) + (value & 65280) + ((value & 255) << 16); + } + multiply(value) { + const [r, g, b, a] = _Color.temp.setValue(value)._components; + this._components[0] *= r; + this._components[1] *= g; + this._components[2] *= b; + this._components[3] *= a; + this.refreshInt(); + this._value = null; + return this; + } + premultiply(alpha, applyToRGB = true) { + if (applyToRGB) { + this._components[0] *= alpha; + this._components[1] *= alpha; + this._components[2] *= alpha; + } + this._components[3] = alpha; + this.refreshInt(); + this._value = null; + return this; + } + toPremultiplied(alpha, applyToRGB = true) { + if (alpha === 1) { + return (255 << 24) + this._int; + } + if (alpha === 0) { + return applyToRGB ? 0 : this._int; + } + let r = this._int >> 16 & 255; + let g = this._int >> 8 & 255; + let b = this._int & 255; + if (applyToRGB) { + r = r * alpha + 0.5 | 0; + g = g * alpha + 0.5 | 0; + b = b * alpha + 0.5 | 0; + } + return (alpha * 255 << 24) + (r << 16) + (g << 8) + b; + } + toHex() { + const hexString = this._int.toString(16); + return `#${"000000".substring(0, 6 - hexString.length) + hexString}`; + } + toHexa() { + const alphaValue = Math.round(this._components[3] * 255); + const alphaString = alphaValue.toString(16); + return this.toHex() + "00".substring(0, 2 - alphaString.length) + alphaString; + } + setAlpha(alpha) { + this._components[3] = this._clamp(alpha); + return this; + } + round(steps) { + const [r, g, b] = this._components; + this._components[0] = Math.round(r * steps) / steps; + this._components[1] = Math.round(g * steps) / steps; + this._components[2] = Math.round(b * steps) / steps; + this.refreshInt(); + this._value = null; + return this; + } + toArray(out) { + out = out ?? []; + const [r, g, b, a] = this._components; + out[0] = r; + out[1] = g; + out[2] = b; + out[3] = a; + return out; + } + normalize(value) { + let r; + let g; + let b; + let a; + if ((typeof value === "number" || value instanceof Number) && value >= 0 && value <= 16777215) { + const int = value; + r = (int >> 16 & 255) / 255; + g = (int >> 8 & 255) / 255; + b = (int & 255) / 255; + a = 1; + } else if ((Array.isArray(value) || value instanceof Float32Array) && value.length >= 3 && value.length <= 4) { + value = this._clamp(value); + [r, g, b, a = 1] = value; + } else if ((value instanceof Uint8Array || value instanceof Uint8ClampedArray) && value.length >= 3 && value.length <= 4) { + value = this._clamp(value, 0, 255); + [r, g, b, a = 255] = value; + r /= 255; + g /= 255; + b /= 255; + a /= 255; + } else if (typeof value === "string" || typeof value === "object") { + if (typeof value === "string") { + const match = _Color.HEX_PATTERN.exec(value); + if (match) { + value = `#${match[2]}`; + } + } + const color = w(value); + if (color.isValid()) { + ({ r, g, b, a } = color.rgba); + r /= 255; + g /= 255; + b /= 255; + } + } + if (r !== void 0) { + this._components[0] = r; + this._components[1] = g; + this._components[2] = b; + this._components[3] = a; + this.refreshInt(); + } else { + throw new Error(`Unable to convert color ${value}`); + } + } + refreshInt() { + this._clamp(this._components); + const [r, g, b] = this._components; + this._int = (r * 255 << 16) + (g * 255 << 8) + (b * 255 | 0); + } + _clamp(value, min = 0, max = 1) { + if (typeof value === "number") { + return Math.min(Math.max(value, min), max); + } + value.forEach((v, i) => { + value[i] = Math.min(Math.max(v, min), max); + }); + return value; + } + }; + let Color = _Color; + Color.shared = new _Color(); + Color.temp = new _Color(); + Color.HEX_PATTERN = /^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i; + + function hex2rgb(hex, out = []) { + deprecation$1("7.2.0", "utils.hex2rgb is deprecated, use Color#toRgbArray instead"); + return Color.shared.setValue(hex).toRgbArray(out); + } + function hex2string(hex) { + deprecation$1("7.2.0", "utils.hex2string is deprecated, use Color#toHex instead"); + return Color.shared.setValue(hex).toHex(); + } + function string2hex(string) { + deprecation$1("7.2.0", "utils.string2hex is deprecated, use Color#toNumber instead"); + return Color.shared.setValue(string).toNumber(); + } + function rgb2hex(rgb) { + deprecation$1("7.2.0", "utils.rgb2hex is deprecated, use Color#toNumber instead"); + return Color.shared.setValue(rgb).toNumber(); + } + + function mapPremultipliedBlendModes() { + const pm = []; + const npm = []; + for (let i = 0; i < 32; i++) { + pm[i] = i; + npm[i] = i; + } + pm[BLEND_MODES.NORMAL_NPM] = BLEND_MODES.NORMAL; + pm[BLEND_MODES.ADD_NPM] = BLEND_MODES.ADD; + pm[BLEND_MODES.SCREEN_NPM] = BLEND_MODES.SCREEN; + npm[BLEND_MODES.NORMAL] = BLEND_MODES.NORMAL_NPM; + npm[BLEND_MODES.ADD] = BLEND_MODES.ADD_NPM; + npm[BLEND_MODES.SCREEN] = BLEND_MODES.SCREEN_NPM; + const array = []; + array.push(npm); + array.push(pm); + return array; + } + const premultiplyBlendMode = mapPremultipliedBlendModes(); + function correctBlendMode(blendMode, premultiplied) { + return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode]; + } + function premultiplyRgba(rgb, alpha, out, premultiply = true) { + deprecation$1("7.2.0", `utils.premultiplyRgba has moved to Color.premultiply`); + return Color.shared.setValue(rgb).premultiply(alpha, premultiply).toArray(out ?? new Float32Array(4)); + } + function premultiplyTint(tint, alpha) { + deprecation$1("7.2.0", `utils.premultiplyTint has moved to Color.toPremultiplied`); + return Color.shared.setValue(tint).toPremultiplied(alpha); + } + function premultiplyTintToRgba(tint, alpha, out, premultiply = true) { + deprecation$1("7.2.0", `utils.premultiplyTintToRgba has moved to Color.premultiply`); + return Color.shared.setValue(tint).premultiply(alpha, premultiply).toArray(out ?? new Float32Array(4)); + } + + const DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i; + + function createIndicesForQuads(size, outBuffer = null) { + const totalIndices = size * 6; + outBuffer = outBuffer || new Uint16Array(totalIndices); + if (outBuffer.length !== totalIndices) { + throw new Error(`Out buffer length is incorrect, got ${outBuffer.length} and expected ${totalIndices}`); + } + for (let i = 0, j = 0; i < totalIndices; i += 6, j += 4) { + outBuffer[i + 0] = j + 0; + outBuffer[i + 1] = j + 1; + outBuffer[i + 2] = j + 2; + outBuffer[i + 3] = j + 0; + outBuffer[i + 4] = j + 2; + outBuffer[i + 5] = j + 3; + } + return outBuffer; + } + + function getBufferType(array) { + if (array.BYTES_PER_ELEMENT === 4) { + if (array instanceof Float32Array) { + return "Float32Array"; + } else if (array instanceof Uint32Array) { + return "Uint32Array"; + } + return "Int32Array"; + } else if (array.BYTES_PER_ELEMENT === 2) { + if (array instanceof Uint16Array) { + return "Uint16Array"; + } + } else if (array.BYTES_PER_ELEMENT === 1) { + if (array instanceof Uint8Array) { + return "Uint8Array"; + } + } + return null; + } + + const map$2 = { Float32Array, Uint32Array, Int32Array, Uint8Array }; + function interleaveTypedArrays$1(arrays, sizes) { + let outSize = 0; + let stride = 0; + const views = {}; + for (let i = 0; i < arrays.length; i++) { + stride += sizes[i]; + outSize += arrays[i].length; + } + const buffer = new ArrayBuffer(outSize * 4); + let out = null; + let littleOffset = 0; + for (let i = 0; i < arrays.length; i++) { + const size = sizes[i]; + const array = arrays[i]; + const type = getBufferType(array); + if (!views[type]) { + views[type] = new map$2[type](buffer); + } + out = views[type]; + for (let j = 0; j < array.length; j++) { + const indexStart = (j / size | 0) * stride + littleOffset; + const index = j % size; + out[indexStart + index] = array[j]; + } + littleOffset += size; + } + return new Float32Array(buffer); + } + + function nextPow2(v) { + v += v === 0 ? 1 : 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; + } + function isPow2(v) { + return !(v & v - 1) && !!v; + } + function log2(v) { + let r = (v > 65535 ? 1 : 0) << 4; + v >>>= r; + let shift = (v > 255 ? 1 : 0) << 3; + v >>>= shift; + r |= shift; + shift = (v > 15 ? 1 : 0) << 2; + v >>>= shift; + r |= shift; + shift = (v > 3 ? 1 : 0) << 1; + v >>>= shift; + r |= shift; + return r | v >> 1; + } + + function removeItems(arr, startIdx, removeCount) { + const length = arr.length; + let i; + if (startIdx >= length || removeCount === 0) { + return; + } + removeCount = startIdx + removeCount > length ? length - startIdx : removeCount; + const len = length - removeCount; + for (i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount]; + } + arr.length = len; + } + + function sign(n) { + if (n === 0) + return 0; + return n < 0 ? -1 : 1; + } + + let nextUid = 0; + function uid() { + return ++nextUid; + } + + const _BoundingBox = class { + constructor(left, top, right, bottom) { + this.left = left; + this.top = top; + this.right = right; + this.bottom = bottom; + } + get width() { + return this.right - this.left; + } + get height() { + return this.bottom - this.top; + } + isEmpty() { + return this.left === this.right || this.top === this.bottom; + } + }; + let BoundingBox = _BoundingBox; + BoundingBox.EMPTY = new _BoundingBox(0, 0, 0, 0); + + const ProgramCache = {}; + const TextureCache = /* @__PURE__ */ Object.create(null); + const BaseTextureCache = /* @__PURE__ */ Object.create(null); + function destroyTextureCache() { + let key; + for (key in TextureCache) { + TextureCache[key].destroy(); + } + for (key in BaseTextureCache) { + BaseTextureCache[key].destroy(); + } + } + function clearTextureCache() { + let key; + for (key in TextureCache) { + delete TextureCache[key]; + } + for (key in BaseTextureCache) { + delete BaseTextureCache[key]; + } + } + + class CanvasRenderTarget { + constructor(width, height, resolution) { + this._canvas = settings.ADAPTER.createCanvas(); + this._context = this._canvas.getContext("2d"); + this.resolution = resolution || settings.RESOLUTION; + this.resize(width, height); + } + clear() { + this._checkDestroyed(); + this._context.setTransform(1, 0, 0, 1, 0, 0); + this._context.clearRect(0, 0, this._canvas.width, this._canvas.height); + } + resize(desiredWidth, desiredHeight) { + this._checkDestroyed(); + this._canvas.width = Math.round(desiredWidth * this.resolution); + this._canvas.height = Math.round(desiredHeight * this.resolution); + } + destroy() { + this._context = null; + this._canvas = null; + } + get width() { + this._checkDestroyed(); + return this._canvas.width; + } + set width(val) { + this._checkDestroyed(); + this._canvas.width = Math.round(val); + } + get height() { + this._checkDestroyed(); + return this._canvas.height; + } + set height(val) { + this._checkDestroyed(); + this._canvas.height = Math.round(val); + } + get canvas() { + this._checkDestroyed(); + return this._canvas; + } + get context() { + this._checkDestroyed(); + return this._context; + } + _checkDestroyed() { + if (this._canvas === null) { + throw new TypeError("The CanvasRenderTarget has already been destroyed"); + } + } + } + + function checkRow(data, width, y) { + for (let x = 0, index = 4 * y * width; x < width; ++x, index += 4) { + if (data[index + 3] !== 0) + return false; + } + return true; + } + function checkColumn(data, width, x, top, bottom) { + const stride = 4 * width; + for (let y = top, index = top * stride + 4 * x; y <= bottom; ++y, index += stride) { + if (data[index + 3] !== 0) + return false; + } + return true; + } + function getCanvasBoundingBox(canvas) { + const { width, height } = canvas; + const context = canvas.getContext("2d", { + willReadFrequently: true + }); + if (context === null) { + throw new TypeError("Failed to get canvas 2D context"); + } + const imageData = context.getImageData(0, 0, width, height); + const data = imageData.data; + let left = 0; + let top = 0; + let right = width - 1; + let bottom = height - 1; + while (top < height && checkRow(data, width, top)) + ++top; + if (top === height) + return BoundingBox.EMPTY; + while (checkRow(data, width, bottom)) + --bottom; + while (checkColumn(data, width, left, top, bottom)) + ++left; + while (checkColumn(data, width, right, top, bottom)) + --right; + ++right; + ++bottom; + return new BoundingBox(left, top, right, bottom); + } + + function trimCanvas(canvas) { + const boundingBox = getCanvasBoundingBox(canvas); + const { width, height } = boundingBox; + let data = null; + if (!boundingBox.isEmpty()) { + const context = canvas.getContext("2d"); + if (context === null) { + throw new TypeError("Failed to get canvas 2D context"); + } + data = context.getImageData(boundingBox.left, boundingBox.top, width, height); + } + return { width, height, data }; + } + + function decomposeDataUri(dataUri) { + const dataUriMatch = DATA_URI.exec(dataUri); + if (dataUriMatch) { + return { + mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : void 0, + subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : void 0, + charset: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : void 0, + encoding: dataUriMatch[4] ? dataUriMatch[4].toLowerCase() : void 0, + data: dataUriMatch[5] + }; + } + return void 0; + } + + let tempAnchor; + function determineCrossOrigin(url$1, loc = globalThis.location) { + if (url$1.startsWith("data:")) { + return ""; + } + loc = loc || globalThis.location; + if (!tempAnchor) { + tempAnchor = document.createElement("a"); + } + tempAnchor.href = url$1; + const parsedUrl = url.parse(tempAnchor.href); + const samePort = !parsedUrl.port && loc.port === "" || parsedUrl.port === loc.port; + if (parsedUrl.hostname !== loc.hostname || !samePort || parsedUrl.protocol !== loc.protocol) { + return "anonymous"; + } + return ""; + } + + function getResolutionOfUrl(url, defaultValue = 1) { + const resolution = settings.RETINA_PREFIX?.exec(url); + if (resolution) { + return parseFloat(resolution[1]); + } + return defaultValue; + } + + var utils = { + __proto__: null, + isMobile: isMobile, + EventEmitter: eventemitter3, + earcut: earcut_1, + url: url, + path: path, + sayHello: sayHello, + skipHello: skipHello, + isWebGLSupported: isWebGLSupported, + hex2rgb: hex2rgb, + hex2string: hex2string, + rgb2hex: rgb2hex, + string2hex: string2hex, + correctBlendMode: correctBlendMode, + premultiplyBlendMode: premultiplyBlendMode, + premultiplyRgba: premultiplyRgba, + premultiplyTint: premultiplyTint, + premultiplyTintToRgba: premultiplyTintToRgba, + DATA_URI: DATA_URI, + createIndicesForQuads: createIndicesForQuads, + getBufferType: getBufferType, + interleaveTypedArrays: interleaveTypedArrays$1, + isPow2: isPow2, + log2: log2, + nextPow2: nextPow2, + removeItems: removeItems, + sign: sign, + uid: uid, + deprecation: deprecation$1, + BoundingBox: BoundingBox, + BaseTextureCache: BaseTextureCache, + ProgramCache: ProgramCache, + TextureCache: TextureCache, + clearTextureCache: clearTextureCache, + destroyTextureCache: destroyTextureCache, + CanvasRenderTarget: CanvasRenderTarget, + getCanvasBoundingBox: getCanvasBoundingBox, + trimCanvas: trimCanvas, + decomposeDataUri: decomposeDataUri, + determineCrossOrigin: determineCrossOrigin, + getResolutionOfUrl: getResolutionOfUrl + }; + + var ExtensionType = /* @__PURE__ */ ((ExtensionType2) => { + ExtensionType2["Renderer"] = "renderer"; + ExtensionType2["Application"] = "application"; + ExtensionType2["RendererSystem"] = "renderer-webgl-system"; + ExtensionType2["RendererPlugin"] = "renderer-webgl-plugin"; + ExtensionType2["CanvasRendererSystem"] = "renderer-canvas-system"; + ExtensionType2["CanvasRendererPlugin"] = "renderer-canvas-plugin"; + ExtensionType2["Asset"] = "asset"; + ExtensionType2["LoadParser"] = "load-parser"; + ExtensionType2["ResolveParser"] = "resolve-parser"; + ExtensionType2["CacheParser"] = "cache-parser"; + ExtensionType2["DetectionParser"] = "detection-parser"; + return ExtensionType2; + })(ExtensionType || {}); + const normalizeExtension = (ext) => { + if (typeof ext === "function" || typeof ext === "object" && ext.extension) { + if (!ext.extension) { + throw new Error("Extension class must have an extension object"); + } + const metadata = typeof ext.extension !== "object" ? { type: ext.extension } : ext.extension; + ext = { ...metadata, ref: ext }; + } + if (typeof ext === "object") { + ext = { ...ext }; + } else { + throw new Error("Invalid extension type"); + } + if (typeof ext.type === "string") { + ext.type = [ext.type]; + } + return ext; + }; + const normalizePriority = (ext, defaultPriority) => normalizeExtension(ext).priority ?? defaultPriority; + const extensions$1 = { + _addHandlers: {}, + _removeHandlers: {}, + _queue: {}, + remove(...extensions2) { + extensions2.map(normalizeExtension).forEach((ext) => { + ext.type.forEach((type) => this._removeHandlers[type]?.(ext)); + }); + return this; + }, + add(...extensions2) { + extensions2.map(normalizeExtension).forEach((ext) => { + ext.type.forEach((type) => { + const handlers = this._addHandlers; + const queue = this._queue; + if (!handlers[type]) { + queue[type] = queue[type] || []; + queue[type].push(ext); + } else { + handlers[type](ext); + } + }); + }); + return this; + }, + handle(type, onAdd, onRemove) { + const addHandlers = this._addHandlers; + const removeHandlers = this._removeHandlers; + if (addHandlers[type] || removeHandlers[type]) { + throw new Error(`Extension type ${type} already has a handler`); + } + addHandlers[type] = onAdd; + removeHandlers[type] = onRemove; + const queue = this._queue; + if (queue[type]) { + queue[type].forEach((ext) => onAdd(ext)); + delete queue[type]; + } + return this; + }, + handleByMap(type, map) { + return this.handle(type, (extension) => { + map[extension.name] = extension.ref; + }, (extension) => { + delete map[extension.name]; + }); + }, + handleByList(type, list, defaultPriority = -1) { + return this.handle(type, (extension) => { + if (list.includes(extension.ref)) { + return; + } + list.push(extension.ref); + list.sort((a, b) => normalizePriority(b, defaultPriority) - normalizePriority(a, defaultPriority)); + }, (extension) => { + const index = list.indexOf(extension.ref); + if (index !== -1) { + list.splice(index, 1); + } + }); + } + }; + + class ViewableBuffer { + constructor(sizeOrBuffer) { + if (typeof sizeOrBuffer === "number") { + this.rawBinaryData = new ArrayBuffer(sizeOrBuffer); + } else if (sizeOrBuffer instanceof Uint8Array) { + this.rawBinaryData = sizeOrBuffer.buffer; + } else { + this.rawBinaryData = sizeOrBuffer; + } + this.uint32View = new Uint32Array(this.rawBinaryData); + this.float32View = new Float32Array(this.rawBinaryData); + } + get int8View() { + if (!this._int8View) { + this._int8View = new Int8Array(this.rawBinaryData); + } + return this._int8View; + } + get uint8View() { + if (!this._uint8View) { + this._uint8View = new Uint8Array(this.rawBinaryData); + } + return this._uint8View; + } + get int16View() { + if (!this._int16View) { + this._int16View = new Int16Array(this.rawBinaryData); + } + return this._int16View; + } + get uint16View() { + if (!this._uint16View) { + this._uint16View = new Uint16Array(this.rawBinaryData); + } + return this._uint16View; + } + get int32View() { + if (!this._int32View) { + this._int32View = new Int32Array(this.rawBinaryData); + } + return this._int32View; + } + view(type) { + return this[`${type}View`]; + } + destroy() { + this.rawBinaryData = null; + this._int8View = null; + this._uint8View = null; + this._int16View = null; + this._uint16View = null; + this._int32View = null; + this.uint32View = null; + this.float32View = null; + } + static sizeOf(type) { + switch (type) { + case "int8": + case "uint8": + return 1; + case "int16": + case "uint16": + return 2; + case "int32": + case "uint32": + case "float32": + return 4; + default: + throw new Error(`${type} isn't a valid view type`); + } + } + } + + const fragTemplate$1 = [ + "precision mediump float;", + "void main(void){", + "float test = 0.1;", + "%forloop%", + "gl_FragColor = vec4(0.0);", + "}" + ].join("\n"); + function generateIfTestSrc(maxIfs) { + let src = ""; + for (let i = 0; i < maxIfs; ++i) { + if (i > 0) { + src += "\nelse "; + } + if (i < maxIfs - 1) { + src += `if(test == ${i}.0){}`; + } + } + return src; + } + function checkMaxIfStatementsInShader(maxIfs, gl) { + if (maxIfs === 0) { + throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`"); + } + const shader = gl.createShader(gl.FRAGMENT_SHADER); + while (true) { + const fragmentSrc = fragTemplate$1.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + maxIfs = maxIfs / 2 | 0; + } else { + break; + } + } + return maxIfs; + } + + const BLEND$1 = 0; + const OFFSET$1 = 1; + const CULLING$1 = 2; + const DEPTH_TEST$1 = 3; + const WINDING$1 = 4; + const DEPTH_MASK$1 = 5; + class State { + constructor() { + this.data = 0; + this.blendMode = BLEND_MODES.NORMAL; + this.polygonOffset = 0; + this.blend = true; + this.depthMask = true; + } + get blend() { + return !!(this.data & 1 << BLEND$1); + } + set blend(value) { + if (!!(this.data & 1 << BLEND$1) !== value) { + this.data ^= 1 << BLEND$1; + } + } + get offsets() { + return !!(this.data & 1 << OFFSET$1); + } + set offsets(value) { + if (!!(this.data & 1 << OFFSET$1) !== value) { + this.data ^= 1 << OFFSET$1; + } + } + get culling() { + return !!(this.data & 1 << CULLING$1); + } + set culling(value) { + if (!!(this.data & 1 << CULLING$1) !== value) { + this.data ^= 1 << CULLING$1; + } + } + get depthTest() { + return !!(this.data & 1 << DEPTH_TEST$1); + } + set depthTest(value) { + if (!!(this.data & 1 << DEPTH_TEST$1) !== value) { + this.data ^= 1 << DEPTH_TEST$1; + } + } + get depthMask() { + return !!(this.data & 1 << DEPTH_MASK$1); + } + set depthMask(value) { + if (!!(this.data & 1 << DEPTH_MASK$1) !== value) { + this.data ^= 1 << DEPTH_MASK$1; + } + } + get clockwiseFrontFace() { + return !!(this.data & 1 << WINDING$1); + } + set clockwiseFrontFace(value) { + if (!!(this.data & 1 << WINDING$1) !== value) { + this.data ^= 1 << WINDING$1; + } + } + get blendMode() { + return this._blendMode; + } + set blendMode(value) { + this.blend = value !== BLEND_MODES.NONE; + this._blendMode = value; + } + get polygonOffset() { + return this._polygonOffset; + } + set polygonOffset(value) { + this.offsets = !!value; + this._polygonOffset = value; + } + toString() { + return `[@pixi/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`; + } + static for2d() { + const state = new State(); + state.depthTest = false; + state.blend = true; + return state; + } + } + + const INSTALLED = []; + function autoDetectResource(source, options) { + if (!source) { + return null; + } + let extension = ""; + if (typeof source === "string") { + const result = /\.(\w{3,4})(?:$|\?|#)/i.exec(source); + if (result) { + extension = result[1].toLowerCase(); + } + } + for (let i = INSTALLED.length - 1; i >= 0; --i) { + const ResourcePlugin = INSTALLED[i]; + if (ResourcePlugin.test && ResourcePlugin.test(source, extension)) { + return new ResourcePlugin(source, options); + } + } + throw new Error("Unrecognized source type to auto-detect Resource"); + } + + class Runner { + constructor(name) { + this.items = []; + this._name = name; + this._aliasCount = 0; + } + emit(a0, a1, a2, a3, a4, a5, a6, a7) { + if (arguments.length > 8) { + throw new Error("max arguments reached"); + } + const { name, items } = this; + this._aliasCount++; + for (let i = 0, len = items.length; i < len; i++) { + items[i][name](a0, a1, a2, a3, a4, a5, a6, a7); + } + if (items === this.items) { + this._aliasCount--; + } + return this; + } + ensureNonAliasedItems() { + if (this._aliasCount > 0 && this.items.length > 1) { + this._aliasCount = 0; + this.items = this.items.slice(0); + } + } + add(item) { + if (item[this._name]) { + this.ensureNonAliasedItems(); + this.remove(item); + this.items.push(item); + } + return this; + } + remove(item) { + const index = this.items.indexOf(item); + if (index !== -1) { + this.ensureNonAliasedItems(); + this.items.splice(index, 1); + } + return this; + } + contains(item) { + return this.items.includes(item); + } + removeAll() { + this.ensureNonAliasedItems(); + this.items.length = 0; + return this; + } + destroy() { + this.removeAll(); + this.items = null; + this._name = null; + } + get empty() { + return this.items.length === 0; + } + get name() { + return this._name; + } + } + Object.defineProperties(Runner.prototype, { + dispatch: { value: Runner.prototype.emit }, + run: { value: Runner.prototype.emit } + }); + + class Resource { + constructor(width = 0, height = 0) { + this._width = width; + this._height = height; + this.destroyed = false; + this.internal = false; + this.onResize = new Runner("setRealSize"); + this.onUpdate = new Runner("update"); + this.onError = new Runner("onError"); + } + bind(baseTexture) { + this.onResize.add(baseTexture); + this.onUpdate.add(baseTexture); + this.onError.add(baseTexture); + if (this._width || this._height) { + this.onResize.emit(this._width, this._height); + } + } + unbind(baseTexture) { + this.onResize.remove(baseTexture); + this.onUpdate.remove(baseTexture); + this.onError.remove(baseTexture); + } + resize(width, height) { + if (width !== this._width || height !== this._height) { + this._width = width; + this._height = height; + this.onResize.emit(width, height); + } + } + get valid() { + return !!this._width && !!this._height; + } + update() { + if (!this.destroyed) { + this.onUpdate.emit(); + } + } + load() { + return Promise.resolve(this); + } + get width() { + return this._width; + } + get height() { + return this._height; + } + style(_renderer, _baseTexture, _glTexture) { + return false; + } + dispose() { + } + destroy() { + if (!this.destroyed) { + this.destroyed = true; + this.dispose(); + this.onError.removeAll(); + this.onError = null; + this.onResize.removeAll(); + this.onResize = null; + this.onUpdate.removeAll(); + this.onUpdate = null; + } + } + static test(_source, _extension) { + return false; + } + } + + class BufferResource extends Resource { + constructor(source, options) { + const { width, height } = options || {}; + if (!width || !height) { + throw new Error("BufferResource width or height invalid"); + } + super(width, height); + this.data = source; + } + upload(renderer, baseTexture, glTexture) { + const gl = renderer.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === ALPHA_MODES.UNPACK); + const width = baseTexture.realWidth; + const height = baseTexture.realHeight; + if (glTexture.width === width && glTexture.height === height) { + gl.texSubImage2D(baseTexture.target, 0, 0, 0, width, height, baseTexture.format, glTexture.type, this.data); + } else { + glTexture.width = width; + glTexture.height = height; + gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, width, height, 0, baseTexture.format, glTexture.type, this.data); + } + return true; + } + dispose() { + this.data = null; + } + static test(source) { + return source instanceof Float32Array || source instanceof Uint8Array || source instanceof Uint32Array; + } + } + + const defaultBufferOptions = { + scaleMode: SCALE_MODES.NEAREST, + format: FORMATS.RGBA, + alphaMode: ALPHA_MODES.NPM + }; + const _BaseTexture = class extends eventemitter3 { + constructor(resource = null, options = null) { + super(); + options = Object.assign({}, _BaseTexture.defaultOptions, options); + const { + alphaMode, + mipmap, + anisotropicLevel, + scaleMode, + width, + height, + wrapMode, + format, + type, + target, + resolution, + resourceOptions + } = options; + if (resource && !(resource instanceof Resource)) { + resource = autoDetectResource(resource, resourceOptions); + resource.internal = true; + } + this.resolution = resolution || settings.RESOLUTION; + this.width = Math.round((width || 0) * this.resolution) / this.resolution; + this.height = Math.round((height || 0) * this.resolution) / this.resolution; + this._mipmap = mipmap; + this.anisotropicLevel = anisotropicLevel; + this._wrapMode = wrapMode; + this._scaleMode = scaleMode; + this.format = format; + this.type = type; + this.target = target; + this.alphaMode = alphaMode; + this.uid = uid(); + this.touched = 0; + this.isPowerOfTwo = false; + this._refreshPOT(); + this._glTextures = {}; + this.dirtyId = 0; + this.dirtyStyleId = 0; + this.cacheId = null; + this.valid = width > 0 && height > 0; + this.textureCacheIds = []; + this.destroyed = false; + this.resource = null; + this._batchEnabled = 0; + this._batchLocation = 0; + this.parentTextureArray = null; + this.setResource(resource); + } + get realWidth() { + return Math.round(this.width * this.resolution); + } + get realHeight() { + return Math.round(this.height * this.resolution); + } + get mipmap() { + return this._mipmap; + } + set mipmap(value) { + if (this._mipmap !== value) { + this._mipmap = value; + this.dirtyStyleId++; + } + } + get scaleMode() { + return this._scaleMode; + } + set scaleMode(value) { + if (this._scaleMode !== value) { + this._scaleMode = value; + this.dirtyStyleId++; + } + } + get wrapMode() { + return this._wrapMode; + } + set wrapMode(value) { + if (this._wrapMode !== value) { + this._wrapMode = value; + this.dirtyStyleId++; + } + } + setStyle(scaleMode, mipmap) { + let dirty; + if (scaleMode !== void 0 && scaleMode !== this.scaleMode) { + this.scaleMode = scaleMode; + dirty = true; + } + if (mipmap !== void 0 && mipmap !== this.mipmap) { + this.mipmap = mipmap; + dirty = true; + } + if (dirty) { + this.dirtyStyleId++; + } + return this; + } + setSize(desiredWidth, desiredHeight, resolution) { + resolution = resolution || this.resolution; + return this.setRealSize(desiredWidth * resolution, desiredHeight * resolution, resolution); + } + setRealSize(realWidth, realHeight, resolution) { + this.resolution = resolution || this.resolution; + this.width = Math.round(realWidth) / this.resolution; + this.height = Math.round(realHeight) / this.resolution; + this._refreshPOT(); + this.update(); + return this; + } + _refreshPOT() { + this.isPowerOfTwo = isPow2(this.realWidth) && isPow2(this.realHeight); + } + setResolution(resolution) { + const oldResolution = this.resolution; + if (oldResolution === resolution) { + return this; + } + this.resolution = resolution; + if (this.valid) { + this.width = Math.round(this.width * oldResolution) / resolution; + this.height = Math.round(this.height * oldResolution) / resolution; + this.emit("update", this); + } + this._refreshPOT(); + return this; + } + setResource(resource) { + if (this.resource === resource) { + return this; + } + if (this.resource) { + throw new Error("Resource can be set only once"); + } + resource.bind(this); + this.resource = resource; + return this; + } + update() { + if (!this.valid) { + if (this.width > 0 && this.height > 0) { + this.valid = true; + this.emit("loaded", this); + this.emit("update", this); + } + } else { + this.dirtyId++; + this.dirtyStyleId++; + this.emit("update", this); + } + } + onError(event) { + this.emit("error", this, event); + } + destroy() { + if (this.resource) { + this.resource.unbind(this); + if (this.resource.internal) { + this.resource.destroy(); + } + this.resource = null; + } + if (this.cacheId) { + delete BaseTextureCache[this.cacheId]; + delete TextureCache[this.cacheId]; + this.cacheId = null; + } + this.dispose(); + _BaseTexture.removeFromCache(this); + this.textureCacheIds = null; + this.destroyed = true; + } + dispose() { + this.emit("dispose", this); + } + castToBaseTexture() { + return this; + } + static from(source, options, strict = settings.STRICT_TEXTURE_CACHE) { + const isFrame = typeof source === "string"; + let cacheId = null; + if (isFrame) { + cacheId = source; + } else { + if (!source._pixiId) { + const prefix = options?.pixiIdPrefix || "pixiid"; + source._pixiId = `${prefix}_${uid()}`; + } + cacheId = source._pixiId; + } + let baseTexture = BaseTextureCache[cacheId]; + if (isFrame && strict && !baseTexture) { + throw new Error(`The cacheId "${cacheId}" does not exist in BaseTextureCache.`); + } + if (!baseTexture) { + baseTexture = new _BaseTexture(source, options); + baseTexture.cacheId = cacheId; + _BaseTexture.addToCache(baseTexture, cacheId); + } + return baseTexture; + } + static fromBuffer(buffer, width, height, options) { + buffer = buffer || new Float32Array(width * height * 4); + const resource = new BufferResource(buffer, { width, height }); + const type = buffer instanceof Float32Array ? TYPES.FLOAT : TYPES.UNSIGNED_BYTE; + return new _BaseTexture(resource, Object.assign({}, defaultBufferOptions, { type }, options)); + } + static addToCache(baseTexture, id) { + if (id) { + if (!baseTexture.textureCacheIds.includes(id)) { + baseTexture.textureCacheIds.push(id); + } + if (BaseTextureCache[id] && BaseTextureCache[id] !== baseTexture) { + console.warn(`BaseTexture added to the cache with an id [${id}] that already had an entry`); + } + BaseTextureCache[id] = baseTexture; + } + } + static removeFromCache(baseTexture) { + if (typeof baseTexture === "string") { + const baseTextureFromCache = BaseTextureCache[baseTexture]; + if (baseTextureFromCache) { + const index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture); + if (index > -1) { + baseTextureFromCache.textureCacheIds.splice(index, 1); + } + delete BaseTextureCache[baseTexture]; + return baseTextureFromCache; + } + } else if (baseTexture?.textureCacheIds) { + for (let i = 0; i < baseTexture.textureCacheIds.length; ++i) { + delete BaseTextureCache[baseTexture.textureCacheIds[i]]; + } + baseTexture.textureCacheIds.length = 0; + return baseTexture; + } + return null; + } + }; + let BaseTexture = _BaseTexture; + BaseTexture.defaultOptions = { + mipmap: MIPMAP_MODES.POW2, + anisotropicLevel: 0, + scaleMode: SCALE_MODES.LINEAR, + wrapMode: WRAP_MODES.CLAMP, + alphaMode: ALPHA_MODES.UNPACK, + target: TARGETS.TEXTURE_2D, + format: FORMATS.RGBA, + type: TYPES.UNSIGNED_BYTE + }; + BaseTexture._globalBatch = 0; + + class BatchDrawCall { + constructor() { + this.texArray = null; + this.blend = 0; + this.type = DRAW_MODES.TRIANGLES; + this.start = 0; + this.size = 0; + this.data = null; + } + } + + let UID$4 = 0; + class Buffer { + constructor(data, _static = true, index = false) { + this.data = data || new Float32Array(1); + this._glBuffers = {}; + this._updateID = 0; + this.index = index; + this.static = _static; + this.id = UID$4++; + this.disposeRunner = new Runner("disposeBuffer"); + } + update(data) { + if (data instanceof Array) { + data = new Float32Array(data); + } + this.data = data || this.data; + this._updateID++; + } + dispose() { + this.disposeRunner.emit(this, false); + } + destroy() { + this.dispose(); + this.data = null; + } + set index(value) { + this.type = value ? BUFFER_TYPE.ELEMENT_ARRAY_BUFFER : BUFFER_TYPE.ARRAY_BUFFER; + } + get index() { + return this.type === BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; + } + static from(data) { + if (data instanceof Array) { + data = new Float32Array(data); + } + return new Buffer(data); + } + } + + class Attribute { + constructor(buffer, size = 0, normalized = false, type = TYPES.FLOAT, stride, start, instance, divisor = 1) { + this.buffer = buffer; + this.size = size; + this.normalized = normalized; + this.type = type; + this.stride = stride; + this.start = start; + this.instance = instance; + this.divisor = divisor; + } + destroy() { + this.buffer = null; + } + static from(buffer, size, normalized, type, stride) { + return new Attribute(buffer, size, normalized, type, stride); + } + } + + const map$1 = { + Float32Array, + Uint32Array, + Int32Array, + Uint8Array + }; + function interleaveTypedArrays(arrays, sizes) { + let outSize = 0; + let stride = 0; + const views = {}; + for (let i = 0; i < arrays.length; i++) { + stride += sizes[i]; + outSize += arrays[i].length; + } + const buffer = new ArrayBuffer(outSize * 4); + let out = null; + let littleOffset = 0; + for (let i = 0; i < arrays.length; i++) { + const size = sizes[i]; + const array = arrays[i]; + const type = getBufferType(array); + if (!views[type]) { + views[type] = new map$1[type](buffer); + } + out = views[type]; + for (let j = 0; j < array.length; j++) { + const indexStart = (j / size | 0) * stride + littleOffset; + const index = j % size; + out[indexStart + index] = array[j]; + } + littleOffset += size; + } + return new Float32Array(buffer); + } + + const byteSizeMap$1 = { 5126: 4, 5123: 2, 5121: 1 }; + let UID$3 = 0; + const map = { + Float32Array, + Uint32Array, + Int32Array, + Uint8Array, + Uint16Array + }; + class Geometry { + constructor(buffers = [], attributes = {}) { + this.buffers = buffers; + this.indexBuffer = null; + this.attributes = attributes; + this.glVertexArrayObjects = {}; + this.id = UID$3++; + this.instanced = false; + this.instanceCount = 1; + this.disposeRunner = new Runner("disposeGeometry"); + this.refCount = 0; + } + addAttribute(id, buffer, size = 0, normalized = false, type, stride, start, instance = false) { + if (!buffer) { + throw new Error("You must pass a buffer when creating an attribute"); + } + if (!(buffer instanceof Buffer)) { + if (buffer instanceof Array) { + buffer = new Float32Array(buffer); + } + buffer = new Buffer(buffer); + } + const ids = id.split("|"); + if (ids.length > 1) { + for (let i = 0; i < ids.length; i++) { + this.addAttribute(ids[i], buffer, size, normalized, type); + } + return this; + } + let bufferIndex = this.buffers.indexOf(buffer); + if (bufferIndex === -1) { + this.buffers.push(buffer); + bufferIndex = this.buffers.length - 1; + } + this.attributes[id] = new Attribute(bufferIndex, size, normalized, type, stride, start, instance); + this.instanced = this.instanced || instance; + return this; + } + getAttribute(id) { + return this.attributes[id]; + } + getBuffer(id) { + return this.buffers[this.getAttribute(id).buffer]; + } + addIndex(buffer) { + if (!(buffer instanceof Buffer)) { + if (buffer instanceof Array) { + buffer = new Uint16Array(buffer); + } + buffer = new Buffer(buffer); + } + buffer.type = BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; + this.indexBuffer = buffer; + if (!this.buffers.includes(buffer)) { + this.buffers.push(buffer); + } + return this; + } + getIndex() { + return this.indexBuffer; + } + interleave() { + if (this.buffers.length === 1 || this.buffers.length === 2 && this.indexBuffer) + return this; + const arrays = []; + const sizes = []; + const interleavedBuffer = new Buffer(); + let i; + for (i in this.attributes) { + const attribute = this.attributes[i]; + const buffer = this.buffers[attribute.buffer]; + arrays.push(buffer.data); + sizes.push(attribute.size * byteSizeMap$1[attribute.type] / 4); + attribute.buffer = 0; + } + interleavedBuffer.data = interleaveTypedArrays(arrays, sizes); + for (i = 0; i < this.buffers.length; i++) { + if (this.buffers[i] !== this.indexBuffer) { + this.buffers[i].destroy(); + } + } + this.buffers = [interleavedBuffer]; + if (this.indexBuffer) { + this.buffers.push(this.indexBuffer); + } + return this; + } + getSize() { + for (const i in this.attributes) { + const attribute = this.attributes[i]; + const buffer = this.buffers[attribute.buffer]; + return buffer.data.length / (attribute.stride / 4 || attribute.size); + } + return 0; + } + dispose() { + this.disposeRunner.emit(this, false); + } + destroy() { + this.dispose(); + this.buffers = null; + this.indexBuffer = null; + this.attributes = null; + } + clone() { + const geometry = new Geometry(); + for (let i = 0; i < this.buffers.length; i++) { + geometry.buffers[i] = new Buffer(this.buffers[i].data.slice(0)); + } + for (const i in this.attributes) { + const attrib = this.attributes[i]; + geometry.attributes[i] = new Attribute(attrib.buffer, attrib.size, attrib.normalized, attrib.type, attrib.stride, attrib.start, attrib.instance); + } + if (this.indexBuffer) { + geometry.indexBuffer = geometry.buffers[this.buffers.indexOf(this.indexBuffer)]; + geometry.indexBuffer.type = BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; + } + return geometry; + } + static merge(geometries) { + const geometryOut = new Geometry(); + const arrays = []; + const sizes = []; + const offsets = []; + let geometry; + for (let i = 0; i < geometries.length; i++) { + geometry = geometries[i]; + for (let j = 0; j < geometry.buffers.length; j++) { + sizes[j] = sizes[j] || 0; + sizes[j] += geometry.buffers[j].data.length; + offsets[j] = 0; + } + } + for (let i = 0; i < geometry.buffers.length; i++) { + arrays[i] = new map[getBufferType(geometry.buffers[i].data)](sizes[i]); + geometryOut.buffers[i] = new Buffer(arrays[i]); + } + for (let i = 0; i < geometries.length; i++) { + geometry = geometries[i]; + for (let j = 0; j < geometry.buffers.length; j++) { + arrays[j].set(geometry.buffers[j].data, offsets[j]); + offsets[j] += geometry.buffers[j].data.length; + } + } + geometryOut.attributes = geometry.attributes; + if (geometry.indexBuffer) { + geometryOut.indexBuffer = geometryOut.buffers[geometry.buffers.indexOf(geometry.indexBuffer)]; + geometryOut.indexBuffer.type = BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; + let offset = 0; + let stride = 0; + let offset2 = 0; + let bufferIndexToCount = 0; + for (let i = 0; i < geometry.buffers.length; i++) { + if (geometry.buffers[i] !== geometry.indexBuffer) { + bufferIndexToCount = i; + break; + } + } + for (const i in geometry.attributes) { + const attribute = geometry.attributes[i]; + if ((attribute.buffer | 0) === bufferIndexToCount) { + stride += attribute.size * byteSizeMap$1[attribute.type] / 4; + } + } + for (let i = 0; i < geometries.length; i++) { + const indexBufferData = geometries[i].indexBuffer.data; + for (let j = 0; j < indexBufferData.length; j++) { + geometryOut.indexBuffer.data[j + offset2] += offset; + } + offset += geometries[i].buffers[bufferIndexToCount].data.length / stride; + offset2 += indexBufferData.length; + } + } + return geometryOut; + } + } + + class BatchGeometry extends Geometry { + constructor(_static = false) { + super(); + this._buffer = new Buffer(null, _static, false); + this._indexBuffer = new Buffer(null, _static, true); + this.addAttribute("aVertexPosition", this._buffer, 2, false, TYPES.FLOAT).addAttribute("aTextureCoord", this._buffer, 2, false, TYPES.FLOAT).addAttribute("aColor", this._buffer, 4, true, TYPES.UNSIGNED_BYTE).addAttribute("aTextureId", this._buffer, 1, true, TYPES.FLOAT).addIndex(this._indexBuffer); + } + } + + const PI_2 = Math.PI * 2; + const RAD_TO_DEG = 180 / Math.PI; + const DEG_TO_RAD = Math.PI / 180; + var SHAPES = /* @__PURE__ */ ((SHAPES2) => { + SHAPES2[SHAPES2["POLY"] = 0] = "POLY"; + SHAPES2[SHAPES2["RECT"] = 1] = "RECT"; + SHAPES2[SHAPES2["CIRC"] = 2] = "CIRC"; + SHAPES2[SHAPES2["ELIP"] = 3] = "ELIP"; + SHAPES2[SHAPES2["RREC"] = 4] = "RREC"; + return SHAPES2; + })(SHAPES || {}); + + class Point { + constructor(x = 0, y = 0) { + this.x = 0; + this.y = 0; + this.x = x; + this.y = y; + } + clone() { + return new Point(this.x, this.y); + } + copyFrom(p) { + this.set(p.x, p.y); + return this; + } + copyTo(p) { + p.set(this.x, this.y); + return p; + } + equals(p) { + return p.x === this.x && p.y === this.y; + } + set(x = 0, y = x) { + this.x = x; + this.y = y; + return this; + } + toString() { + return `[@pixi/math:Point x=${this.x} y=${this.y}]`; + } + } + + const tempPoints$1 = [new Point(), new Point(), new Point(), new Point()]; + class Rectangle { + constructor(x = 0, y = 0, width = 0, height = 0) { + this.x = Number(x); + this.y = Number(y); + this.width = Number(width); + this.height = Number(height); + this.type = SHAPES.RECT; + } + get left() { + return this.x; + } + get right() { + return this.x + this.width; + } + get top() { + return this.y; + } + get bottom() { + return this.y + this.height; + } + static get EMPTY() { + return new Rectangle(0, 0, 0, 0); + } + clone() { + return new Rectangle(this.x, this.y, this.width, this.height); + } + copyFrom(rectangle) { + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + return this; + } + copyTo(rectangle) { + rectangle.x = this.x; + rectangle.y = this.y; + rectangle.width = this.width; + rectangle.height = this.height; + return rectangle; + } + contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x < this.x + this.width) { + if (y >= this.y && y < this.y + this.height) { + return true; + } + } + return false; + } + intersects(other, transform) { + if (!transform) { + const x02 = this.x < other.x ? other.x : this.x; + const x12 = this.right > other.right ? other.right : this.right; + if (x12 <= x02) { + return false; + } + const y02 = this.y < other.y ? other.y : this.y; + const y12 = this.bottom > other.bottom ? other.bottom : this.bottom; + return y12 > y02; + } + const x0 = this.left; + const x1 = this.right; + const y0 = this.top; + const y1 = this.bottom; + if (x1 <= x0 || y1 <= y0) { + return false; + } + const lt = tempPoints$1[0].set(other.left, other.top); + const lb = tempPoints$1[1].set(other.left, other.bottom); + const rt = tempPoints$1[2].set(other.right, other.top); + const rb = tempPoints$1[3].set(other.right, other.bottom); + if (rt.x <= lt.x || lb.y <= lt.y) { + return false; + } + const s = Math.sign(transform.a * transform.d - transform.b * transform.c); + if (s === 0) { + return false; + } + transform.apply(lt, lt); + transform.apply(lb, lb); + transform.apply(rt, rt); + transform.apply(rb, rb); + if (Math.max(lt.x, lb.x, rt.x, rb.x) <= x0 || Math.min(lt.x, lb.x, rt.x, rb.x) >= x1 || Math.max(lt.y, lb.y, rt.y, rb.y) <= y0 || Math.min(lt.y, lb.y, rt.y, rb.y) >= y1) { + return false; + } + const nx = s * (lb.y - lt.y); + const ny = s * (lt.x - lb.x); + const n00 = nx * x0 + ny * y0; + const n10 = nx * x1 + ny * y0; + const n01 = nx * x0 + ny * y1; + const n11 = nx * x1 + ny * y1; + if (Math.max(n00, n10, n01, n11) <= nx * lt.x + ny * lt.y || Math.min(n00, n10, n01, n11) >= nx * rb.x + ny * rb.y) { + return false; + } + const mx = s * (lt.y - rt.y); + const my = s * (rt.x - lt.x); + const m00 = mx * x0 + my * y0; + const m10 = mx * x1 + my * y0; + const m01 = mx * x0 + my * y1; + const m11 = mx * x1 + my * y1; + if (Math.max(m00, m10, m01, m11) <= mx * lt.x + my * lt.y || Math.min(m00, m10, m01, m11) >= mx * rb.x + my * rb.y) { + return false; + } + return true; + } + pad(paddingX = 0, paddingY = paddingX) { + this.x -= paddingX; + this.y -= paddingY; + this.width += paddingX * 2; + this.height += paddingY * 2; + return this; + } + fit(rectangle) { + const x1 = Math.max(this.x, rectangle.x); + const x2 = Math.min(this.x + this.width, rectangle.x + rectangle.width); + const y1 = Math.max(this.y, rectangle.y); + const y2 = Math.min(this.y + this.height, rectangle.y + rectangle.height); + this.x = x1; + this.width = Math.max(x2 - x1, 0); + this.y = y1; + this.height = Math.max(y2 - y1, 0); + return this; + } + ceil(resolution = 1, eps = 1e-3) { + const x2 = Math.ceil((this.x + this.width - eps) * resolution) / resolution; + const y2 = Math.ceil((this.y + this.height - eps) * resolution) / resolution; + this.x = Math.floor((this.x + eps) * resolution) / resolution; + this.y = Math.floor((this.y + eps) * resolution) / resolution; + this.width = x2 - this.x; + this.height = y2 - this.y; + return this; + } + enlarge(rectangle) { + const x1 = Math.min(this.x, rectangle.x); + const x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); + const y1 = Math.min(this.y, rectangle.y); + const y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; + return this; + } + toString() { + return `[@pixi/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`; + } + } + + class Circle { + constructor(x = 0, y = 0, radius = 0) { + this.x = x; + this.y = y; + this.radius = radius; + this.type = SHAPES.CIRC; + } + clone() { + return new Circle(this.x, this.y, this.radius); + } + contains(x, y) { + if (this.radius <= 0) { + return false; + } + const r2 = this.radius * this.radius; + let dx = this.x - x; + let dy = this.y - y; + dx *= dx; + dy *= dy; + return dx + dy <= r2; + } + getBounds() { + return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); + } + toString() { + return `[@pixi/math:Circle x=${this.x} y=${this.y} radius=${this.radius}]`; + } + } + + class Ellipse { + constructor(x = 0, y = 0, halfWidth = 0, halfHeight = 0) { + this.x = x; + this.y = y; + this.width = halfWidth; + this.height = halfHeight; + this.type = SHAPES.ELIP; + } + clone() { + return new Ellipse(this.x, this.y, this.width, this.height); + } + contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + let normx = (x - this.x) / this.width; + let normy = (y - this.y) / this.height; + normx *= normx; + normy *= normy; + return normx + normy <= 1; + } + getBounds() { + return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); + } + toString() { + return `[@pixi/math:Ellipse x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`; + } + } + + class Polygon { + constructor(...points) { + let flat = Array.isArray(points[0]) ? points[0] : points; + if (typeof flat[0] !== "number") { + const p = []; + for (let i = 0, il = flat.length; i < il; i++) { + p.push(flat[i].x, flat[i].y); + } + flat = p; + } + this.points = flat; + this.type = SHAPES.POLY; + this.closeStroke = true; + } + clone() { + const points = this.points.slice(); + const polygon = new Polygon(points); + polygon.closeStroke = this.closeStroke; + return polygon; + } + contains(x, y) { + let inside = false; + const length = this.points.length / 2; + for (let i = 0, j = length - 1; i < length; j = i++) { + const xi = this.points[i * 2]; + const yi = this.points[i * 2 + 1]; + const xj = this.points[j * 2]; + const yj = this.points[j * 2 + 1]; + const intersect = yi > y !== yj > y && x < (xj - xi) * ((y - yi) / (yj - yi)) + xi; + if (intersect) { + inside = !inside; + } + } + return inside; + } + toString() { + return `[@pixi/math:PolygoncloseStroke=${this.closeStroke}points=${this.points.reduce((pointsDesc, currentPoint) => `${pointsDesc}, ${currentPoint}`, "")}]`; + } + } + + class RoundedRectangle { + constructor(x = 0, y = 0, width = 0, height = 0, radius = 20) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + this.radius = radius; + this.type = SHAPES.RREC; + } + clone() { + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + } + contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x <= this.x + this.width) { + if (y >= this.y && y <= this.y + this.height) { + const radius = Math.max(0, Math.min(this.radius, Math.min(this.width, this.height) / 2)); + if (y >= this.y + radius && y <= this.y + this.height - radius || x >= this.x + radius && x <= this.x + this.width - radius) { + return true; + } + let dx = x - (this.x + radius); + let dy = y - (this.y + radius); + const radius2 = radius * radius; + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.width - radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dy = y - (this.y + this.height - radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + } + } + return false; + } + toString() { + return `[@pixi/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`; + } + } + + class Matrix { + constructor(a = 1, b = 0, c = 0, d = 1, tx = 0, ty = 0) { + this.array = null; + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + } + fromArray(array) { + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; + } + set(a, b, c, d, tx, ty) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + return this; + } + toArray(transpose, out) { + if (!this.array) { + this.array = new Float32Array(9); + } + const array = out || this.array; + if (transpose) { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } else { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + return array; + } + apply(pos, newPos) { + newPos = newPos || new Point(); + const x = pos.x; + const y = pos.y; + newPos.x = this.a * x + this.c * y + this.tx; + newPos.y = this.b * x + this.d * y + this.ty; + return newPos; + } + applyInverse(pos, newPos) { + newPos = newPos || new Point(); + const id = 1 / (this.a * this.d + this.c * -this.b); + const x = pos.x; + const y = pos.y; + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + return newPos; + } + translate(x, y) { + this.tx += x; + this.ty += y; + return this; + } + scale(x, y) { + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + return this; + } + rotate(angle) { + const cos = Math.cos(angle); + const sin = Math.sin(angle); + const a1 = this.a; + const c1 = this.c; + const tx1 = this.tx; + this.a = a1 * cos - this.b * sin; + this.b = a1 * sin + this.b * cos; + this.c = c1 * cos - this.d * sin; + this.d = c1 * sin + this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + return this; + } + append(matrix) { + const a1 = this.a; + const b1 = this.b; + const c1 = this.c; + const d1 = this.d; + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + return this; + } + setTransform(x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { + this.a = Math.cos(rotation + skewY) * scaleX; + this.b = Math.sin(rotation + skewY) * scaleX; + this.c = -Math.sin(rotation - skewX) * scaleY; + this.d = Math.cos(rotation - skewX) * scaleY; + this.tx = x - (pivotX * this.a + pivotY * this.c); + this.ty = y - (pivotX * this.b + pivotY * this.d); + return this; + } + prepend(matrix) { + const tx1 = this.tx; + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { + const a1 = this.a; + const c1 = this.c; + this.a = a1 * matrix.a + this.b * matrix.c; + this.b = a1 * matrix.b + this.b * matrix.d; + this.c = c1 * matrix.a + this.d * matrix.c; + this.d = c1 * matrix.b + this.d * matrix.d; + } + this.tx = tx1 * matrix.a + this.ty * matrix.c + matrix.tx; + this.ty = tx1 * matrix.b + this.ty * matrix.d + matrix.ty; + return this; + } + decompose(transform) { + const a = this.a; + const b = this.b; + const c = this.c; + const d = this.d; + const pivot = transform.pivot; + const skewX = -Math.atan2(-c, d); + const skewY = Math.atan2(b, a); + const delta = Math.abs(skewX + skewY); + if (delta < 1e-5 || Math.abs(PI_2 - delta) < 1e-5) { + transform.rotation = skewY; + transform.skew.x = transform.skew.y = 0; + } else { + transform.rotation = 0; + transform.skew.x = skewX; + transform.skew.y = skewY; + } + transform.scale.x = Math.sqrt(a * a + b * b); + transform.scale.y = Math.sqrt(c * c + d * d); + transform.position.x = this.tx + (pivot.x * a + pivot.y * c); + transform.position.y = this.ty + (pivot.x * b + pivot.y * d); + return transform; + } + invert() { + const a1 = this.a; + const b1 = this.b; + const c1 = this.c; + const d1 = this.d; + const tx1 = this.tx; + const n = a1 * d1 - b1 * c1; + this.a = d1 / n; + this.b = -b1 / n; + this.c = -c1 / n; + this.d = a1 / n; + this.tx = (c1 * this.ty - d1 * tx1) / n; + this.ty = -(a1 * this.ty - b1 * tx1) / n; + return this; + } + identity() { + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + return this; + } + clone() { + const matrix = new Matrix(); + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + return matrix; + } + copyTo(matrix) { + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + return matrix; + } + copyFrom(matrix) { + this.a = matrix.a; + this.b = matrix.b; + this.c = matrix.c; + this.d = matrix.d; + this.tx = matrix.tx; + this.ty = matrix.ty; + return this; + } + toString() { + return `[@pixi/math:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`; + } + static get IDENTITY() { + return new Matrix(); + } + static get TEMP_MATRIX() { + return new Matrix(); + } + } + + const ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; + const uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; + const vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; + const vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; + const rotationCayley = []; + const rotationMatrices = []; + const signum = Math.sign; + function init() { + for (let i = 0; i < 16; i++) { + const row = []; + rotationCayley.push(row); + for (let j = 0; j < 16; j++) { + const _ux = signum(ux[i] * ux[j] + vx[i] * uy[j]); + const _uy = signum(uy[i] * ux[j] + vy[i] * uy[j]); + const _vx = signum(ux[i] * vx[j] + vx[i] * vy[j]); + const _vy = signum(uy[i] * vx[j] + vy[i] * vy[j]); + for (let k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } + for (let i = 0; i < 16; i++) { + const mat = new Matrix(); + mat.set(ux[i], uy[i], vx[i], vy[i], 0, 0); + rotationMatrices.push(mat); + } + } + init(); + const groupD8 = { + E: 0, + SE: 1, + S: 2, + SW: 3, + W: 4, + NW: 5, + N: 6, + NE: 7, + MIRROR_VERTICAL: 8, + MAIN_DIAGONAL: 10, + MIRROR_HORIZONTAL: 12, + REVERSE_DIAGONAL: 14, + uX: (ind) => ux[ind], + uY: (ind) => uy[ind], + vX: (ind) => vx[ind], + vY: (ind) => vy[ind], + inv: (rotation) => { + if (rotation & 8) { + return rotation & 15; + } + return -rotation & 7; + }, + add: (rotationSecond, rotationFirst) => rotationCayley[rotationSecond][rotationFirst], + sub: (rotationSecond, rotationFirst) => rotationCayley[rotationSecond][groupD8.inv(rotationFirst)], + rotate180: (rotation) => rotation ^ 4, + isVertical: (rotation) => (rotation & 3) === 2, + byDirection: (dx, dy) => { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return groupD8.S; + } + return groupD8.N; + } else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return groupD8.E; + } + return groupD8.W; + } else if (dy > 0) { + if (dx > 0) { + return groupD8.SE; + } + return groupD8.SW; + } else if (dx > 0) { + return groupD8.NE; + } + return groupD8.NW; + }, + matrixAppendRotationInv: (matrix, rotation, tx = 0, ty = 0) => { + const mat = rotationMatrices[groupD8.inv(rotation)]; + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + } + }; + + class ObservablePoint { + constructor(cb, scope, x = 0, y = 0) { + this._x = x; + this._y = y; + this.cb = cb; + this.scope = scope; + } + clone(cb = this.cb, scope = this.scope) { + return new ObservablePoint(cb, scope, this._x, this._y); + } + set(x = 0, y = x) { + if (this._x !== x || this._y !== y) { + this._x = x; + this._y = y; + this.cb.call(this.scope); + } + return this; + } + copyFrom(p) { + if (this._x !== p.x || this._y !== p.y) { + this._x = p.x; + this._y = p.y; + this.cb.call(this.scope); + } + return this; + } + copyTo(p) { + p.set(this._x, this._y); + return p; + } + equals(p) { + return p.x === this._x && p.y === this._y; + } + toString() { + return `[@pixi/math:ObservablePoint x=${0} y=${0} scope=${this.scope}]`; + } + get x() { + return this._x; + } + set x(value) { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + } + get y() { + return this._y; + } + set y(value) { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + } + } + + const _Transform = class { + constructor() { + this.worldTransform = new Matrix(); + this.localTransform = new Matrix(); + this.position = new ObservablePoint(this.onChange, this, 0, 0); + this.scale = new ObservablePoint(this.onChange, this, 1, 1); + this.pivot = new ObservablePoint(this.onChange, this, 0, 0); + this.skew = new ObservablePoint(this.updateSkew, this, 0, 0); + this._rotation = 0; + this._cx = 1; + this._sx = 0; + this._cy = 0; + this._sy = 1; + this._localID = 0; + this._currentLocalID = 0; + this._worldID = 0; + this._parentID = 0; + } + onChange() { + this._localID++; + } + updateSkew() { + this._cx = Math.cos(this._rotation + this.skew.y); + this._sx = Math.sin(this._rotation + this.skew.y); + this._cy = -Math.sin(this._rotation - this.skew.x); + this._sy = Math.cos(this._rotation - this.skew.x); + this._localID++; + } + toString() { + return `[@pixi/math:Transform position=(${this.position.x}, ${this.position.y}) rotation=${this.rotation} scale=(${this.scale.x}, ${this.scale.y}) skew=(${this.skew.x}, ${this.skew.y}) ]`; + } + updateLocalTransform() { + const lt = this.localTransform; + if (this._localID !== this._currentLocalID) { + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + this._currentLocalID = this._localID; + this._parentID = -1; + } + } + updateTransform(parentTransform) { + const lt = this.localTransform; + if (this._localID !== this._currentLocalID) { + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + this._currentLocalID = this._localID; + this._parentID = -1; + } + if (this._parentID !== parentTransform._worldID) { + const pt = parentTransform.worldTransform; + const wt = this.worldTransform; + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + this._parentID = parentTransform._worldID; + this._worldID++; + } + } + setFromMatrix(matrix) { + matrix.decompose(this); + this._localID++; + } + get rotation() { + return this._rotation; + } + set rotation(value) { + if (this._rotation !== value) { + this._rotation = value; + this.updateSkew(); + } + } + }; + let Transform = _Transform; + Transform.IDENTITY = new _Transform(); + + var defaultFragment$2 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor *= texture2D(uSampler, vTextureCoord);\n}"; + + var defaultVertex$3 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}\n"; + + function compileShader(gl, type, src) { + const shader = gl.createShader(type); + gl.shaderSource(shader, src); + gl.compileShader(shader); + return shader; + } + + function booleanArray(size) { + const array = new Array(size); + for (let i = 0; i < array.length; i++) { + array[i] = false; + } + return array; + } + function defaultValue(type, size) { + switch (type) { + case "float": + return 0; + case "vec2": + return new Float32Array(2 * size); + case "vec3": + return new Float32Array(3 * size); + case "vec4": + return new Float32Array(4 * size); + case "int": + case "uint": + case "sampler2D": + case "sampler2DArray": + return 0; + case "ivec2": + return new Int32Array(2 * size); + case "ivec3": + return new Int32Array(3 * size); + case "ivec4": + return new Int32Array(4 * size); + case "uvec2": + return new Uint32Array(2 * size); + case "uvec3": + return new Uint32Array(3 * size); + case "uvec4": + return new Uint32Array(4 * size); + case "bool": + return false; + case "bvec2": + return booleanArray(2 * size); + case "bvec3": + return booleanArray(3 * size); + case "bvec4": + return booleanArray(4 * size); + case "mat2": + return new Float32Array([ + 1, + 0, + 0, + 1 + ]); + case "mat3": + return new Float32Array([ + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1 + ]); + case "mat4": + return new Float32Array([ + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ]); + } + return null; + } + + const uniformParsers = [ + { + test: (data) => data.type === "float" && data.size === 1 && !data.isArray, + code: (name) => ` + if(uv["${name}"] !== ud["${name}"].value) + { + ud["${name}"].value = uv["${name}"] + gl.uniform1f(ud["${name}"].location, uv["${name}"]) + } + ` + }, + { + test: (data, uniform) => (data.type === "sampler2D" || data.type === "samplerCube" || data.type === "sampler2DArray") && data.size === 1 && !data.isArray && (uniform == null || uniform.castToBaseTexture !== void 0), + code: (name) => `t = syncData.textureCount++; + + renderer.texture.bind(uv["${name}"], t); + + if(ud["${name}"].value !== t) + { + ud["${name}"].value = t; + gl.uniform1i(ud["${name}"].location, t); +; // eslint-disable-line max-len + }` + }, + { + test: (data, uniform) => data.type === "mat3" && data.size === 1 && !data.isArray && uniform.a !== void 0, + code: (name) => ` + gl.uniformMatrix3fv(ud["${name}"].location, false, uv["${name}"].toArray(true)); + `, + codeUbo: (name) => ` + var ${name}_matrix = uv.${name}.toArray(true); + + data[offset] = ${name}_matrix[0]; + data[offset+1] = ${name}_matrix[1]; + data[offset+2] = ${name}_matrix[2]; + + data[offset + 4] = ${name}_matrix[3]; + data[offset + 5] = ${name}_matrix[4]; + data[offset + 6] = ${name}_matrix[5]; + + data[offset + 8] = ${name}_matrix[6]; + data[offset + 9] = ${name}_matrix[7]; + data[offset + 10] = ${name}_matrix[8]; + ` + }, + { + test: (data, uniform) => data.type === "vec2" && data.size === 1 && !data.isArray && uniform.x !== void 0, + code: (name) => ` + cv = ud["${name}"].value; + v = uv["${name}"]; + + if(cv[0] !== v.x || cv[1] !== v.y) + { + cv[0] = v.x; + cv[1] = v.y; + gl.uniform2f(ud["${name}"].location, v.x, v.y); + }`, + codeUbo: (name) => ` + v = uv.${name}; + + data[offset] = v.x; + data[offset+1] = v.y; + ` + }, + { + test: (data) => data.type === "vec2" && data.size === 1 && !data.isArray, + code: (name) => ` + cv = ud["${name}"].value; + v = uv["${name}"]; + + if(cv[0] !== v[0] || cv[1] !== v[1]) + { + cv[0] = v[0]; + cv[1] = v[1]; + gl.uniform2f(ud["${name}"].location, v[0], v[1]); + } + ` + }, + { + test: (data, uniform) => data.type === "vec4" && data.size === 1 && !data.isArray && uniform.width !== void 0, + code: (name) => ` + cv = ud["${name}"].value; + v = uv["${name}"]; + + if(cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.width || cv[3] !== v.height) + { + cv[0] = v.x; + cv[1] = v.y; + cv[2] = v.width; + cv[3] = v.height; + gl.uniform4f(ud["${name}"].location, v.x, v.y, v.width, v.height) + }`, + codeUbo: (name) => ` + v = uv.${name}; + + data[offset] = v.x; + data[offset+1] = v.y; + data[offset+2] = v.width; + data[offset+3] = v.height; + ` + }, + { + test: (data, uniform) => data.type === "vec4" && data.size === 1 && !data.isArray && uniform.red !== void 0, + code: (name) => ` + cv = ud["${name}"].value; + v = uv["${name}"]; + + if(cv[0] !== v.red || cv[1] !== v.green || cv[2] !== v.blue || cv[3] !== v.alpha) + { + cv[0] = v.red; + cv[1] = v.green; + cv[2] = v.blue; + cv[3] = v.alpha; + gl.uniform4f(ud["${name}"].location, v.red, v.green, v.blue, v.alpha) + }`, + codeUbo: (name) => ` + v = uv.${name}; + + data[offset] = v.red; + data[offset+1] = v.green; + data[offset+2] = v.blue; + data[offset+3] = v.alpha; + ` + }, + { + test: (data, uniform) => data.type === "vec3" && data.size === 1 && !data.isArray && uniform.red !== void 0, + code: (name) => ` + cv = ud["${name}"].value; + v = uv["${name}"]; + + if(cv[0] !== v.red || cv[1] !== v.green || cv[2] !== v.blue || cv[3] !== v.a) + { + cv[0] = v.red; + cv[1] = v.green; + cv[2] = v.blue; + + gl.uniform3f(ud["${name}"].location, v.red, v.green, v.blue) + }`, + codeUbo: (name) => ` + v = uv.${name}; + + data[offset] = v.red; + data[offset+1] = v.green; + data[offset+2] = v.blue; + ` + }, + { + test: (data) => data.type === "vec4" && data.size === 1 && !data.isArray, + code: (name) => ` + cv = ud["${name}"].value; + v = uv["${name}"]; + + if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) + { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + cv[3] = v[3]; + + gl.uniform4f(ud["${name}"].location, v[0], v[1], v[2], v[3]) + }` + } + ]; + + const GLSL_TO_SINGLE_SETTERS_CACHED = { + float: ` + if (cv !== v) + { + cu.value = v; + gl.uniform1f(location, v); + }`, + vec2: ` + if (cv[0] !== v[0] || cv[1] !== v[1]) + { + cv[0] = v[0]; + cv[1] = v[1]; + + gl.uniform2f(location, v[0], v[1]) + }`, + vec3: ` + if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) + { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + + gl.uniform3f(location, v[0], v[1], v[2]) + }`, + vec4: ` + if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) + { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + cv[3] = v[3]; + + gl.uniform4f(location, v[0], v[1], v[2], v[3]); + }`, + int: ` + if (cv !== v) + { + cu.value = v; + + gl.uniform1i(location, v); + }`, + ivec2: ` + if (cv[0] !== v[0] || cv[1] !== v[1]) + { + cv[0] = v[0]; + cv[1] = v[1]; + + gl.uniform2i(location, v[0], v[1]); + }`, + ivec3: ` + if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) + { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + + gl.uniform3i(location, v[0], v[1], v[2]); + }`, + ivec4: ` + if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) + { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + cv[3] = v[3]; + + gl.uniform4i(location, v[0], v[1], v[2], v[3]); + }`, + uint: ` + if (cv !== v) + { + cu.value = v; + + gl.uniform1ui(location, v); + }`, + uvec2: ` + if (cv[0] !== v[0] || cv[1] !== v[1]) + { + cv[0] = v[0]; + cv[1] = v[1]; + + gl.uniform2ui(location, v[0], v[1]); + }`, + uvec3: ` + if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) + { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + + gl.uniform3ui(location, v[0], v[1], v[2]); + }`, + uvec4: ` + if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) + { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + cv[3] = v[3]; + + gl.uniform4ui(location, v[0], v[1], v[2], v[3]); + }`, + bool: ` + if (cv !== v) + { + cu.value = v; + gl.uniform1i(location, v); + }`, + bvec2: ` + if (cv[0] != v[0] || cv[1] != v[1]) + { + cv[0] = v[0]; + cv[1] = v[1]; + + gl.uniform2i(location, v[0], v[1]); + }`, + bvec3: ` + if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) + { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + + gl.uniform3i(location, v[0], v[1], v[2]); + }`, + bvec4: ` + if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) + { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + cv[3] = v[3]; + + gl.uniform4i(location, v[0], v[1], v[2], v[3]); + }`, + mat2: "gl.uniformMatrix2fv(location, false, v)", + mat3: "gl.uniformMatrix3fv(location, false, v)", + mat4: "gl.uniformMatrix4fv(location, false, v)", + sampler2D: ` + if (cv !== v) + { + cu.value = v; + + gl.uniform1i(location, v); + }`, + samplerCube: ` + if (cv !== v) + { + cu.value = v; + + gl.uniform1i(location, v); + }`, + sampler2DArray: ` + if (cv !== v) + { + cu.value = v; + + gl.uniform1i(location, v); + }` + }; + const GLSL_TO_ARRAY_SETTERS = { + float: `gl.uniform1fv(location, v)`, + vec2: `gl.uniform2fv(location, v)`, + vec3: `gl.uniform3fv(location, v)`, + vec4: "gl.uniform4fv(location, v)", + mat4: "gl.uniformMatrix4fv(location, false, v)", + mat3: "gl.uniformMatrix3fv(location, false, v)", + mat2: "gl.uniformMatrix2fv(location, false, v)", + int: "gl.uniform1iv(location, v)", + ivec2: "gl.uniform2iv(location, v)", + ivec3: "gl.uniform3iv(location, v)", + ivec4: "gl.uniform4iv(location, v)", + uint: "gl.uniform1uiv(location, v)", + uvec2: "gl.uniform2uiv(location, v)", + uvec3: "gl.uniform3uiv(location, v)", + uvec4: "gl.uniform4uiv(location, v)", + bool: "gl.uniform1iv(location, v)", + bvec2: "gl.uniform2iv(location, v)", + bvec3: "gl.uniform3iv(location, v)", + bvec4: "gl.uniform4iv(location, v)", + sampler2D: "gl.uniform1iv(location, v)", + samplerCube: "gl.uniform1iv(location, v)", + sampler2DArray: "gl.uniform1iv(location, v)" + }; + function generateUniformsSync(group, uniformData) { + const funcFragments = [` + var v = null; + var cv = null; + var cu = null; + var t = 0; + var gl = renderer.gl; + `]; + for (const i in group.uniforms) { + const data = uniformData[i]; + if (!data) { + if (group.uniforms[i]?.group) { + if (group.uniforms[i].ubo) { + funcFragments.push(` + renderer.shader.syncUniformBufferGroup(uv.${i}, '${i}'); + `); + } else { + funcFragments.push(` + renderer.shader.syncUniformGroup(uv.${i}, syncData); + `); + } + } + continue; + } + const uniform = group.uniforms[i]; + let parsed = false; + for (let j = 0; j < uniformParsers.length; j++) { + if (uniformParsers[j].test(data, uniform)) { + funcFragments.push(uniformParsers[j].code(i, uniform)); + parsed = true; + break; + } + } + if (!parsed) { + const templateType = data.size === 1 && !data.isArray ? GLSL_TO_SINGLE_SETTERS_CACHED : GLSL_TO_ARRAY_SETTERS; + const template = templateType[data.type].replace("location", `ud["${i}"].location`); + funcFragments.push(` + cu = ud["${i}"]; + cv = cu.value; + v = uv["${i}"]; + ${template};`); + } + } + return new Function("ud", "uv", "renderer", "syncData", funcFragments.join("\n")); + } + + const unknownContext = {}; + let context = unknownContext; + function getTestContext() { + if (context === unknownContext || context?.isContextLost()) { + const canvas = settings.ADAPTER.createCanvas(); + let gl; + if (settings.PREFER_ENV >= ENV.WEBGL2) { + gl = canvas.getContext("webgl2", {}); + } + if (!gl) { + gl = canvas.getContext("webgl", {}) || canvas.getContext("experimental-webgl", {}); + if (!gl) { + gl = null; + } else { + gl.getExtension("WEBGL_draw_buffers"); + } + } + context = gl; + } + return context; + } + + let maxFragmentPrecision; + function getMaxFragmentPrecision() { + if (!maxFragmentPrecision) { + maxFragmentPrecision = PRECISION.MEDIUM; + const gl = getTestContext(); + if (gl) { + if (gl.getShaderPrecisionFormat) { + const shaderFragment = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT); + maxFragmentPrecision = shaderFragment.precision ? PRECISION.HIGH : PRECISION.MEDIUM; + } + } + } + return maxFragmentPrecision; + } + + function logPrettyShaderError(gl, shader) { + const shaderSrc = gl.getShaderSource(shader).split("\n").map((line, index) => `${index}: ${line}`); + const shaderLog = gl.getShaderInfoLog(shader); + const splitShader = shaderLog.split("\n"); + const dedupe = {}; + const lineNumbers = splitShader.map((line) => parseFloat(line.replace(/^ERROR\: 0\:([\d]+)\:.*$/, "$1"))).filter((n) => { + if (n && !dedupe[n]) { + dedupe[n] = true; + return true; + } + return false; + }); + const logArgs = [""]; + lineNumbers.forEach((number) => { + shaderSrc[number - 1] = `%c${shaderSrc[number - 1]}%c`; + logArgs.push("background: #FF0000; color:#FFFFFF; font-size: 10px", "font-size: 10px"); + }); + const fragmentSourceToLog = shaderSrc.join("\n"); + logArgs[0] = fragmentSourceToLog; + console.error(shaderLog); + console.groupCollapsed("click to view full shader code"); + console.warn(...logArgs); + console.groupEnd(); + } + function logProgramError(gl, program, vertexShader, fragmentShader) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) { + logPrettyShaderError(gl, vertexShader); + } + if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) { + logPrettyShaderError(gl, fragmentShader); + } + console.error("PixiJS Error: Could not initialize shader."); + if (gl.getProgramInfoLog(program) !== "") { + console.warn("PixiJS Warning: gl.getProgramInfoLog()", gl.getProgramInfoLog(program)); + } + } + } + + const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + uint: 1, + uvec2: 2, + uvec3: 3, + uvec4: 4, + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + mat2: 4, + mat3: 9, + mat4: 16, + sampler2D: 1 + }; + function mapSize(type) { + return GLSL_TO_SIZE[type]; + } + + let GL_TABLE = null; + const GL_TO_GLSL_TYPES = { + FLOAT: "float", + FLOAT_VEC2: "vec2", + FLOAT_VEC3: "vec3", + FLOAT_VEC4: "vec4", + INT: "int", + INT_VEC2: "ivec2", + INT_VEC3: "ivec3", + INT_VEC4: "ivec4", + UNSIGNED_INT: "uint", + UNSIGNED_INT_VEC2: "uvec2", + UNSIGNED_INT_VEC3: "uvec3", + UNSIGNED_INT_VEC4: "uvec4", + BOOL: "bool", + BOOL_VEC2: "bvec2", + BOOL_VEC3: "bvec3", + BOOL_VEC4: "bvec4", + FLOAT_MAT2: "mat2", + FLOAT_MAT3: "mat3", + FLOAT_MAT4: "mat4", + SAMPLER_2D: "sampler2D", + INT_SAMPLER_2D: "sampler2D", + UNSIGNED_INT_SAMPLER_2D: "sampler2D", + SAMPLER_CUBE: "samplerCube", + INT_SAMPLER_CUBE: "samplerCube", + UNSIGNED_INT_SAMPLER_CUBE: "samplerCube", + SAMPLER_2D_ARRAY: "sampler2DArray", + INT_SAMPLER_2D_ARRAY: "sampler2DArray", + UNSIGNED_INT_SAMPLER_2D_ARRAY: "sampler2DArray" + }; + function mapType(gl, type) { + if (!GL_TABLE) { + const typeNames = Object.keys(GL_TO_GLSL_TYPES); + GL_TABLE = {}; + for (let i = 0; i < typeNames.length; ++i) { + const tn = typeNames[i]; + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; + } + } + return GL_TABLE[type]; + } + + function setPrecision(src, requestedPrecision, maxSupportedPrecision) { + if (src.substring(0, 9) !== "precision") { + let precision = requestedPrecision; + if (requestedPrecision === PRECISION.HIGH && maxSupportedPrecision !== PRECISION.HIGH) { + precision = PRECISION.MEDIUM; + } + return `precision ${precision} float; +${src}`; + } else if (maxSupportedPrecision !== PRECISION.HIGH && src.substring(0, 15) === "precision highp") { + return src.replace("precision highp", "precision mediump"); + } + return src; + } + + let unsafeEval; + function unsafeEvalSupported() { + if (typeof unsafeEval === "boolean") { + return unsafeEval; + } + try { + const func = new Function("param1", "param2", "param3", "return param1[param2] === param3;"); + unsafeEval = func({ a: "b" }, "a", "b") === true; + } catch (e) { + unsafeEval = false; + } + return unsafeEval; + } + + let UID$2 = 0; + const nameCache = {}; + const _Program = class { + constructor(vertexSrc, fragmentSrc, name = "pixi-shader", extra = {}) { + this.extra = {}; + this.id = UID$2++; + this.vertexSrc = vertexSrc || _Program.defaultVertexSrc; + this.fragmentSrc = fragmentSrc || _Program.defaultFragmentSrc; + this.vertexSrc = this.vertexSrc.trim(); + this.fragmentSrc = this.fragmentSrc.trim(); + this.extra = extra; + if (this.vertexSrc.substring(0, 8) !== "#version") { + name = name.replace(/\s+/g, "-"); + if (nameCache[name]) { + nameCache[name]++; + name += `-${nameCache[name]}`; + } else { + nameCache[name] = 1; + } + this.vertexSrc = `#define SHADER_NAME ${name} +${this.vertexSrc}`; + this.fragmentSrc = `#define SHADER_NAME ${name} +${this.fragmentSrc}`; + this.vertexSrc = setPrecision(this.vertexSrc, _Program.defaultVertexPrecision, PRECISION.HIGH); + this.fragmentSrc = setPrecision(this.fragmentSrc, _Program.defaultFragmentPrecision, getMaxFragmentPrecision()); + } + this.glPrograms = {}; + this.syncUniforms = null; + } + static get defaultVertexSrc() { + return defaultVertex$3; + } + static get defaultFragmentSrc() { + return defaultFragment$2; + } + static from(vertexSrc, fragmentSrc, name) { + const key = vertexSrc + fragmentSrc; + let program = ProgramCache[key]; + if (!program) { + ProgramCache[key] = program = new _Program(vertexSrc, fragmentSrc, name); + } + return program; + } + }; + let Program = _Program; + Program.defaultVertexPrecision = PRECISION.HIGH; + Program.defaultFragmentPrecision = isMobile.apple.device ? PRECISION.HIGH : PRECISION.MEDIUM; + + let UID$1 = 0; + class UniformGroup { + constructor(uniforms, isStatic, isUbo) { + this.group = true; + this.syncUniforms = {}; + this.dirtyId = 0; + this.id = UID$1++; + this.static = !!isStatic; + this.ubo = !!isUbo; + if (uniforms instanceof Buffer) { + this.buffer = uniforms; + this.buffer.type = BUFFER_TYPE.UNIFORM_BUFFER; + this.autoManage = false; + this.ubo = true; + } else { + this.uniforms = uniforms; + if (this.ubo) { + this.buffer = new Buffer(new Float32Array(1)); + this.buffer.type = BUFFER_TYPE.UNIFORM_BUFFER; + this.autoManage = true; + } + } + } + update() { + this.dirtyId++; + if (!this.autoManage && this.buffer) { + this.buffer.update(); + } + } + add(name, uniforms, _static) { + if (!this.ubo) { + this.uniforms[name] = new UniformGroup(uniforms, _static); + } else { + throw new Error("[UniformGroup] uniform groups in ubo mode cannot be modified, or have uniform groups nested in them"); + } + } + static from(uniforms, _static, _ubo) { + return new UniformGroup(uniforms, _static, _ubo); + } + static uboFrom(uniforms, _static) { + return new UniformGroup(uniforms, _static ?? true, true); + } + } + + class Shader { + constructor(program, uniforms) { + this.uniformBindCount = 0; + this.program = program; + if (uniforms) { + if (uniforms instanceof UniformGroup) { + this.uniformGroup = uniforms; + } else { + this.uniformGroup = new UniformGroup(uniforms); + } + } else { + this.uniformGroup = new UniformGroup({}); + } + this.disposeRunner = new Runner("disposeShader"); + } + checkUniformExists(name, group) { + if (group.uniforms[name]) { + return true; + } + for (const i in group.uniforms) { + const uniform = group.uniforms[i]; + if (uniform.group) { + if (this.checkUniformExists(name, uniform)) { + return true; + } + } + } + return false; + } + destroy() { + this.uniformGroup = null; + this.disposeRunner.emit(this); + this.disposeRunner.destroy(); + } + get uniforms() { + return this.uniformGroup.uniforms; + } + static from(vertexSrc, fragmentSrc, uniforms) { + const program = Program.from(vertexSrc, fragmentSrc); + return new Shader(program, uniforms); + } + } + + class BatchShaderGenerator { + constructor(vertexSrc, fragTemplate) { + this.vertexSrc = vertexSrc; + this.fragTemplate = fragTemplate; + this.programCache = {}; + this.defaultGroupCache = {}; + if (!fragTemplate.includes("%count%")) { + throw new Error('Fragment template must contain "%count%".'); + } + if (!fragTemplate.includes("%forloop%")) { + throw new Error('Fragment template must contain "%forloop%".'); + } + } + generateShader(maxTextures) { + if (!this.programCache[maxTextures]) { + const sampleValues = new Int32Array(maxTextures); + for (let i = 0; i < maxTextures; i++) { + sampleValues[i] = i; + } + this.defaultGroupCache[maxTextures] = UniformGroup.from({ uSamplers: sampleValues }, true); + let fragmentSrc = this.fragTemplate; + fragmentSrc = fragmentSrc.replace(/%count%/gi, `${maxTextures}`); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, this.generateSampleSrc(maxTextures)); + this.programCache[maxTextures] = new Program(this.vertexSrc, fragmentSrc); + } + const uniforms = { + tint: new Float32Array([1, 1, 1, 1]), + translationMatrix: new Matrix(), + default: this.defaultGroupCache[maxTextures] + }; + return new Shader(this.programCache[maxTextures], uniforms); + } + generateSampleSrc(maxTextures) { + let src = ""; + src += "\n"; + src += "\n"; + for (let i = 0; i < maxTextures; i++) { + if (i > 0) { + src += "\nelse "; + } + if (i < maxTextures - 1) { + src += `if(vTextureId < ${i}.5)`; + } + src += "\n{"; + src += ` + color = texture2D(uSamplers[${i}], vTextureCoord);`; + src += "\n}"; + } + src += "\n"; + src += "\n"; + return src; + } + } + + class BatchTextureArray { + constructor() { + this.elements = []; + this.ids = []; + this.count = 0; + } + clear() { + for (let i = 0; i < this.count; i++) { + this.elements[i] = null; + } + this.count = 0; + } + } + + function canUploadSameBuffer() { + return !isMobile.apple.device; + } + + function maxRecommendedTextures(max) { + let allowMax = true; + const navigator = settings.ADAPTER.getNavigator(); + if (isMobile.tablet || isMobile.phone) { + if (isMobile.apple.device) { + const match = navigator.userAgent.match(/OS (\d+)_(\d+)?/); + if (match) { + const majorVersion = parseInt(match[1], 10); + if (majorVersion < 11) { + allowMax = false; + } + } + } + if (isMobile.android.device) { + const match = navigator.userAgent.match(/Android\s([0-9.]*)/); + if (match) { + const majorVersion = parseInt(match[1], 10); + if (majorVersion < 7) { + allowMax = false; + } + } + } + } + return allowMax ? max : 4; + } + + class ObjectRenderer { + constructor(renderer) { + this.renderer = renderer; + } + flush() { + } + destroy() { + this.renderer = null; + } + start() { + } + stop() { + this.flush(); + } + render(_object) { + } + } + + var defaultFragment$1 = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\nuniform sampler2D uSamplers[%count%];\n\nvoid main(void){\n vec4 color;\n %forloop%\n gl_FragColor = color * vColor;\n}\n"; + + var defaultVertex$2 = "precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform vec4 tint;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor * tint;\n}\n"; + + const _BatchRenderer = class extends ObjectRenderer { + constructor(renderer) { + super(renderer); + this.setShaderGenerator(); + this.geometryClass = BatchGeometry; + this.vertexSize = 6; + this.state = State.for2d(); + this.size = _BatchRenderer.defaultBatchSize * 4; + this._vertexCount = 0; + this._indexCount = 0; + this._bufferedElements = []; + this._bufferedTextures = []; + this._bufferSize = 0; + this._shader = null; + this._packedGeometries = []; + this._packedGeometryPoolSize = 2; + this._flushId = 0; + this._aBuffers = {}; + this._iBuffers = {}; + this.maxTextures = 1; + this.renderer.on("prerender", this.onPrerender, this); + renderer.runners.contextChange.add(this); + this._dcIndex = 0; + this._aIndex = 0; + this._iIndex = 0; + this._attributeBuffer = null; + this._indexBuffer = null; + this._tempBoundTextures = []; + } + static get defaultMaxTextures() { + this._defaultMaxTextures = this._defaultMaxTextures ?? maxRecommendedTextures(32); + return this._defaultMaxTextures; + } + static set defaultMaxTextures(value) { + this._defaultMaxTextures = value; + } + static get canUploadSameBuffer() { + this._canUploadSameBuffer = this._canUploadSameBuffer ?? canUploadSameBuffer(); + return this._canUploadSameBuffer; + } + static set canUploadSameBuffer(value) { + this._canUploadSameBuffer = value; + } + get MAX_TEXTURES() { + deprecation$1("7.1.0", "BatchRenderer#MAX_TEXTURES renamed to BatchRenderer#maxTextures"); + return this.maxTextures; + } + static get defaultVertexSrc() { + return defaultVertex$2; + } + static get defaultFragmentTemplate() { + return defaultFragment$1; + } + setShaderGenerator({ + vertex = _BatchRenderer.defaultVertexSrc, + fragment = _BatchRenderer.defaultFragmentTemplate + } = {}) { + this.shaderGenerator = new BatchShaderGenerator(vertex, fragment); + } + contextChange() { + const gl = this.renderer.gl; + if (settings.PREFER_ENV === ENV.WEBGL_LEGACY) { + this.maxTextures = 1; + } else { + this.maxTextures = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), _BatchRenderer.defaultMaxTextures); + this.maxTextures = checkMaxIfStatementsInShader(this.maxTextures, gl); + } + this._shader = this.shaderGenerator.generateShader(this.maxTextures); + for (let i = 0; i < this._packedGeometryPoolSize; i++) { + this._packedGeometries[i] = new this.geometryClass(); + } + this.initFlushBuffers(); + } + initFlushBuffers() { + const { + _drawCallPool, + _textureArrayPool + } = _BatchRenderer; + const MAX_SPRITES = this.size / 4; + const MAX_TA = Math.floor(MAX_SPRITES / this.maxTextures) + 1; + while (_drawCallPool.length < MAX_SPRITES) { + _drawCallPool.push(new BatchDrawCall()); + } + while (_textureArrayPool.length < MAX_TA) { + _textureArrayPool.push(new BatchTextureArray()); + } + for (let i = 0; i < this.maxTextures; i++) { + this._tempBoundTextures[i] = null; + } + } + onPrerender() { + this._flushId = 0; + } + render(element) { + if (!element._texture.valid) { + return; + } + if (this._vertexCount + element.vertexData.length / 2 > this.size) { + this.flush(); + } + this._vertexCount += element.vertexData.length / 2; + this._indexCount += element.indices.length; + this._bufferedTextures[this._bufferSize] = element._texture.baseTexture; + this._bufferedElements[this._bufferSize++] = element; + } + buildTexturesAndDrawCalls() { + const { + _bufferedTextures: textures, + maxTextures + } = this; + const textureArrays = _BatchRenderer._textureArrayPool; + const batch = this.renderer.batch; + const boundTextures = this._tempBoundTextures; + const touch = this.renderer.textureGC.count; + let TICK = ++BaseTexture._globalBatch; + let countTexArrays = 0; + let texArray = textureArrays[0]; + let start = 0; + batch.copyBoundTextures(boundTextures, maxTextures); + for (let i = 0; i < this._bufferSize; ++i) { + const tex = textures[i]; + textures[i] = null; + if (tex._batchEnabled === TICK) { + continue; + } + if (texArray.count >= maxTextures) { + batch.boundArray(texArray, boundTextures, TICK, maxTextures); + this.buildDrawCalls(texArray, start, i); + start = i; + texArray = textureArrays[++countTexArrays]; + ++TICK; + } + tex._batchEnabled = TICK; + tex.touched = touch; + texArray.elements[texArray.count++] = tex; + } + if (texArray.count > 0) { + batch.boundArray(texArray, boundTextures, TICK, maxTextures); + this.buildDrawCalls(texArray, start, this._bufferSize); + ++countTexArrays; + ++TICK; + } + for (let i = 0; i < boundTextures.length; i++) { + boundTextures[i] = null; + } + BaseTexture._globalBatch = TICK; + } + buildDrawCalls(texArray, start, finish) { + const { + _bufferedElements: elements, + _attributeBuffer, + _indexBuffer, + vertexSize + } = this; + const drawCalls = _BatchRenderer._drawCallPool; + let dcIndex = this._dcIndex; + let aIndex = this._aIndex; + let iIndex = this._iIndex; + let drawCall = drawCalls[dcIndex]; + drawCall.start = this._iIndex; + drawCall.texArray = texArray; + for (let i = start; i < finish; ++i) { + const sprite = elements[i]; + const tex = sprite._texture.baseTexture; + const spriteBlendMode = premultiplyBlendMode[tex.alphaMode ? 1 : 0][sprite.blendMode]; + elements[i] = null; + if (start < i && drawCall.blend !== spriteBlendMode) { + drawCall.size = iIndex - drawCall.start; + start = i; + drawCall = drawCalls[++dcIndex]; + drawCall.texArray = texArray; + drawCall.start = iIndex; + } + this.packInterleavedGeometry(sprite, _attributeBuffer, _indexBuffer, aIndex, iIndex); + aIndex += sprite.vertexData.length / 2 * vertexSize; + iIndex += sprite.indices.length; + drawCall.blend = spriteBlendMode; + } + if (start < finish) { + drawCall.size = iIndex - drawCall.start; + ++dcIndex; + } + this._dcIndex = dcIndex; + this._aIndex = aIndex; + this._iIndex = iIndex; + } + bindAndClearTexArray(texArray) { + const textureSystem = this.renderer.texture; + for (let j = 0; j < texArray.count; j++) { + textureSystem.bind(texArray.elements[j], texArray.ids[j]); + texArray.elements[j] = null; + } + texArray.count = 0; + } + updateGeometry() { + const { + _packedGeometries: packedGeometries, + _attributeBuffer: attributeBuffer, + _indexBuffer: indexBuffer + } = this; + if (!_BatchRenderer.canUploadSameBuffer) { + if (this._packedGeometryPoolSize <= this._flushId) { + this._packedGeometryPoolSize++; + packedGeometries[this._flushId] = new this.geometryClass(); + } + packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData); + packedGeometries[this._flushId]._indexBuffer.update(indexBuffer); + this.renderer.geometry.bind(packedGeometries[this._flushId]); + this.renderer.geometry.updateBuffers(); + this._flushId++; + } else { + packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData); + packedGeometries[this._flushId]._indexBuffer.update(indexBuffer); + this.renderer.geometry.updateBuffers(); + } + } + drawBatches() { + const dcCount = this._dcIndex; + const { gl, state: stateSystem } = this.renderer; + const drawCalls = _BatchRenderer._drawCallPool; + let curTexArray = null; + for (let i = 0; i < dcCount; i++) { + const { texArray, type, size, start, blend } = drawCalls[i]; + if (curTexArray !== texArray) { + curTexArray = texArray; + this.bindAndClearTexArray(texArray); + } + this.state.blendMode = blend; + stateSystem.set(this.state); + gl.drawElements(type, size, gl.UNSIGNED_SHORT, start * 2); + } + } + flush() { + if (this._vertexCount === 0) { + return; + } + this._attributeBuffer = this.getAttributeBuffer(this._vertexCount); + this._indexBuffer = this.getIndexBuffer(this._indexCount); + this._aIndex = 0; + this._iIndex = 0; + this._dcIndex = 0; + this.buildTexturesAndDrawCalls(); + this.updateGeometry(); + this.drawBatches(); + this._bufferSize = 0; + this._vertexCount = 0; + this._indexCount = 0; + } + start() { + this.renderer.state.set(this.state); + this.renderer.texture.ensureSamplerType(this.maxTextures); + this.renderer.shader.bind(this._shader); + if (_BatchRenderer.canUploadSameBuffer) { + this.renderer.geometry.bind(this._packedGeometries[this._flushId]); + } + } + stop() { + this.flush(); + } + destroy() { + for (let i = 0; i < this._packedGeometryPoolSize; i++) { + if (this._packedGeometries[i]) { + this._packedGeometries[i].destroy(); + } + } + this.renderer.off("prerender", this.onPrerender, this); + this._aBuffers = null; + this._iBuffers = null; + this._packedGeometries = null; + this._attributeBuffer = null; + this._indexBuffer = null; + if (this._shader) { + this._shader.destroy(); + this._shader = null; + } + super.destroy(); + } + getAttributeBuffer(size) { + const roundedP2 = nextPow2(Math.ceil(size / 8)); + const roundedSizeIndex = log2(roundedP2); + const roundedSize = roundedP2 * 8; + if (this._aBuffers.length <= roundedSizeIndex) { + this._iBuffers.length = roundedSizeIndex + 1; + } + let buffer = this._aBuffers[roundedSize]; + if (!buffer) { + this._aBuffers[roundedSize] = buffer = new ViewableBuffer(roundedSize * this.vertexSize * 4); + } + return buffer; + } + getIndexBuffer(size) { + const roundedP2 = nextPow2(Math.ceil(size / 12)); + const roundedSizeIndex = log2(roundedP2); + const roundedSize = roundedP2 * 12; + if (this._iBuffers.length <= roundedSizeIndex) { + this._iBuffers.length = roundedSizeIndex + 1; + } + let buffer = this._iBuffers[roundedSizeIndex]; + if (!buffer) { + this._iBuffers[roundedSizeIndex] = buffer = new Uint16Array(roundedSize); + } + return buffer; + } + packInterleavedGeometry(element, attributeBuffer, indexBuffer, aIndex, iIndex) { + const { + uint32View, + float32View + } = attributeBuffer; + const packedVertices = aIndex / this.vertexSize; + const uvs = element.uvs; + const indicies = element.indices; + const vertexData = element.vertexData; + const textureId = element._texture.baseTexture._batchLocation; + const alpha = Math.min(element.worldAlpha, 1); + const argb = Color.shared.setValue(element._tintRGB).toPremultiplied(alpha, element._texture.baseTexture.alphaMode > 0); + for (let i = 0; i < vertexData.length; i += 2) { + float32View[aIndex++] = vertexData[i]; + float32View[aIndex++] = vertexData[i + 1]; + float32View[aIndex++] = uvs[i]; + float32View[aIndex++] = uvs[i + 1]; + uint32View[aIndex++] = argb; + float32View[aIndex++] = textureId; + } + for (let i = 0; i < indicies.length; i++) { + indexBuffer[iIndex++] = packedVertices + indicies[i]; + } + } + }; + let BatchRenderer = _BatchRenderer; + BatchRenderer.defaultBatchSize = 4096; + BatchRenderer.extension = { + name: "batch", + type: ExtensionType.RendererPlugin + }; + BatchRenderer._drawCallPool = []; + BatchRenderer._textureArrayPool = []; + extensions$1.add(BatchRenderer); + + var defaultFragment = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n"; + + var defaultVertex$1 = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"; + + const _Filter = class extends Shader { + constructor(vertexSrc, fragmentSrc, uniforms) { + const program = Program.from(vertexSrc || _Filter.defaultVertexSrc, fragmentSrc || _Filter.defaultFragmentSrc); + super(program, uniforms); + this.padding = 0; + this.resolution = _Filter.defaultResolution; + this.multisample = _Filter.defaultMultisample; + this.enabled = true; + this.autoFit = true; + this.state = new State(); + } + apply(filterManager, input, output, clearMode, _currentState) { + filterManager.applyFilter(this, input, output, clearMode); + } + get blendMode() { + return this.state.blendMode; + } + set blendMode(value) { + this.state.blendMode = value; + } + get resolution() { + return this._resolution; + } + set resolution(value) { + this._resolution = value; + } + static get defaultVertexSrc() { + return defaultVertex$1; + } + static get defaultFragmentSrc() { + return defaultFragment; + } + }; + let Filter = _Filter; + Filter.defaultResolution = 1; + Filter.defaultMultisample = MSAA_QUALITY.NONE; + + class BackgroundSystem { + constructor() { + this.clearBeforeRender = true; + this._backgroundColor = new Color(0); + this.alpha = 1; + } + init(options) { + this.clearBeforeRender = options.clearBeforeRender; + const { backgroundColor, background, backgroundAlpha } = options; + const color = background ?? backgroundColor; + if (color !== void 0) { + this.color = color; + } + this.alpha = backgroundAlpha; + } + get color() { + return this._backgroundColor.value; + } + set color(value) { + this._backgroundColor.setValue(value); + } + get alpha() { + return this._backgroundColor.alpha; + } + set alpha(value) { + this._backgroundColor.setAlpha(value); + } + get backgroundColor() { + return this._backgroundColor; + } + destroy() { + } + } + BackgroundSystem.defaultOptions = { + backgroundAlpha: 1, + backgroundColor: 0, + clearBeforeRender: true + }; + BackgroundSystem.extension = { + type: [ + ExtensionType.RendererSystem, + ExtensionType.CanvasRendererSystem + ], + name: "background" + }; + extensions$1.add(BackgroundSystem); + + class BatchSystem { + constructor(renderer) { + this.renderer = renderer; + this.emptyRenderer = new ObjectRenderer(renderer); + this.currentRenderer = this.emptyRenderer; + } + setObjectRenderer(objectRenderer) { + if (this.currentRenderer === objectRenderer) { + return; + } + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); + } + flush() { + this.setObjectRenderer(this.emptyRenderer); + } + reset() { + this.setObjectRenderer(this.emptyRenderer); + } + copyBoundTextures(arr, maxTextures) { + const { boundTextures } = this.renderer.texture; + for (let i = maxTextures - 1; i >= 0; --i) { + arr[i] = boundTextures[i] || null; + if (arr[i]) { + arr[i]._batchLocation = i; + } + } + } + boundArray(texArray, boundTextures, batchId, maxTextures) { + const { elements, ids, count } = texArray; + let j = 0; + for (let i = 0; i < count; i++) { + const tex = elements[i]; + const loc = tex._batchLocation; + if (loc >= 0 && loc < maxTextures && boundTextures[loc] === tex) { + ids[i] = loc; + continue; + } + while (j < maxTextures) { + const bound = boundTextures[j]; + if (bound && bound._batchEnabled === batchId && bound._batchLocation === j) { + j++; + continue; + } + ids[i] = j; + tex._batchLocation = j; + boundTextures[j] = tex; + break; + } + } + } + destroy() { + this.renderer = null; + } + } + BatchSystem.extension = { + type: ExtensionType.RendererSystem, + name: "batch" + }; + extensions$1.add(BatchSystem); + + let CONTEXT_UID_COUNTER = 0; + class ContextSystem { + constructor(renderer) { + this.renderer = renderer; + this.webGLVersion = 1; + this.extensions = {}; + this.supports = { + uint32Indices: false + }; + this.handleContextLost = this.handleContextLost.bind(this); + this.handleContextRestored = this.handleContextRestored.bind(this); + } + get isLost() { + return !this.gl || this.gl.isContextLost(); + } + contextChange(gl) { + this.gl = gl; + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID_COUNTER++; + } + init(options) { + if (options.context) { + this.initFromContext(options.context); + } else { + const alpha = this.renderer.background.alpha < 1; + const premultipliedAlpha = options.premultipliedAlpha; + this.preserveDrawingBuffer = options.preserveDrawingBuffer; + this.useContextAlpha = options.useContextAlpha; + this.powerPreference = options.powerPreference; + this.initFromOptions({ + alpha, + premultipliedAlpha, + antialias: options.antialias, + stencil: true, + preserveDrawingBuffer: options.preserveDrawingBuffer, + powerPreference: options.powerPreference + }); + } + } + initFromContext(gl) { + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID_COUNTER++; + this.renderer.runners.contextChange.emit(gl); + const view = this.renderer.view; + if (view.addEventListener !== void 0) { + view.addEventListener("webglcontextlost", this.handleContextLost, false); + view.addEventListener("webglcontextrestored", this.handleContextRestored, false); + } + } + initFromOptions(options) { + const gl = this.createContext(this.renderer.view, options); + this.initFromContext(gl); + } + createContext(canvas, options) { + let gl; + if (settings.PREFER_ENV >= ENV.WEBGL2) { + gl = canvas.getContext("webgl2", options); + } + if (gl) { + this.webGLVersion = 2; + } else { + this.webGLVersion = 1; + gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options); + if (!gl) { + throw new Error("This browser does not support WebGL. Try using the canvas renderer"); + } + } + this.gl = gl; + this.getExtensions(); + return this.gl; + } + getExtensions() { + const { gl } = this; + const common = { + loseContext: gl.getExtension("WEBGL_lose_context"), + anisotropicFiltering: gl.getExtension("EXT_texture_filter_anisotropic"), + floatTextureLinear: gl.getExtension("OES_texture_float_linear"), + s3tc: gl.getExtension("WEBGL_compressed_texture_s3tc"), + s3tc_sRGB: gl.getExtension("WEBGL_compressed_texture_s3tc_srgb"), + etc: gl.getExtension("WEBGL_compressed_texture_etc"), + etc1: gl.getExtension("WEBGL_compressed_texture_etc1"), + pvrtc: gl.getExtension("WEBGL_compressed_texture_pvrtc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"), + atc: gl.getExtension("WEBGL_compressed_texture_atc"), + astc: gl.getExtension("WEBGL_compressed_texture_astc") + }; + if (this.webGLVersion === 1) { + Object.assign(this.extensions, common, { + drawBuffers: gl.getExtension("WEBGL_draw_buffers"), + depthTexture: gl.getExtension("WEBGL_depth_texture"), + vertexArrayObject: gl.getExtension("OES_vertex_array_object") || gl.getExtension("MOZ_OES_vertex_array_object") || gl.getExtension("WEBKIT_OES_vertex_array_object"), + uint32ElementIndex: gl.getExtension("OES_element_index_uint"), + floatTexture: gl.getExtension("OES_texture_float"), + floatTextureLinear: gl.getExtension("OES_texture_float_linear"), + textureHalfFloat: gl.getExtension("OES_texture_half_float"), + textureHalfFloatLinear: gl.getExtension("OES_texture_half_float_linear") + }); + } else if (this.webGLVersion === 2) { + Object.assign(this.extensions, common, { + colorBufferFloat: gl.getExtension("EXT_color_buffer_float") + }); + } + } + handleContextLost(event) { + event.preventDefault(); + setTimeout(() => { + if (this.gl.isContextLost() && this.extensions.loseContext) { + this.extensions.loseContext.restoreContext(); + } + }, 0); + } + handleContextRestored() { + this.renderer.runners.contextChange.emit(this.gl); + } + destroy() { + const view = this.renderer.view; + this.renderer = null; + if (view.removeEventListener !== void 0) { + view.removeEventListener("webglcontextlost", this.handleContextLost); + view.removeEventListener("webglcontextrestored", this.handleContextRestored); + } + this.gl.useProgram(null); + if (this.extensions.loseContext) { + this.extensions.loseContext.loseContext(); + } + } + postrender() { + if (this.renderer.objectRenderer.renderingToScreen) { + this.gl.flush(); + } + } + validateContext(gl) { + const attributes = gl.getContextAttributes(); + const isWebGl2 = "WebGL2RenderingContext" in globalThis && gl instanceof globalThis.WebGL2RenderingContext; + if (isWebGl2) { + this.webGLVersion = 2; + } + if (attributes && !attributes.stencil) { + console.warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly"); + } + const hasuint32 = isWebGl2 || !!gl.getExtension("OES_element_index_uint"); + this.supports.uint32Indices = hasuint32; + if (!hasuint32) { + console.warn("Provided WebGL context does not support 32 index buffer, complex graphics may not render correctly"); + } + } + } + ContextSystem.defaultOptions = { + context: null, + antialias: false, + premultipliedAlpha: true, + preserveDrawingBuffer: false, + powerPreference: "default" + }; + ContextSystem.extension = { + type: ExtensionType.RendererSystem, + name: "context" + }; + extensions$1.add(ContextSystem); + + class DepthResource extends BufferResource { + upload(renderer, baseTexture, glTexture) { + const gl = renderer.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === ALPHA_MODES.UNPACK); + const width = baseTexture.realWidth; + const height = baseTexture.realHeight; + if (glTexture.width === width && glTexture.height === height) { + gl.texSubImage2D(baseTexture.target, 0, 0, 0, width, height, baseTexture.format, glTexture.type, this.data); + } else { + glTexture.width = width; + glTexture.height = height; + gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, width, height, 0, baseTexture.format, glTexture.type, this.data); + } + return true; + } + } + + class Framebuffer { + constructor(width, height) { + this.width = Math.round(width || 100); + this.height = Math.round(height || 100); + this.stencil = false; + this.depth = false; + this.dirtyId = 0; + this.dirtyFormat = 0; + this.dirtySize = 0; + this.depthTexture = null; + this.colorTextures = []; + this.glFramebuffers = {}; + this.disposeRunner = new Runner("disposeFramebuffer"); + this.multisample = MSAA_QUALITY.NONE; + } + get colorTexture() { + return this.colorTextures[0]; + } + addColorTexture(index = 0, texture) { + this.colorTextures[index] = texture || new BaseTexture(null, { + scaleMode: SCALE_MODES.NEAREST, + resolution: 1, + mipmap: MIPMAP_MODES.OFF, + width: this.width, + height: this.height + }); + this.dirtyId++; + this.dirtyFormat++; + return this; + } + addDepthTexture(texture) { + this.depthTexture = texture || new BaseTexture(new DepthResource(null, { width: this.width, height: this.height }), { + scaleMode: SCALE_MODES.NEAREST, + resolution: 1, + width: this.width, + height: this.height, + mipmap: MIPMAP_MODES.OFF, + format: FORMATS.DEPTH_COMPONENT, + type: TYPES.UNSIGNED_SHORT + }); + this.dirtyId++; + this.dirtyFormat++; + return this; + } + enableDepth() { + this.depth = true; + this.dirtyId++; + this.dirtyFormat++; + return this; + } + enableStencil() { + this.stencil = true; + this.dirtyId++; + this.dirtyFormat++; + return this; + } + resize(width, height) { + width = Math.round(width); + height = Math.round(height); + if (width === this.width && height === this.height) + return; + this.width = width; + this.height = height; + this.dirtyId++; + this.dirtySize++; + for (let i = 0; i < this.colorTextures.length; i++) { + const texture = this.colorTextures[i]; + const resolution = texture.resolution; + texture.setSize(width / resolution, height / resolution); + } + if (this.depthTexture) { + const resolution = this.depthTexture.resolution; + this.depthTexture.setSize(width / resolution, height / resolution); + } + } + dispose() { + this.disposeRunner.emit(this, false); + } + destroyDepthTexture() { + if (this.depthTexture) { + this.depthTexture.destroy(); + this.depthTexture = null; + ++this.dirtyId; + ++this.dirtyFormat; + } + } + } + + class BaseRenderTexture extends BaseTexture { + constructor(options = {}) { + if (typeof options === "number") { + const width = arguments[0]; + const height = arguments[1]; + const scaleMode = arguments[2]; + const resolution = arguments[3]; + options = { width, height, scaleMode, resolution }; + } + options.width = options.width || 100; + options.height = options.height || 100; + options.multisample ?? (options.multisample = MSAA_QUALITY.NONE); + super(null, options); + this.mipmap = MIPMAP_MODES.OFF; + this.valid = true; + this._clear = new Color([0, 0, 0, 0]); + this.framebuffer = new Framebuffer(this.realWidth, this.realHeight).addColorTexture(0, this); + this.framebuffer.multisample = options.multisample; + this.maskStack = []; + this.filterStack = [{}]; + } + set clearColor(value) { + this._clear.setValue(value); + } + get clearColor() { + return this._clear.value; + } + get clear() { + return this._clear; + } + resize(desiredWidth, desiredHeight) { + this.framebuffer.resize(desiredWidth * this.resolution, desiredHeight * this.resolution); + this.setRealSize(this.framebuffer.width, this.framebuffer.height); + } + dispose() { + this.framebuffer.dispose(); + super.dispose(); + } + destroy() { + super.destroy(); + this.framebuffer.destroyDepthTexture(); + this.framebuffer = null; + } + } + + class BaseImageResource extends Resource { + constructor(source) { + const sourceAny = source; + const width = sourceAny.naturalWidth || sourceAny.videoWidth || sourceAny.width; + const height = sourceAny.naturalHeight || sourceAny.videoHeight || sourceAny.height; + super(width, height); + this.source = source; + this.noSubImage = false; + } + static crossOrigin(element, url, crossorigin) { + if (crossorigin === void 0 && !url.startsWith("data:")) { + element.crossOrigin = determineCrossOrigin(url); + } else if (crossorigin !== false) { + element.crossOrigin = typeof crossorigin === "string" ? crossorigin : "anonymous"; + } + } + upload(renderer, baseTexture, glTexture, source) { + const gl = renderer.gl; + const width = baseTexture.realWidth; + const height = baseTexture.realHeight; + source = source || this.source; + if (typeof HTMLImageElement !== "undefined" && source instanceof HTMLImageElement) { + if (!source.complete || source.naturalWidth === 0) { + return false; + } + } else if (typeof HTMLVideoElement !== "undefined" && source instanceof HTMLVideoElement) { + if (source.readyState <= 1 && source.buffered.length === 0) { + return false; + } + } + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === ALPHA_MODES.UNPACK); + if (!this.noSubImage && baseTexture.target === gl.TEXTURE_2D && glTexture.width === width && glTexture.height === height) { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, baseTexture.format, glTexture.type, source); + } else { + glTexture.width = width; + glTexture.height = height; + gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, baseTexture.format, glTexture.type, source); + } + return true; + } + update() { + if (this.destroyed) { + return; + } + const source = this.source; + const width = source.naturalWidth || source.videoWidth || source.width; + const height = source.naturalHeight || source.videoHeight || source.height; + this.resize(width, height); + super.update(); + } + dispose() { + this.source = null; + } + } + + class ImageResource extends BaseImageResource { + constructor(source, options) { + options = options || {}; + if (typeof source === "string") { + const imageElement = new Image(); + BaseImageResource.crossOrigin(imageElement, source, options.crossorigin); + imageElement.src = source; + source = imageElement; + } + super(source); + if (!source.complete && !!this._width && !!this._height) { + this._width = 0; + this._height = 0; + } + this.url = source.src; + this._process = null; + this.preserveBitmap = false; + this.createBitmap = (options.createBitmap ?? settings.CREATE_IMAGE_BITMAP) && !!globalThis.createImageBitmap; + this.alphaMode = typeof options.alphaMode === "number" ? options.alphaMode : null; + this.bitmap = null; + this._load = null; + if (options.autoLoad !== false) { + this.load(); + } + } + load(createBitmap) { + if (this._load) { + return this._load; + } + if (createBitmap !== void 0) { + this.createBitmap = createBitmap; + } + this._load = new Promise((resolve, reject) => { + const source = this.source; + this.url = source.src; + const completed = () => { + if (this.destroyed) { + return; + } + source.onload = null; + source.onerror = null; + this.resize(source.width, source.height); + this._load = null; + if (this.createBitmap) { + resolve(this.process()); + } else { + resolve(this); + } + }; + if (source.complete && source.src) { + completed(); + } else { + source.onload = completed; + source.onerror = (event) => { + reject(event); + this.onError.emit(event); + }; + } + }); + return this._load; + } + process() { + const source = this.source; + if (this._process !== null) { + return this._process; + } + if (this.bitmap !== null || !globalThis.createImageBitmap) { + return Promise.resolve(this); + } + const createImageBitmap = globalThis.createImageBitmap; + const cors = !source.crossOrigin || source.crossOrigin === "anonymous"; + this._process = fetch(source.src, { + mode: cors ? "cors" : "no-cors" + }).then((r) => r.blob()).then((blob) => createImageBitmap(blob, 0, 0, source.width, source.height, { + premultiplyAlpha: this.alphaMode === null || this.alphaMode === ALPHA_MODES.UNPACK ? "premultiply" : "none" + })).then((bitmap) => { + if (this.destroyed) { + return Promise.reject(); + } + this.bitmap = bitmap; + this.update(); + this._process = null; + return Promise.resolve(this); + }); + return this._process; + } + upload(renderer, baseTexture, glTexture) { + if (typeof this.alphaMode === "number") { + baseTexture.alphaMode = this.alphaMode; + } + if (!this.createBitmap) { + return super.upload(renderer, baseTexture, glTexture); + } + if (!this.bitmap) { + this.process(); + if (!this.bitmap) { + return false; + } + } + super.upload(renderer, baseTexture, glTexture, this.bitmap); + if (!this.preserveBitmap) { + let flag = true; + const glTextures = baseTexture._glTextures; + for (const key in glTextures) { + const otherTex = glTextures[key]; + if (otherTex !== glTexture && otherTex.dirtyId !== baseTexture.dirtyId) { + flag = false; + break; + } + } + if (flag) { + if (this.bitmap.close) { + this.bitmap.close(); + } + this.bitmap = null; + } + } + return true; + } + dispose() { + this.source.onload = null; + this.source.onerror = null; + super.dispose(); + if (this.bitmap) { + this.bitmap.close(); + this.bitmap = null; + } + this._process = null; + this._load = null; + } + static test(source) { + return typeof HTMLImageElement !== "undefined" && (typeof source === "string" || source instanceof HTMLImageElement); + } + } + + class TextureUvs { + constructor() { + this.x0 = 0; + this.y0 = 0; + this.x1 = 1; + this.y1 = 0; + this.x2 = 1; + this.y2 = 1; + this.x3 = 0; + this.y3 = 1; + this.uvsFloat32 = new Float32Array(8); + } + set(frame, baseFrame, rotate) { + const tw = baseFrame.width; + const th = baseFrame.height; + if (rotate) { + const w2 = frame.width / 2 / tw; + const h2 = frame.height / 2 / th; + const cX = frame.x / tw + w2; + const cY = frame.y / th + h2; + rotate = groupD8.add(rotate, groupD8.NW); + this.x0 = cX + w2 * groupD8.uX(rotate); + this.y0 = cY + h2 * groupD8.uY(rotate); + rotate = groupD8.add(rotate, 2); + this.x1 = cX + w2 * groupD8.uX(rotate); + this.y1 = cY + h2 * groupD8.uY(rotate); + rotate = groupD8.add(rotate, 2); + this.x2 = cX + w2 * groupD8.uX(rotate); + this.y2 = cY + h2 * groupD8.uY(rotate); + rotate = groupD8.add(rotate, 2); + this.x3 = cX + w2 * groupD8.uX(rotate); + this.y3 = cY + h2 * groupD8.uY(rotate); + } else { + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + this.uvsFloat32[0] = this.x0; + this.uvsFloat32[1] = this.y0; + this.uvsFloat32[2] = this.x1; + this.uvsFloat32[3] = this.y1; + this.uvsFloat32[4] = this.x2; + this.uvsFloat32[5] = this.y2; + this.uvsFloat32[6] = this.x3; + this.uvsFloat32[7] = this.y3; + } + toString() { + return `[@pixi/core:TextureUvs x0=${this.x0} y0=${this.y0} x1=${this.x1} y1=${this.y1} x2=${this.x2} y2=${this.y2} x3=${this.x3} y3=${this.y3}]`; + } + } + + const DEFAULT_UVS = new TextureUvs(); + function removeAllHandlers(tex) { + tex.destroy = function _emptyDestroy() { + }; + tex.on = function _emptyOn() { + }; + tex.once = function _emptyOnce() { + }; + tex.emit = function _emptyEmit() { + }; + } + class Texture extends eventemitter3 { + constructor(baseTexture, frame, orig, trim, rotate, anchor, borders) { + super(); + this.noFrame = false; + if (!frame) { + this.noFrame = true; + frame = new Rectangle(0, 0, 1, 1); + } + if (baseTexture instanceof Texture) { + baseTexture = baseTexture.baseTexture; + } + this.baseTexture = baseTexture; + this._frame = frame; + this.trim = trim; + this.valid = false; + this._uvs = DEFAULT_UVS; + this.uvMatrix = null; + this.orig = orig || frame; + this._rotate = Number(rotate || 0); + if (rotate === true) { + this._rotate = 2; + } else if (this._rotate % 2 !== 0) { + throw new Error("attempt to use diamond-shaped UVs. If you are sure, set rotation manually"); + } + this.defaultAnchor = anchor ? new Point(anchor.x, anchor.y) : new Point(0, 0); + this.defaultBorders = borders; + this._updateID = 0; + this.textureCacheIds = []; + if (!baseTexture.valid) { + baseTexture.once("loaded", this.onBaseTextureUpdated, this); + } else if (this.noFrame) { + if (baseTexture.valid) { + this.onBaseTextureUpdated(baseTexture); + } + } else { + this.frame = frame; + } + if (this.noFrame) { + baseTexture.on("update", this.onBaseTextureUpdated, this); + } + } + update() { + if (this.baseTexture.resource) { + this.baseTexture.resource.update(); + } + } + onBaseTextureUpdated(baseTexture) { + if (this.noFrame) { + if (!this.baseTexture.valid) { + return; + } + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + this.valid = true; + this.updateUvs(); + } else { + this.frame = this._frame; + } + this.emit("update", this); + } + destroy(destroyBase) { + if (this.baseTexture) { + if (destroyBase) { + const { resource } = this.baseTexture; + if (resource?.url && TextureCache[resource.url]) { + Texture.removeFromCache(resource.url); + } + this.baseTexture.destroy(); + } + this.baseTexture.off("loaded", this.onBaseTextureUpdated, this); + this.baseTexture.off("update", this.onBaseTextureUpdated, this); + this.baseTexture = null; + } + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + this.valid = false; + Texture.removeFromCache(this); + this.textureCacheIds = null; + } + clone() { + const clonedFrame = this._frame.clone(); + const clonedOrig = this._frame === this.orig ? clonedFrame : this.orig.clone(); + const clonedTexture = new Texture(this.baseTexture, !this.noFrame && clonedFrame, clonedOrig, this.trim?.clone(), this.rotate, this.defaultAnchor, this.defaultBorders); + if (this.noFrame) { + clonedTexture._frame = clonedFrame; + } + return clonedTexture; + } + updateUvs() { + if (this._uvs === DEFAULT_UVS) { + this._uvs = new TextureUvs(); + } + this._uvs.set(this._frame, this.baseTexture, this.rotate); + this._updateID++; + } + static from(source, options = {}, strict = settings.STRICT_TEXTURE_CACHE) { + const isFrame = typeof source === "string"; + let cacheId = null; + if (isFrame) { + cacheId = source; + } else if (source instanceof BaseTexture) { + if (!source.cacheId) { + const prefix = options?.pixiIdPrefix || "pixiid"; + source.cacheId = `${prefix}-${uid()}`; + BaseTexture.addToCache(source, source.cacheId); + } + cacheId = source.cacheId; + } else { + if (!source._pixiId) { + const prefix = options?.pixiIdPrefix || "pixiid"; + source._pixiId = `${prefix}_${uid()}`; + } + cacheId = source._pixiId; + } + let texture = TextureCache[cacheId]; + if (isFrame && strict && !texture) { + throw new Error(`The cacheId "${cacheId}" does not exist in TextureCache.`); + } + if (!texture && !(source instanceof BaseTexture)) { + if (!options.resolution) { + options.resolution = getResolutionOfUrl(source); + } + texture = new Texture(new BaseTexture(source, options)); + texture.baseTexture.cacheId = cacheId; + BaseTexture.addToCache(texture.baseTexture, cacheId); + Texture.addToCache(texture, cacheId); + } else if (!texture && source instanceof BaseTexture) { + texture = new Texture(source); + Texture.addToCache(texture, cacheId); + } + return texture; + } + static fromURL(url, options) { + const resourceOptions = Object.assign({ autoLoad: false }, options?.resourceOptions); + const texture = Texture.from(url, Object.assign({ resourceOptions }, options), false); + const resource = texture.baseTexture.resource; + if (texture.baseTexture.valid) { + return Promise.resolve(texture); + } + return resource.load().then(() => Promise.resolve(texture)); + } + static fromBuffer(buffer, width, height, options) { + return new Texture(BaseTexture.fromBuffer(buffer, width, height, options)); + } + static fromLoader(source, imageUrl, name, options) { + const baseTexture = new BaseTexture(source, Object.assign({ + scaleMode: BaseTexture.defaultOptions.scaleMode, + resolution: getResolutionOfUrl(imageUrl) + }, options)); + const { resource } = baseTexture; + if (resource instanceof ImageResource) { + resource.url = imageUrl; + } + const texture = new Texture(baseTexture); + if (!name) { + name = imageUrl; + } + BaseTexture.addToCache(texture.baseTexture, name); + Texture.addToCache(texture, name); + if (name !== imageUrl) { + BaseTexture.addToCache(texture.baseTexture, imageUrl); + Texture.addToCache(texture, imageUrl); + } + if (texture.baseTexture.valid) { + return Promise.resolve(texture); + } + return new Promise((resolve) => { + texture.baseTexture.once("loaded", () => resolve(texture)); + }); + } + static addToCache(texture, id) { + if (id) { + if (!texture.textureCacheIds.includes(id)) { + texture.textureCacheIds.push(id); + } + if (TextureCache[id] && TextureCache[id] !== texture) { + console.warn(`Texture added to the cache with an id [${id}] that already had an entry`); + } + TextureCache[id] = texture; + } + } + static removeFromCache(texture) { + if (typeof texture === "string") { + const textureFromCache = TextureCache[texture]; + if (textureFromCache) { + const index = textureFromCache.textureCacheIds.indexOf(texture); + if (index > -1) { + textureFromCache.textureCacheIds.splice(index, 1); + } + delete TextureCache[texture]; + return textureFromCache; + } + } else if (texture?.textureCacheIds) { + for (let i = 0; i < texture.textureCacheIds.length; ++i) { + if (TextureCache[texture.textureCacheIds[i]] === texture) { + delete TextureCache[texture.textureCacheIds[i]]; + } + } + texture.textureCacheIds.length = 0; + return texture; + } + return null; + } + get resolution() { + return this.baseTexture.resolution; + } + get frame() { + return this._frame; + } + set frame(frame) { + this._frame = frame; + this.noFrame = false; + const { x, y, width, height } = frame; + const xNotFit = x + width > this.baseTexture.width; + const yNotFit = y + height > this.baseTexture.height; + if (xNotFit || yNotFit) { + const relationship = xNotFit && yNotFit ? "and" : "or"; + const errorX = `X: ${x} + ${width} = ${x + width} > ${this.baseTexture.width}`; + const errorY = `Y: ${y} + ${height} = ${y + height} > ${this.baseTexture.height}`; + throw new Error(`Texture Error: frame does not fit inside the base Texture dimensions: ${errorX} ${relationship} ${errorY}`); + } + this.valid = width && height && this.baseTexture.valid; + if (!this.trim && !this.rotate) { + this.orig = frame; + } + if (this.valid) { + this.updateUvs(); + } + } + get rotate() { + return this._rotate; + } + set rotate(rotate) { + this._rotate = rotate; + if (this.valid) { + this.updateUvs(); + } + } + get width() { + return this.orig.width; + } + get height() { + return this.orig.height; + } + castToBaseTexture() { + return this.baseTexture; + } + static get EMPTY() { + if (!Texture._EMPTY) { + Texture._EMPTY = new Texture(new BaseTexture()); + removeAllHandlers(Texture._EMPTY); + removeAllHandlers(Texture._EMPTY.baseTexture); + } + return Texture._EMPTY; + } + static get WHITE() { + if (!Texture._WHITE) { + const canvas = settings.ADAPTER.createCanvas(16, 16); + const context = canvas.getContext("2d"); + canvas.width = 16; + canvas.height = 16; + context.fillStyle = "white"; + context.fillRect(0, 0, 16, 16); + Texture._WHITE = new Texture(BaseTexture.from(canvas)); + removeAllHandlers(Texture._WHITE); + removeAllHandlers(Texture._WHITE.baseTexture); + } + return Texture._WHITE; + } + } + + class RenderTexture extends Texture { + constructor(baseRenderTexture, frame) { + super(baseRenderTexture, frame); + this.valid = true; + this.filterFrame = null; + this.filterPoolKey = null; + this.updateUvs(); + } + get framebuffer() { + return this.baseTexture.framebuffer; + } + get multisample() { + return this.framebuffer.multisample; + } + set multisample(value) { + this.framebuffer.multisample = value; + } + resize(desiredWidth, desiredHeight, resizeBaseTexture = true) { + const resolution = this.baseTexture.resolution; + const width = Math.round(desiredWidth * resolution) / resolution; + const height = Math.round(desiredHeight * resolution) / resolution; + this.valid = width > 0 && height > 0; + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + if (resizeBaseTexture) { + this.baseTexture.resize(width, height); + } + this.updateUvs(); + } + setResolution(resolution) { + const { baseTexture } = this; + if (baseTexture.resolution === resolution) { + return; + } + baseTexture.setResolution(resolution); + this.resize(baseTexture.width, baseTexture.height, false); + } + static create(options) { + return new RenderTexture(new BaseRenderTexture(options)); + } + } + + class RenderTexturePool { + constructor(textureOptions) { + this.texturePool = {}; + this.textureOptions = textureOptions || {}; + this.enableFullScreen = false; + this._pixelsWidth = 0; + this._pixelsHeight = 0; + } + createTexture(realWidth, realHeight, multisample = MSAA_QUALITY.NONE) { + const baseRenderTexture = new BaseRenderTexture(Object.assign({ + width: realWidth, + height: realHeight, + resolution: 1, + multisample + }, this.textureOptions)); + return new RenderTexture(baseRenderTexture); + } + getOptimalTexture(minWidth, minHeight, resolution = 1, multisample = MSAA_QUALITY.NONE) { + let key; + minWidth = Math.ceil(minWidth * resolution - 1e-6); + minHeight = Math.ceil(minHeight * resolution - 1e-6); + if (!this.enableFullScreen || minWidth !== this._pixelsWidth || minHeight !== this._pixelsHeight) { + minWidth = nextPow2(minWidth); + minHeight = nextPow2(minHeight); + key = ((minWidth & 65535) << 16 | minHeight & 65535) >>> 0; + if (multisample > 1) { + key += multisample * 4294967296; + } + } else { + key = multisample > 1 ? -multisample : -1; + } + if (!this.texturePool[key]) { + this.texturePool[key] = []; + } + let renderTexture = this.texturePool[key].pop(); + if (!renderTexture) { + renderTexture = this.createTexture(minWidth, minHeight, multisample); + } + renderTexture.filterPoolKey = key; + renderTexture.setResolution(resolution); + return renderTexture; + } + getFilterTexture(input, resolution, multisample) { + const filterTexture = this.getOptimalTexture(input.width, input.height, resolution || input.resolution, multisample || MSAA_QUALITY.NONE); + filterTexture.filterFrame = input.filterFrame; + return filterTexture; + } + returnTexture(renderTexture) { + const key = renderTexture.filterPoolKey; + renderTexture.filterFrame = null; + this.texturePool[key].push(renderTexture); + } + returnFilterTexture(renderTexture) { + this.returnTexture(renderTexture); + } + clear(destroyTextures) { + destroyTextures = destroyTextures !== false; + if (destroyTextures) { + for (const i in this.texturePool) { + const textures = this.texturePool[i]; + if (textures) { + for (let j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + } + } + this.texturePool = {}; + } + setScreenSize(size) { + if (size.width === this._pixelsWidth && size.height === this._pixelsHeight) { + return; + } + this.enableFullScreen = size.width > 0 && size.height > 0; + for (const i in this.texturePool) { + if (!(Number(i) < 0)) { + continue; + } + const textures = this.texturePool[i]; + if (textures) { + for (let j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + this.texturePool[i] = []; + } + this._pixelsWidth = size.width; + this._pixelsHeight = size.height; + } + } + RenderTexturePool.SCREEN_KEY = -1; + + class Quad extends Geometry { + constructor() { + super(); + this.addAttribute("aVertexPosition", new Float32Array([ + 0, + 0, + 1, + 0, + 1, + 1, + 0, + 1 + ])).addIndex([0, 1, 3, 2]); + } + } + + class QuadUv extends Geometry { + constructor() { + super(); + this.vertices = new Float32Array([ + -1, + -1, + 1, + -1, + 1, + 1, + -1, + 1 + ]); + this.uvs = new Float32Array([ + 0, + 0, + 1, + 0, + 1, + 1, + 0, + 1 + ]); + this.vertexBuffer = new Buffer(this.vertices); + this.uvBuffer = new Buffer(this.uvs); + this.addAttribute("aVertexPosition", this.vertexBuffer).addAttribute("aTextureCoord", this.uvBuffer).addIndex([0, 1, 2, 0, 2, 3]); + } + map(targetTextureFrame, destinationFrame) { + let x = 0; + let y = 0; + this.uvs[0] = x; + this.uvs[1] = y; + this.uvs[2] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[3] = y; + this.uvs[4] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[5] = y + destinationFrame.height / targetTextureFrame.height; + this.uvs[6] = x; + this.uvs[7] = y + destinationFrame.height / targetTextureFrame.height; + x = destinationFrame.x; + y = destinationFrame.y; + this.vertices[0] = x; + this.vertices[1] = y; + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + this.invalidate(); + return this; + } + invalidate() { + this.vertexBuffer._updateID++; + this.uvBuffer._updateID++; + return this; + } + } + + class FilterState { + constructor() { + this.renderTexture = null; + this.target = null; + this.legacy = false; + this.resolution = 1; + this.multisample = MSAA_QUALITY.NONE; + this.sourceFrame = new Rectangle(); + this.destinationFrame = new Rectangle(); + this.bindingSourceFrame = new Rectangle(); + this.bindingDestinationFrame = new Rectangle(); + this.filters = []; + this.transform = null; + } + clear() { + this.target = null; + this.filters = null; + this.renderTexture = null; + } + } + + const tempPoints = [new Point(), new Point(), new Point(), new Point()]; + const tempMatrix$4 = new Matrix(); + class FilterSystem { + constructor(renderer) { + this.renderer = renderer; + this.defaultFilterStack = [{}]; + this.texturePool = new RenderTexturePool(); + this.statePool = []; + this.quad = new Quad(); + this.quadUv = new QuadUv(); + this.tempRect = new Rectangle(); + this.activeState = {}; + this.globalUniforms = new UniformGroup({ + outputFrame: new Rectangle(), + inputSize: new Float32Array(4), + inputPixel: new Float32Array(4), + inputClamp: new Float32Array(4), + resolution: 1, + filterArea: new Float32Array(4), + filterClamp: new Float32Array(4) + }, true); + this.forceClear = false; + this.useMaxPadding = false; + } + init() { + this.texturePool.setScreenSize(this.renderer.view); + } + push(target, filters) { + const renderer = this.renderer; + const filterStack = this.defaultFilterStack; + const state = this.statePool.pop() || new FilterState(); + const renderTextureSystem = this.renderer.renderTexture; + let resolution = filters[0].resolution; + let multisample = filters[0].multisample; + let padding = filters[0].padding; + let autoFit = filters[0].autoFit; + let legacy = filters[0].legacy ?? true; + for (let i = 1; i < filters.length; i++) { + const filter = filters[i]; + resolution = Math.min(resolution, filter.resolution); + multisample = Math.min(multisample, filter.multisample); + padding = this.useMaxPadding ? Math.max(padding, filter.padding) : padding + filter.padding; + autoFit = autoFit && filter.autoFit; + legacy = legacy || (filter.legacy ?? true); + } + if (filterStack.length === 1) { + this.defaultFilterStack[0].renderTexture = renderTextureSystem.current; + } + filterStack.push(state); + state.resolution = resolution; + state.multisample = multisample; + state.legacy = legacy; + state.target = target; + state.sourceFrame.copyFrom(target.filterArea || target.getBounds(true)); + state.sourceFrame.pad(padding); + const sourceFrameProjected = this.tempRect.copyFrom(renderTextureSystem.sourceFrame); + if (renderer.projection.transform) { + this.transformAABB(tempMatrix$4.copyFrom(renderer.projection.transform).invert(), sourceFrameProjected); + } + if (autoFit) { + state.sourceFrame.fit(sourceFrameProjected); + if (state.sourceFrame.width <= 0 || state.sourceFrame.height <= 0) { + state.sourceFrame.width = 0; + state.sourceFrame.height = 0; + } + } else if (!state.sourceFrame.intersects(sourceFrameProjected)) { + state.sourceFrame.width = 0; + state.sourceFrame.height = 0; + } + this.roundFrame(state.sourceFrame, renderTextureSystem.current ? renderTextureSystem.current.resolution : renderer.resolution, renderTextureSystem.sourceFrame, renderTextureSystem.destinationFrame, renderer.projection.transform); + state.renderTexture = this.getOptimalFilterTexture(state.sourceFrame.width, state.sourceFrame.height, resolution, multisample); + state.filters = filters; + state.destinationFrame.width = state.renderTexture.width; + state.destinationFrame.height = state.renderTexture.height; + const destinationFrame = this.tempRect; + destinationFrame.x = 0; + destinationFrame.y = 0; + destinationFrame.width = state.sourceFrame.width; + destinationFrame.height = state.sourceFrame.height; + state.renderTexture.filterFrame = state.sourceFrame; + state.bindingSourceFrame.copyFrom(renderTextureSystem.sourceFrame); + state.bindingDestinationFrame.copyFrom(renderTextureSystem.destinationFrame); + state.transform = renderer.projection.transform; + renderer.projection.transform = null; + renderTextureSystem.bind(state.renderTexture, state.sourceFrame, destinationFrame); + renderer.framebuffer.clear(0, 0, 0, 0); + } + pop() { + const filterStack = this.defaultFilterStack; + const state = filterStack.pop(); + const filters = state.filters; + this.activeState = state; + const globalUniforms = this.globalUniforms.uniforms; + globalUniforms.outputFrame = state.sourceFrame; + globalUniforms.resolution = state.resolution; + const inputSize = globalUniforms.inputSize; + const inputPixel = globalUniforms.inputPixel; + const inputClamp = globalUniforms.inputClamp; + inputSize[0] = state.destinationFrame.width; + inputSize[1] = state.destinationFrame.height; + inputSize[2] = 1 / inputSize[0]; + inputSize[3] = 1 / inputSize[1]; + inputPixel[0] = Math.round(inputSize[0] * state.resolution); + inputPixel[1] = Math.round(inputSize[1] * state.resolution); + inputPixel[2] = 1 / inputPixel[0]; + inputPixel[3] = 1 / inputPixel[1]; + inputClamp[0] = 0.5 * inputPixel[2]; + inputClamp[1] = 0.5 * inputPixel[3]; + inputClamp[2] = state.sourceFrame.width * inputSize[2] - 0.5 * inputPixel[2]; + inputClamp[3] = state.sourceFrame.height * inputSize[3] - 0.5 * inputPixel[3]; + if (state.legacy) { + const filterArea = globalUniforms.filterArea; + filterArea[0] = state.destinationFrame.width; + filterArea[1] = state.destinationFrame.height; + filterArea[2] = state.sourceFrame.x; + filterArea[3] = state.sourceFrame.y; + globalUniforms.filterClamp = globalUniforms.inputClamp; + } + this.globalUniforms.update(); + const lastState = filterStack[filterStack.length - 1]; + this.renderer.framebuffer.blit(); + if (filters.length === 1) { + filters[0].apply(this, state.renderTexture, lastState.renderTexture, CLEAR_MODES.BLEND, state); + this.returnFilterTexture(state.renderTexture); + } else { + let flip = state.renderTexture; + let flop = this.getOptimalFilterTexture(flip.width, flip.height, state.resolution); + flop.filterFrame = flip.filterFrame; + let i = 0; + for (i = 0; i < filters.length - 1; ++i) { + if (i === 1 && state.multisample > 1) { + flop = this.getOptimalFilterTexture(flip.width, flip.height, state.resolution); + flop.filterFrame = flip.filterFrame; + } + filters[i].apply(this, flip, flop, CLEAR_MODES.CLEAR, state); + const t = flip; + flip = flop; + flop = t; + } + filters[i].apply(this, flip, lastState.renderTexture, CLEAR_MODES.BLEND, state); + if (i > 1 && state.multisample > 1) { + this.returnFilterTexture(state.renderTexture); + } + this.returnFilterTexture(flip); + this.returnFilterTexture(flop); + } + state.clear(); + this.statePool.push(state); + } + bindAndClear(filterTexture, clearMode = CLEAR_MODES.CLEAR) { + const { + renderTexture: renderTextureSystem, + state: stateSystem + } = this.renderer; + if (filterTexture === this.defaultFilterStack[this.defaultFilterStack.length - 1].renderTexture) { + this.renderer.projection.transform = this.activeState.transform; + } else { + this.renderer.projection.transform = null; + } + if (filterTexture?.filterFrame) { + const destinationFrame = this.tempRect; + destinationFrame.x = 0; + destinationFrame.y = 0; + destinationFrame.width = filterTexture.filterFrame.width; + destinationFrame.height = filterTexture.filterFrame.height; + renderTextureSystem.bind(filterTexture, filterTexture.filterFrame, destinationFrame); + } else if (filterTexture !== this.defaultFilterStack[this.defaultFilterStack.length - 1].renderTexture) { + renderTextureSystem.bind(filterTexture); + } else { + this.renderer.renderTexture.bind(filterTexture, this.activeState.bindingSourceFrame, this.activeState.bindingDestinationFrame); + } + const autoClear = stateSystem.stateId & 1 || this.forceClear; + if (clearMode === CLEAR_MODES.CLEAR || clearMode === CLEAR_MODES.BLIT && autoClear) { + this.renderer.framebuffer.clear(0, 0, 0, 0); + } + } + applyFilter(filter, input, output, clearMode) { + const renderer = this.renderer; + renderer.state.set(filter.state); + this.bindAndClear(output, clearMode); + filter.uniforms.uSampler = input; + filter.uniforms.filterGlobals = this.globalUniforms; + renderer.shader.bind(filter); + filter.legacy = !!filter.program.attributeData.aTextureCoord; + if (filter.legacy) { + this.quadUv.map(input._frame, input.filterFrame); + renderer.geometry.bind(this.quadUv); + renderer.geometry.draw(DRAW_MODES.TRIANGLES); + } else { + renderer.geometry.bind(this.quad); + renderer.geometry.draw(DRAW_MODES.TRIANGLE_STRIP); + } + } + calculateSpriteMatrix(outputMatrix, sprite) { + const { sourceFrame, destinationFrame } = this.activeState; + const { orig } = sprite._texture; + const mappedMatrix = outputMatrix.set(destinationFrame.width, 0, 0, destinationFrame.height, sourceFrame.x, sourceFrame.y); + const worldTransform = sprite.worldTransform.copyTo(Matrix.TEMP_MATRIX); + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + mappedMatrix.scale(1 / orig.width, 1 / orig.height); + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + return mappedMatrix; + } + destroy() { + this.renderer = null; + this.texturePool.clear(false); + } + getOptimalFilterTexture(minWidth, minHeight, resolution = 1, multisample = MSAA_QUALITY.NONE) { + return this.texturePool.getOptimalTexture(minWidth, minHeight, resolution, multisample); + } + getFilterTexture(input, resolution, multisample) { + if (typeof input === "number") { + const swap = input; + input = resolution; + resolution = swap; + } + input = input || this.activeState.renderTexture; + const filterTexture = this.texturePool.getOptimalTexture(input.width, input.height, resolution || input.resolution, multisample || MSAA_QUALITY.NONE); + filterTexture.filterFrame = input.filterFrame; + return filterTexture; + } + returnFilterTexture(renderTexture) { + this.texturePool.returnTexture(renderTexture); + } + emptyPool() { + this.texturePool.clear(true); + } + resize() { + this.texturePool.setScreenSize(this.renderer.view); + } + transformAABB(matrix, rect) { + const lt = tempPoints[0]; + const lb = tempPoints[1]; + const rt = tempPoints[2]; + const rb = tempPoints[3]; + lt.set(rect.left, rect.top); + lb.set(rect.left, rect.bottom); + rt.set(rect.right, rect.top); + rb.set(rect.right, rect.bottom); + matrix.apply(lt, lt); + matrix.apply(lb, lb); + matrix.apply(rt, rt); + matrix.apply(rb, rb); + const x0 = Math.min(lt.x, lb.x, rt.x, rb.x); + const y0 = Math.min(lt.y, lb.y, rt.y, rb.y); + const x1 = Math.max(lt.x, lb.x, rt.x, rb.x); + const y1 = Math.max(lt.y, lb.y, rt.y, rb.y); + rect.x = x0; + rect.y = y0; + rect.width = x1 - x0; + rect.height = y1 - y0; + } + roundFrame(frame, resolution, bindingSourceFrame, bindingDestinationFrame, transform) { + if (frame.width <= 0 || frame.height <= 0 || bindingSourceFrame.width <= 0 || bindingSourceFrame.height <= 0) { + return; + } + if (transform) { + const { a, b, c, d } = transform; + if ((Math.abs(b) > 1e-4 || Math.abs(c) > 1e-4) && (Math.abs(a) > 1e-4 || Math.abs(d) > 1e-4)) { + return; + } + } + transform = transform ? tempMatrix$4.copyFrom(transform) : tempMatrix$4.identity(); + transform.translate(-bindingSourceFrame.x, -bindingSourceFrame.y).scale(bindingDestinationFrame.width / bindingSourceFrame.width, bindingDestinationFrame.height / bindingSourceFrame.height).translate(bindingDestinationFrame.x, bindingDestinationFrame.y); + this.transformAABB(transform, frame); + frame.ceil(resolution); + this.transformAABB(transform.invert(), frame); + } + } + FilterSystem.extension = { + type: ExtensionType.RendererSystem, + name: "filter" + }; + extensions$1.add(FilterSystem); + + class GLFramebuffer { + constructor(framebuffer) { + this.framebuffer = framebuffer; + this.stencil = null; + this.dirtyId = -1; + this.dirtyFormat = -1; + this.dirtySize = -1; + this.multisample = MSAA_QUALITY.NONE; + this.msaaBuffer = null; + this.blitFramebuffer = null; + this.mipLevel = 0; + } + } + + const tempRectangle = new Rectangle(); + class FramebufferSystem { + constructor(renderer) { + this.renderer = renderer; + this.managedFramebuffers = []; + this.unknownFramebuffer = new Framebuffer(10, 10); + this.msaaSamples = null; + } + contextChange() { + this.disposeAll(true); + const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.current = this.unknownFramebuffer; + this.viewport = new Rectangle(); + this.hasMRT = true; + this.writeDepthTexture = true; + if (this.renderer.context.webGLVersion === 1) { + let nativeDrawBuffersExtension = this.renderer.context.extensions.drawBuffers; + let nativeDepthTextureExtension = this.renderer.context.extensions.depthTexture; + if (settings.PREFER_ENV === ENV.WEBGL_LEGACY) { + nativeDrawBuffersExtension = null; + nativeDepthTextureExtension = null; + } + if (nativeDrawBuffersExtension) { + gl.drawBuffers = (activeTextures) => nativeDrawBuffersExtension.drawBuffersWEBGL(activeTextures); + } else { + this.hasMRT = false; + gl.drawBuffers = () => { + }; + } + if (!nativeDepthTextureExtension) { + this.writeDepthTexture = false; + } + } else { + this.msaaSamples = gl.getInternalformatParameter(gl.RENDERBUFFER, gl.RGBA8, gl.SAMPLES); + } + } + bind(framebuffer, frame, mipLevel = 0) { + const { gl } = this; + if (framebuffer) { + const fbo = framebuffer.glFramebuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + if (this.current !== framebuffer) { + this.current = framebuffer; + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); + } + if (fbo.mipLevel !== mipLevel) { + framebuffer.dirtyId++; + framebuffer.dirtyFormat++; + fbo.mipLevel = mipLevel; + } + if (fbo.dirtyId !== framebuffer.dirtyId) { + fbo.dirtyId = framebuffer.dirtyId; + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { + fbo.dirtyFormat = framebuffer.dirtyFormat; + fbo.dirtySize = framebuffer.dirtySize; + this.updateFramebuffer(framebuffer, mipLevel); + } else if (fbo.dirtySize !== framebuffer.dirtySize) { + fbo.dirtySize = framebuffer.dirtySize; + this.resizeFramebuffer(framebuffer); + } + } + for (let i = 0; i < framebuffer.colorTextures.length; i++) { + const tex = framebuffer.colorTextures[i]; + this.renderer.texture.unbind(tex.parentTextureArray || tex); + } + if (framebuffer.depthTexture) { + this.renderer.texture.unbind(framebuffer.depthTexture); + } + if (frame) { + const mipWidth = frame.width >> mipLevel; + const mipHeight = frame.height >> mipLevel; + const scale = mipWidth / frame.width; + this.setViewport(frame.x * scale, frame.y * scale, mipWidth, mipHeight); + } else { + const mipWidth = framebuffer.width >> mipLevel; + const mipHeight = framebuffer.height >> mipLevel; + this.setViewport(0, 0, mipWidth, mipHeight); + } + } else { + if (this.current) { + this.current = null; + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + } + if (frame) { + this.setViewport(frame.x, frame.y, frame.width, frame.height); + } else { + this.setViewport(0, 0, this.renderer.width, this.renderer.height); + } + } + } + setViewport(x, y, width, height) { + const v = this.viewport; + x = Math.round(x); + y = Math.round(y); + width = Math.round(width); + height = Math.round(height); + if (v.width !== width || v.height !== height || v.x !== x || v.y !== y) { + v.x = x; + v.y = y; + v.width = width; + v.height = height; + this.gl.viewport(x, y, width, height); + } + } + get size() { + if (this.current) { + return { x: 0, y: 0, width: this.current.width, height: this.current.height }; + } + return { x: 0, y: 0, width: this.renderer.width, height: this.renderer.height }; + } + clear(r, g, b, a, mask = BUFFER_BITS.COLOR | BUFFER_BITS.DEPTH) { + const { gl } = this; + gl.clearColor(r, g, b, a); + gl.clear(mask); + } + initFramebuffer(framebuffer) { + const { gl } = this; + const fbo = new GLFramebuffer(gl.createFramebuffer()); + fbo.multisample = this.detectSamples(framebuffer.multisample); + framebuffer.glFramebuffers[this.CONTEXT_UID] = fbo; + this.managedFramebuffers.push(framebuffer); + framebuffer.disposeRunner.add(this); + return fbo; + } + resizeFramebuffer(framebuffer) { + const { gl } = this; + const fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + if (fbo.stencil) { + gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil); + if (fbo.msaaBuffer) { + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, framebuffer.width, framebuffer.height); + } else { + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + } + } + const colorTextures = framebuffer.colorTextures; + let count = colorTextures.length; + if (!gl.drawBuffers) { + count = Math.min(count, 1); + } + for (let i = 0; i < count; i++) { + const texture = colorTextures[i]; + const parentTexture = texture.parentTextureArray || texture; + this.renderer.texture.bind(parentTexture, 0); + if (i === 0 && fbo.msaaBuffer) { + gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.msaaBuffer); + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, parentTexture._glTextures[this.CONTEXT_UID].internalFormat, framebuffer.width, framebuffer.height); + } + } + if (framebuffer.depthTexture && this.writeDepthTexture) { + this.renderer.texture.bind(framebuffer.depthTexture, 0); + } + } + updateFramebuffer(framebuffer, mipLevel) { + const { gl } = this; + const fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + const colorTextures = framebuffer.colorTextures; + let count = colorTextures.length; + if (!gl.drawBuffers) { + count = Math.min(count, 1); + } + if (fbo.multisample > 1 && this.canMultisampleFramebuffer(framebuffer)) { + fbo.msaaBuffer = fbo.msaaBuffer || gl.createRenderbuffer(); + } else if (fbo.msaaBuffer) { + gl.deleteRenderbuffer(fbo.msaaBuffer); + fbo.msaaBuffer = null; + if (fbo.blitFramebuffer) { + fbo.blitFramebuffer.dispose(); + fbo.blitFramebuffer = null; + } + } + const activeTextures = []; + for (let i = 0; i < count; i++) { + const texture = colorTextures[i]; + const parentTexture = texture.parentTextureArray || texture; + this.renderer.texture.bind(parentTexture, 0); + if (i === 0 && fbo.msaaBuffer) { + gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.msaaBuffer); + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, parentTexture._glTextures[this.CONTEXT_UID].internalFormat, framebuffer.width, framebuffer.height); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, fbo.msaaBuffer); + } else { + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, texture.target, parentTexture._glTextures[this.CONTEXT_UID].texture, mipLevel); + activeTextures.push(gl.COLOR_ATTACHMENT0 + i); + } + } + if (activeTextures.length > 1) { + gl.drawBuffers(activeTextures); + } + if (framebuffer.depthTexture) { + const writeDepthTexture = this.writeDepthTexture; + if (writeDepthTexture) { + const depthTexture = framebuffer.depthTexture; + this.renderer.texture.bind(depthTexture, 0); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._glTextures[this.CONTEXT_UID].texture, mipLevel); + } + } + if ((framebuffer.stencil || framebuffer.depth) && !(framebuffer.depthTexture && this.writeDepthTexture)) { + fbo.stencil = fbo.stencil || gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil); + if (fbo.msaaBuffer) { + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, framebuffer.width, framebuffer.height); + } else { + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + } + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); + } else if (fbo.stencil) { + gl.deleteRenderbuffer(fbo.stencil); + fbo.stencil = null; + } + } + canMultisampleFramebuffer(framebuffer) { + return this.renderer.context.webGLVersion !== 1 && framebuffer.colorTextures.length <= 1 && !framebuffer.depthTexture; + } + detectSamples(samples) { + const { msaaSamples } = this; + let res = MSAA_QUALITY.NONE; + if (samples <= 1 || msaaSamples === null) { + return res; + } + for (let i = 0; i < msaaSamples.length; i++) { + if (msaaSamples[i] <= samples) { + res = msaaSamples[i]; + break; + } + } + if (res === 1) { + res = MSAA_QUALITY.NONE; + } + return res; + } + blit(framebuffer, sourcePixels, destPixels) { + const { current, renderer, gl, CONTEXT_UID } = this; + if (renderer.context.webGLVersion !== 2) { + return; + } + if (!current) { + return; + } + const fbo = current.glFramebuffers[CONTEXT_UID]; + if (!fbo) { + return; + } + if (!framebuffer) { + if (!fbo.msaaBuffer) { + return; + } + const colorTexture = current.colorTextures[0]; + if (!colorTexture) { + return; + } + if (!fbo.blitFramebuffer) { + fbo.blitFramebuffer = new Framebuffer(current.width, current.height); + fbo.blitFramebuffer.addColorTexture(0, colorTexture); + } + framebuffer = fbo.blitFramebuffer; + if (framebuffer.colorTextures[0] !== colorTexture) { + framebuffer.colorTextures[0] = colorTexture; + framebuffer.dirtyId++; + framebuffer.dirtyFormat++; + } + if (framebuffer.width !== current.width || framebuffer.height !== current.height) { + framebuffer.width = current.width; + framebuffer.height = current.height; + framebuffer.dirtyId++; + framebuffer.dirtySize++; + } + } + if (!sourcePixels) { + sourcePixels = tempRectangle; + sourcePixels.width = current.width; + sourcePixels.height = current.height; + } + if (!destPixels) { + destPixels = sourcePixels; + } + const sameSize = sourcePixels.width === destPixels.width && sourcePixels.height === destPixels.height; + this.bind(framebuffer); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fbo.framebuffer); + gl.blitFramebuffer(sourcePixels.left, sourcePixels.top, sourcePixels.right, sourcePixels.bottom, destPixels.left, destPixels.top, destPixels.right, destPixels.bottom, gl.COLOR_BUFFER_BIT, sameSize ? gl.NEAREST : gl.LINEAR); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, framebuffer.glFramebuffers[this.CONTEXT_UID].framebuffer); + } + disposeFramebuffer(framebuffer, contextLost) { + const fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + const gl = this.gl; + if (!fbo) { + return; + } + delete framebuffer.glFramebuffers[this.CONTEXT_UID]; + const index = this.managedFramebuffers.indexOf(framebuffer); + if (index >= 0) { + this.managedFramebuffers.splice(index, 1); + } + framebuffer.disposeRunner.remove(this); + if (!contextLost) { + gl.deleteFramebuffer(fbo.framebuffer); + if (fbo.msaaBuffer) { + gl.deleteRenderbuffer(fbo.msaaBuffer); + } + if (fbo.stencil) { + gl.deleteRenderbuffer(fbo.stencil); + } + } + if (fbo.blitFramebuffer) { + this.disposeFramebuffer(fbo.blitFramebuffer, contextLost); + } + } + disposeAll(contextLost) { + const list = this.managedFramebuffers; + this.managedFramebuffers = []; + for (let i = 0; i < list.length; i++) { + this.disposeFramebuffer(list[i], contextLost); + } + } + forceStencil() { + const framebuffer = this.current; + if (!framebuffer) { + return; + } + const fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + if (!fbo || fbo.stencil) { + return; + } + framebuffer.stencil = true; + const w = framebuffer.width; + const h = framebuffer.height; + const gl = this.gl; + const stencil = gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, stencil); + if (fbo.msaaBuffer) { + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, w, h); + } else { + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, w, h); + } + fbo.stencil = stencil; + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, stencil); + } + reset() { + this.current = this.unknownFramebuffer; + this.viewport = new Rectangle(); + } + destroy() { + this.renderer = null; + } + } + FramebufferSystem.extension = { + type: ExtensionType.RendererSystem, + name: "framebuffer" + }; + extensions$1.add(FramebufferSystem); + + const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; + class GeometrySystem { + constructor(renderer) { + this.renderer = renderer; + this._activeGeometry = null; + this._activeVao = null; + this.hasVao = true; + this.hasInstance = true; + this.canUseUInt32ElementIndex = false; + this.managedGeometries = {}; + } + contextChange() { + this.disposeAll(true); + const gl = this.gl = this.renderer.gl; + const context = this.renderer.context; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + if (context.webGLVersion !== 2) { + let nativeVaoExtension = this.renderer.context.extensions.vertexArrayObject; + if (settings.PREFER_ENV === ENV.WEBGL_LEGACY) { + nativeVaoExtension = null; + } + if (nativeVaoExtension) { + gl.createVertexArray = () => nativeVaoExtension.createVertexArrayOES(); + gl.bindVertexArray = (vao) => nativeVaoExtension.bindVertexArrayOES(vao); + gl.deleteVertexArray = (vao) => nativeVaoExtension.deleteVertexArrayOES(vao); + } else { + this.hasVao = false; + gl.createVertexArray = () => null; + gl.bindVertexArray = () => null; + gl.deleteVertexArray = () => null; + } + } + if (context.webGLVersion !== 2) { + const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + if (instanceExt) { + gl.vertexAttribDivisor = (a, b) => instanceExt.vertexAttribDivisorANGLE(a, b); + gl.drawElementsInstanced = (a, b, c, d, e) => instanceExt.drawElementsInstancedANGLE(a, b, c, d, e); + gl.drawArraysInstanced = (a, b, c, d) => instanceExt.drawArraysInstancedANGLE(a, b, c, d); + } else { + this.hasInstance = false; + } + } + this.canUseUInt32ElementIndex = context.webGLVersion === 2 || !!context.extensions.uint32ElementIndex; + } + bind(geometry, shader) { + shader = shader || this.renderer.shader.shader; + const { gl } = this; + let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; + let incRefCount = false; + if (!vaos) { + this.managedGeometries[geometry.id] = geometry; + geometry.disposeRunner.add(this); + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; + incRefCount = true; + } + const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader, incRefCount); + this._activeGeometry = geometry; + if (this._activeVao !== vao) { + this._activeVao = vao; + if (this.hasVao) { + gl.bindVertexArray(vao); + } else { + this.activateVao(geometry, shader.program); + } + } + this.updateBuffers(); + } + reset() { + this.unbind(); + } + updateBuffers() { + const geometry = this._activeGeometry; + const bufferSystem = this.renderer.buffer; + for (let i = 0; i < geometry.buffers.length; i++) { + const buffer = geometry.buffers[i]; + bufferSystem.update(buffer); + } + } + checkCompatibility(geometry, program) { + const geometryAttributes = geometry.attributes; + const shaderAttributes = program.attributeData; + for (const j in shaderAttributes) { + if (!geometryAttributes[j]) { + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); + } + } + } + getSignature(geometry, program) { + const attribs = geometry.attributes; + const shaderAttributes = program.attributeData; + const strings = ["g", geometry.id]; + for (const i in attribs) { + if (shaderAttributes[i]) { + strings.push(i, shaderAttributes[i].location); + } + } + return strings.join("-"); + } + initGeometryVao(geometry, shader, incRefCount = true) { + const gl = this.gl; + const CONTEXT_UID = this.CONTEXT_UID; + const bufferSystem = this.renderer.buffer; + const program = shader.program; + if (!program.glPrograms[CONTEXT_UID]) { + this.renderer.shader.generateProgram(shader); + } + this.checkCompatibility(geometry, program); + const signature = this.getSignature(geometry, program); + const vaoObjectHash = geometry.glVertexArrayObjects[this.CONTEXT_UID]; + let vao = vaoObjectHash[signature]; + if (vao) { + vaoObjectHash[program.id] = vao; + return vao; + } + const buffers = geometry.buffers; + const attributes = geometry.attributes; + const tempStride = {}; + const tempStart = {}; + for (const j in buffers) { + tempStride[j] = 0; + tempStart[j] = 0; + } + for (const j in attributes) { + if (!attributes[j].size && program.attributeData[j]) { + attributes[j].size = program.attributeData[j].size; + } else if (!attributes[j].size) { + console.warn(`PIXI Geometry attribute '${j}' size cannot be determined (likely the bound shader does not have the attribute)`); + } + tempStride[attributes[j].buffer] += attributes[j].size * byteSizeMap[attributes[j].type]; + } + for (const j in attributes) { + const attribute = attributes[j]; + const attribSize = attribute.size; + if (attribute.stride === void 0) { + if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) { + attribute.stride = 0; + } else { + attribute.stride = tempStride[attribute.buffer]; + } + } + if (attribute.start === void 0) { + attribute.start = tempStart[attribute.buffer]; + tempStart[attribute.buffer] += attribSize * byteSizeMap[attribute.type]; + } + } + vao = gl.createVertexArray(); + gl.bindVertexArray(vao); + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + bufferSystem.bind(buffer); + if (incRefCount) { + buffer._glBuffers[CONTEXT_UID].refCount++; + } + } + this.activateVao(geometry, program); + vaoObjectHash[program.id] = vao; + vaoObjectHash[signature] = vao; + gl.bindVertexArray(null); + bufferSystem.unbind(BUFFER_TYPE.ARRAY_BUFFER); + return vao; + } + disposeGeometry(geometry, contextLost) { + if (!this.managedGeometries[geometry.id]) { + return; + } + delete this.managedGeometries[geometry.id]; + const vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; + const gl = this.gl; + const buffers = geometry.buffers; + const bufferSystem = this.renderer?.buffer; + geometry.disposeRunner.remove(this); + if (!vaos) { + return; + } + if (bufferSystem) { + for (let i = 0; i < buffers.length; i++) { + const buf = buffers[i]._glBuffers[this.CONTEXT_UID]; + if (buf) { + buf.refCount--; + if (buf.refCount === 0 && !contextLost) { + bufferSystem.dispose(buffers[i], contextLost); + } + } + } + } + if (!contextLost) { + for (const vaoId in vaos) { + if (vaoId[0] === "g") { + const vao = vaos[vaoId]; + if (this._activeVao === vao) { + this.unbind(); + } + gl.deleteVertexArray(vao); + } + } + } + delete geometry.glVertexArrayObjects[this.CONTEXT_UID]; + } + disposeAll(contextLost) { + const all = Object.keys(this.managedGeometries); + for (let i = 0; i < all.length; i++) { + this.disposeGeometry(this.managedGeometries[all[i]], contextLost); + } + } + activateVao(geometry, program) { + const gl = this.gl; + const CONTEXT_UID = this.CONTEXT_UID; + const bufferSystem = this.renderer.buffer; + const buffers = geometry.buffers; + const attributes = geometry.attributes; + if (geometry.indexBuffer) { + bufferSystem.bind(geometry.indexBuffer); + } + let lastBuffer = null; + for (const j in attributes) { + const attribute = attributes[j]; + const buffer = buffers[attribute.buffer]; + const glBuffer = buffer._glBuffers[CONTEXT_UID]; + if (program.attributeData[j]) { + if (lastBuffer !== glBuffer) { + bufferSystem.bind(buffer); + lastBuffer = glBuffer; + } + const location = program.attributeData[j].location; + gl.enableVertexAttribArray(location); + gl.vertexAttribPointer(location, attribute.size, attribute.type || gl.FLOAT, attribute.normalized, attribute.stride, attribute.start); + if (attribute.instance) { + if (this.hasInstance) { + gl.vertexAttribDivisor(location, attribute.divisor); + } else { + throw new Error("geometry error, GPU Instancing is not supported on this device"); + } + } + } + } + } + draw(type, size, start, instanceCount) { + const { gl } = this; + const geometry = this._activeGeometry; + if (geometry.indexBuffer) { + const byteSize = geometry.indexBuffer.data.BYTES_PER_ELEMENT; + const glType = byteSize === 2 ? gl.UNSIGNED_SHORT : gl.UNSIGNED_INT; + if (byteSize === 2 || byteSize === 4 && this.canUseUInt32ElementIndex) { + if (geometry.instanced) { + gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize, instanceCount || 1); + } else { + gl.drawElements(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize); + } + } else { + console.warn("unsupported index buffer type: uint32"); + } + } else if (geometry.instanced) { + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { + gl.drawArrays(type, start, size || geometry.getSize()); + } + return this; + } + unbind() { + this.gl.bindVertexArray(null); + this._activeVao = null; + this._activeGeometry = null; + } + destroy() { + this.renderer = null; + } + } + GeometrySystem.extension = { + type: ExtensionType.RendererSystem, + name: "geometry" + }; + extensions$1.add(GeometrySystem); + + const tempMat$1 = new Matrix(); + class TextureMatrix { + constructor(texture, clampMargin) { + this._texture = texture; + this.mapCoord = new Matrix(); + this.uClampFrame = new Float32Array(4); + this.uClampOffset = new Float32Array(2); + this._textureID = -1; + this._updateID = 0; + this.clampOffset = 0; + this.clampMargin = typeof clampMargin === "undefined" ? 0.5 : clampMargin; + this.isSimple = false; + } + get texture() { + return this._texture; + } + set texture(value) { + this._texture = value; + this._textureID = -1; + } + multiplyUvs(uvs, out) { + if (out === void 0) { + out = uvs; + } + const mat = this.mapCoord; + for (let i = 0; i < uvs.length; i += 2) { + const x = uvs[i]; + const y = uvs[i + 1]; + out[i] = x * mat.a + y * mat.c + mat.tx; + out[i + 1] = x * mat.b + y * mat.d + mat.ty; + } + return out; + } + update(forceUpdate) { + const tex = this._texture; + if (!tex || !tex.valid) { + return false; + } + if (!forceUpdate && this._textureID === tex._updateID) { + return false; + } + this._textureID = tex._updateID; + this._updateID++; + const uvs = tex._uvs; + this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); + const orig = tex.orig; + const trim = tex.trim; + if (trim) { + tempMat$1.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); + this.mapCoord.append(tempMat$1); + } + const texBase = tex.baseTexture; + const frame = this.uClampFrame; + const margin = this.clampMargin / texBase.resolution; + const offset = this.clampOffset; + frame[0] = (tex._frame.x + margin + offset) / texBase.width; + frame[1] = (tex._frame.y + margin + offset) / texBase.height; + frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; + frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; + this.uClampOffset[0] = offset / texBase.realWidth; + this.uClampOffset[1] = offset / texBase.realHeight; + this.isSimple = tex._frame.width === texBase.width && tex._frame.height === texBase.height && tex.rotate === 0; + return true; + } + } + + var fragment$7 = "varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform float npmAlpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);\n\n original *= (alphaMul * masky.r * alpha * clip);\n\n gl_FragColor = original;\n}\n"; + + var vertex$4 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n"; + + class SpriteMaskFilter extends Filter { + constructor(vertexSrc, fragmentSrc, uniforms) { + let sprite = null; + if (typeof vertexSrc !== "string" && fragmentSrc === void 0 && uniforms === void 0) { + sprite = vertexSrc; + vertexSrc = void 0; + fragmentSrc = void 0; + uniforms = void 0; + } + super(vertexSrc || vertex$4, fragmentSrc || fragment$7, uniforms); + this.maskSprite = sprite; + this.maskMatrix = new Matrix(); + } + get maskSprite() { + return this._maskSprite; + } + set maskSprite(value) { + this._maskSprite = value; + if (this._maskSprite) { + this._maskSprite.renderable = false; + } + } + apply(filterManager, input, output, clearMode) { + const maskSprite = this._maskSprite; + const tex = maskSprite._texture; + if (!tex.valid) { + return; + } + if (!tex.uvMatrix) { + tex.uvMatrix = new TextureMatrix(tex, 0); + } + tex.uvMatrix.update(); + this.uniforms.npmAlpha = tex.baseTexture.alphaMode ? 0 : 1; + this.uniforms.mask = tex; + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite).prepend(tex.uvMatrix.mapCoord); + this.uniforms.alpha = maskSprite.worldAlpha; + this.uniforms.maskClamp = tex.uvMatrix.uClampFrame; + filterManager.applyFilter(this, input, output, clearMode); + } + } + + class MaskData { + constructor(maskObject = null) { + this.type = MASK_TYPES.NONE; + this.autoDetect = true; + this.maskObject = maskObject || null; + this.pooled = false; + this.isMaskData = true; + this.resolution = null; + this.multisample = Filter.defaultMultisample; + this.enabled = true; + this.colorMask = 15; + this._filters = null; + this._stencilCounter = 0; + this._scissorCounter = 0; + this._scissorRect = null; + this._scissorRectLocal = null; + this._colorMask = 15; + this._target = null; + } + get filter() { + return this._filters ? this._filters[0] : null; + } + set filter(value) { + if (value) { + if (this._filters) { + this._filters[0] = value; + } else { + this._filters = [value]; + } + } else { + this._filters = null; + } + } + reset() { + if (this.pooled) { + this.maskObject = null; + this.type = MASK_TYPES.NONE; + this.autoDetect = true; + } + this._target = null; + this._scissorRectLocal = null; + } + copyCountersOrReset(maskAbove) { + if (maskAbove) { + this._stencilCounter = maskAbove._stencilCounter; + this._scissorCounter = maskAbove._scissorCounter; + this._scissorRect = maskAbove._scissorRect; + } else { + this._stencilCounter = 0; + this._scissorCounter = 0; + this._scissorRect = null; + } + } + } + + class MaskSystem { + constructor(renderer) { + this.renderer = renderer; + this.enableScissor = true; + this.alphaMaskPool = []; + this.maskDataPool = []; + this.maskStack = []; + this.alphaMaskIndex = 0; + } + setMaskStack(maskStack) { + this.maskStack = maskStack; + this.renderer.scissor.setMaskStack(maskStack); + this.renderer.stencil.setMaskStack(maskStack); + } + push(target, maskDataOrTarget) { + let maskData = maskDataOrTarget; + if (!maskData.isMaskData) { + const d = this.maskDataPool.pop() || new MaskData(); + d.pooled = true; + d.maskObject = maskDataOrTarget; + maskData = d; + } + const maskAbove = this.maskStack.length !== 0 ? this.maskStack[this.maskStack.length - 1] : null; + maskData.copyCountersOrReset(maskAbove); + maskData._colorMask = maskAbove ? maskAbove._colorMask : 15; + if (maskData.autoDetect) { + this.detect(maskData); + } + maskData._target = target; + if (maskData.type !== MASK_TYPES.SPRITE) { + this.maskStack.push(maskData); + } + if (maskData.enabled) { + switch (maskData.type) { + case MASK_TYPES.SCISSOR: + this.renderer.scissor.push(maskData); + break; + case MASK_TYPES.STENCIL: + this.renderer.stencil.push(maskData); + break; + case MASK_TYPES.SPRITE: + maskData.copyCountersOrReset(null); + this.pushSpriteMask(maskData); + break; + case MASK_TYPES.COLOR: + this.pushColorMask(maskData); + break; + default: + break; + } + } + if (maskData.type === MASK_TYPES.SPRITE) { + this.maskStack.push(maskData); + } + } + pop(target) { + const maskData = this.maskStack.pop(); + if (!maskData || maskData._target !== target) { + return; + } + if (maskData.enabled) { + switch (maskData.type) { + case MASK_TYPES.SCISSOR: + this.renderer.scissor.pop(maskData); + break; + case MASK_TYPES.STENCIL: + this.renderer.stencil.pop(maskData.maskObject); + break; + case MASK_TYPES.SPRITE: + this.popSpriteMask(maskData); + break; + case MASK_TYPES.COLOR: + this.popColorMask(maskData); + break; + default: + break; + } + } + maskData.reset(); + if (maskData.pooled) { + this.maskDataPool.push(maskData); + } + if (this.maskStack.length !== 0) { + const maskCurrent = this.maskStack[this.maskStack.length - 1]; + if (maskCurrent.type === MASK_TYPES.SPRITE && maskCurrent._filters) { + maskCurrent._filters[0].maskSprite = maskCurrent.maskObject; + } + } + } + detect(maskData) { + const maskObject = maskData.maskObject; + if (!maskObject) { + maskData.type = MASK_TYPES.COLOR; + } else if (maskObject.isSprite) { + maskData.type = MASK_TYPES.SPRITE; + } else if (this.enableScissor && this.renderer.scissor.testScissor(maskData)) { + maskData.type = MASK_TYPES.SCISSOR; + } else { + maskData.type = MASK_TYPES.STENCIL; + } + } + pushSpriteMask(maskData) { + const { maskObject } = maskData; + const target = maskData._target; + let alphaMaskFilter = maskData._filters; + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new SpriteMaskFilter()]; + } + } + const renderer = this.renderer; + const renderTextureSystem = renderer.renderTexture; + let resolution; + let multisample; + if (renderTextureSystem.current) { + const renderTexture = renderTextureSystem.current; + resolution = maskData.resolution || renderTexture.resolution; + multisample = maskData.multisample ?? renderTexture.multisample; + } else { + resolution = maskData.resolution || renderer.resolution; + multisample = maskData.multisample ?? renderer.multisample; + } + alphaMaskFilter[0].resolution = resolution; + alphaMaskFilter[0].multisample = multisample; + alphaMaskFilter[0].maskSprite = maskObject; + const stashFilterArea = target.filterArea; + target.filterArea = maskObject.getBounds(true); + renderer.filter.push(target, alphaMaskFilter); + target.filterArea = stashFilterArea; + if (!maskData._filters) { + this.alphaMaskIndex++; + } + } + popSpriteMask(maskData) { + this.renderer.filter.pop(); + if (maskData._filters) { + maskData._filters[0].maskSprite = null; + } else { + this.alphaMaskIndex--; + this.alphaMaskPool[this.alphaMaskIndex][0].maskSprite = null; + } + } + pushColorMask(maskData) { + const currColorMask = maskData._colorMask; + const nextColorMask = maskData._colorMask = currColorMask & maskData.colorMask; + if (nextColorMask !== currColorMask) { + this.renderer.gl.colorMask((nextColorMask & 1) !== 0, (nextColorMask & 2) !== 0, (nextColorMask & 4) !== 0, (nextColorMask & 8) !== 0); + } + } + popColorMask(maskData) { + const currColorMask = maskData._colorMask; + const nextColorMask = this.maskStack.length > 0 ? this.maskStack[this.maskStack.length - 1]._colorMask : 15; + if (nextColorMask !== currColorMask) { + this.renderer.gl.colorMask((nextColorMask & 1) !== 0, (nextColorMask & 2) !== 0, (nextColorMask & 4) !== 0, (nextColorMask & 8) !== 0); + } + } + destroy() { + this.renderer = null; + } + } + MaskSystem.extension = { + type: ExtensionType.RendererSystem, + name: "mask" + }; + extensions$1.add(MaskSystem); + + class AbstractMaskSystem { + constructor(renderer) { + this.renderer = renderer; + this.maskStack = []; + this.glConst = 0; + } + getStackLength() { + return this.maskStack.length; + } + setMaskStack(maskStack) { + const { gl } = this.renderer; + const curStackLen = this.getStackLength(); + this.maskStack = maskStack; + const newStackLen = this.getStackLength(); + if (newStackLen !== curStackLen) { + if (newStackLen === 0) { + gl.disable(this.glConst); + } else { + gl.enable(this.glConst); + this._useCurrent(); + } + } + } + _useCurrent() { + } + destroy() { + this.renderer = null; + this.maskStack = null; + } + } + + const tempMatrix$3 = new Matrix(); + const rectPool = []; + const _ScissorSystem = class extends AbstractMaskSystem { + constructor(renderer) { + super(renderer); + this.glConst = settings.ADAPTER.getWebGLRenderingContext().SCISSOR_TEST; + } + getStackLength() { + const maskData = this.maskStack[this.maskStack.length - 1]; + if (maskData) { + return maskData._scissorCounter; + } + return 0; + } + calcScissorRect(maskData) { + if (maskData._scissorRectLocal) { + return; + } + const prevData = maskData._scissorRect; + const { maskObject } = maskData; + const { renderer } = this; + const renderTextureSystem = renderer.renderTexture; + const rect = maskObject.getBounds(true, rectPool.pop() ?? new Rectangle()); + this.roundFrameToPixels(rect, renderTextureSystem.current ? renderTextureSystem.current.resolution : renderer.resolution, renderTextureSystem.sourceFrame, renderTextureSystem.destinationFrame, renderer.projection.transform); + if (prevData) { + rect.fit(prevData); + } + maskData._scissorRectLocal = rect; + } + static isMatrixRotated(matrix) { + if (!matrix) { + return false; + } + const { a, b, c, d } = matrix; + return (Math.abs(b) > 1e-4 || Math.abs(c) > 1e-4) && (Math.abs(a) > 1e-4 || Math.abs(d) > 1e-4); + } + testScissor(maskData) { + const { maskObject } = maskData; + if (!maskObject.isFastRect || !maskObject.isFastRect()) { + return false; + } + if (_ScissorSystem.isMatrixRotated(maskObject.worldTransform)) { + return false; + } + if (_ScissorSystem.isMatrixRotated(this.renderer.projection.transform)) { + return false; + } + this.calcScissorRect(maskData); + const rect = maskData._scissorRectLocal; + return rect.width > 0 && rect.height > 0; + } + roundFrameToPixels(frame, resolution, bindingSourceFrame, bindingDestinationFrame, transform) { + if (_ScissorSystem.isMatrixRotated(transform)) { + return; + } + transform = transform ? tempMatrix$3.copyFrom(transform) : tempMatrix$3.identity(); + transform.translate(-bindingSourceFrame.x, -bindingSourceFrame.y).scale(bindingDestinationFrame.width / bindingSourceFrame.width, bindingDestinationFrame.height / bindingSourceFrame.height).translate(bindingDestinationFrame.x, bindingDestinationFrame.y); + this.renderer.filter.transformAABB(transform, frame); + frame.fit(bindingDestinationFrame); + frame.x = Math.round(frame.x * resolution); + frame.y = Math.round(frame.y * resolution); + frame.width = Math.round(frame.width * resolution); + frame.height = Math.round(frame.height * resolution); + } + push(maskData) { + if (!maskData._scissorRectLocal) { + this.calcScissorRect(maskData); + } + const { gl } = this.renderer; + if (!maskData._scissorRect) { + gl.enable(gl.SCISSOR_TEST); + } + maskData._scissorCounter++; + maskData._scissorRect = maskData._scissorRectLocal; + this._useCurrent(); + } + pop(maskData) { + const { gl } = this.renderer; + if (maskData) { + rectPool.push(maskData._scissorRectLocal); + } + if (this.getStackLength() > 0) { + this._useCurrent(); + } else { + gl.disable(gl.SCISSOR_TEST); + } + } + _useCurrent() { + const rect = this.maskStack[this.maskStack.length - 1]._scissorRect; + let y; + if (this.renderer.renderTexture.current) { + y = rect.y; + } else { + y = this.renderer.height - rect.height - rect.y; + } + this.renderer.gl.scissor(rect.x, y, rect.width, rect.height); + } + }; + let ScissorSystem = _ScissorSystem; + ScissorSystem.extension = { + type: ExtensionType.RendererSystem, + name: "scissor" + }; + extensions$1.add(ScissorSystem); + + class StencilSystem extends AbstractMaskSystem { + constructor(renderer) { + super(renderer); + this.glConst = settings.ADAPTER.getWebGLRenderingContext().STENCIL_TEST; + } + getStackLength() { + const maskData = this.maskStack[this.maskStack.length - 1]; + if (maskData) { + return maskData._stencilCounter; + } + return 0; + } + push(maskData) { + const maskObject = maskData.maskObject; + const { gl } = this.renderer; + const prevMaskCount = maskData._stencilCounter; + if (prevMaskCount === 0) { + this.renderer.framebuffer.forceStencil(); + gl.clearStencil(0); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.enable(gl.STENCIL_TEST); + } + maskData._stencilCounter++; + const colorMask = maskData._colorMask; + if (colorMask !== 0) { + maskData._colorMask = 0; + gl.colorMask(false, false, false, false); + } + gl.stencilFunc(gl.EQUAL, prevMaskCount, 4294967295); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + maskObject.renderable = true; + maskObject.render(this.renderer); + this.renderer.batch.flush(); + maskObject.renderable = false; + if (colorMask !== 0) { + maskData._colorMask = colorMask; + gl.colorMask((colorMask & 1) !== 0, (colorMask & 2) !== 0, (colorMask & 4) !== 0, (colorMask & 8) !== 0); + } + this._useCurrent(); + } + pop(maskObject) { + const gl = this.renderer.gl; + if (this.getStackLength() === 0) { + gl.disable(gl.STENCIL_TEST); + } else { + const maskData = this.maskStack.length !== 0 ? this.maskStack[this.maskStack.length - 1] : null; + const colorMask = maskData ? maskData._colorMask : 15; + if (colorMask !== 0) { + maskData._colorMask = 0; + gl.colorMask(false, false, false, false); + } + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + maskObject.renderable = true; + maskObject.render(this.renderer); + this.renderer.batch.flush(); + maskObject.renderable = false; + if (colorMask !== 0) { + maskData._colorMask = colorMask; + gl.colorMask((colorMask & 1) !== 0, (colorMask & 2) !== 0, (colorMask & 4) !== 0, (colorMask & 8) !== 0); + } + this._useCurrent(); + } + } + _useCurrent() { + const gl = this.renderer.gl; + gl.stencilFunc(gl.EQUAL, this.getStackLength(), 4294967295); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + } + } + StencilSystem.extension = { + type: ExtensionType.RendererSystem, + name: "stencil" + }; + extensions$1.add(StencilSystem); + + class PluginSystem { + constructor(renderer) { + this.renderer = renderer; + this.plugins = {}; + Object.defineProperties(this.plugins, { + extract: { + enumerable: false, + get() { + deprecation$1("7.0.0", "renderer.plugins.extract has moved to renderer.extract"); + return renderer.extract; + } + }, + prepare: { + enumerable: false, + get() { + deprecation$1("7.0.0", "renderer.plugins.prepare has moved to renderer.prepare"); + return renderer.prepare; + } + }, + interaction: { + enumerable: false, + get() { + deprecation$1("7.0.0", "renderer.plugins.interaction has been deprecated, use renderer.events"); + return renderer.events; + } + } + }); + } + init() { + const staticMap = this.rendererPlugins; + for (const o in staticMap) { + this.plugins[o] = new staticMap[o](this.renderer); + } + } + destroy() { + for (const o in this.plugins) { + this.plugins[o].destroy(); + this.plugins[o] = null; + } + } + } + PluginSystem.extension = { + type: [ + ExtensionType.RendererSystem, + ExtensionType.CanvasRendererSystem + ], + name: "_plugin" + }; + extensions$1.add(PluginSystem); + + class ProjectionSystem { + constructor(renderer) { + this.renderer = renderer; + this.destinationFrame = null; + this.sourceFrame = null; + this.defaultFrame = null; + this.projectionMatrix = new Matrix(); + this.transform = null; + } + update(destinationFrame, sourceFrame, resolution, root) { + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame; + this.calculateProjection(this.destinationFrame, this.sourceFrame, resolution, root); + if (this.transform) { + this.projectionMatrix.append(this.transform); + } + const renderer = this.renderer; + renderer.globalUniforms.uniforms.projectionMatrix = this.projectionMatrix; + renderer.globalUniforms.update(); + if (renderer.shader.shader) { + renderer.shader.syncUniformGroup(renderer.shader.shader.uniforms.globals); + } + } + calculateProjection(_destinationFrame, sourceFrame, _resolution, root) { + const pm = this.projectionMatrix; + const sign = !root ? 1 : -1; + pm.identity(); + pm.a = 1 / sourceFrame.width * 2; + pm.d = sign * (1 / sourceFrame.height * 2); + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = -sign - sourceFrame.y * pm.d; + } + setTransform(_matrix) { + } + destroy() { + this.renderer = null; + } + } + ProjectionSystem.extension = { + type: ExtensionType.RendererSystem, + name: "projection" + }; + extensions$1.add(ProjectionSystem); + + const tempTransform = new Transform(); + class GenerateTextureSystem { + constructor(renderer) { + this.renderer = renderer; + this._tempMatrix = new Matrix(); + } + generateTexture(displayObject, options) { + const { region: manualRegion, ...textureOptions } = options || {}; + const region = manualRegion || displayObject.getLocalBounds(null, true); + if (region.width === 0) + region.width = 1; + if (region.height === 0) + region.height = 1; + const renderTexture = RenderTexture.create({ + width: region.width, + height: region.height, + ...textureOptions + }); + this._tempMatrix.tx = -region.x; + this._tempMatrix.ty = -region.y; + const transform = displayObject.transform; + displayObject.transform = tempTransform; + this.renderer.render(displayObject, { + renderTexture, + transform: this._tempMatrix, + skipUpdateTransform: !!displayObject.parent, + blit: true + }); + displayObject.transform = transform; + return renderTexture; + } + destroy() { + } + } + GenerateTextureSystem.extension = { + type: [ + ExtensionType.RendererSystem, + ExtensionType.CanvasRendererSystem + ], + name: "textureGenerator" + }; + extensions$1.add(GenerateTextureSystem); + + const tempRect = new Rectangle(); + const tempRect2 = new Rectangle(); + class RenderTextureSystem { + constructor(renderer) { + this.renderer = renderer; + this.defaultMaskStack = []; + this.current = null; + this.sourceFrame = new Rectangle(); + this.destinationFrame = new Rectangle(); + this.viewportFrame = new Rectangle(); + } + contextChange() { + const attributes = this.renderer?.gl.getContextAttributes(); + this._rendererPremultipliedAlpha = !!(attributes && attributes.alpha && attributes.premultipliedAlpha); + } + bind(renderTexture = null, sourceFrame, destinationFrame) { + const renderer = this.renderer; + this.current = renderTexture; + let baseTexture; + let framebuffer; + let resolution; + if (renderTexture) { + baseTexture = renderTexture.baseTexture; + resolution = baseTexture.resolution; + if (!sourceFrame) { + tempRect.width = renderTexture.frame.width; + tempRect.height = renderTexture.frame.height; + sourceFrame = tempRect; + } + if (!destinationFrame) { + tempRect2.x = renderTexture.frame.x; + tempRect2.y = renderTexture.frame.y; + tempRect2.width = sourceFrame.width; + tempRect2.height = sourceFrame.height; + destinationFrame = tempRect2; + } + framebuffer = baseTexture.framebuffer; + } else { + resolution = renderer.resolution; + if (!sourceFrame) { + tempRect.width = renderer._view.screen.width; + tempRect.height = renderer._view.screen.height; + sourceFrame = tempRect; + } + if (!destinationFrame) { + destinationFrame = tempRect; + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; + } + } + const viewportFrame = this.viewportFrame; + viewportFrame.x = destinationFrame.x * resolution; + viewportFrame.y = destinationFrame.y * resolution; + viewportFrame.width = destinationFrame.width * resolution; + viewportFrame.height = destinationFrame.height * resolution; + if (!renderTexture) { + viewportFrame.y = renderer.view.height - (viewportFrame.y + viewportFrame.height); + } + viewportFrame.ceil(); + this.renderer.framebuffer.bind(framebuffer, viewportFrame); + this.renderer.projection.update(destinationFrame, sourceFrame, resolution, !framebuffer); + if (renderTexture) { + this.renderer.mask.setMaskStack(baseTexture.maskStack); + } else { + this.renderer.mask.setMaskStack(this.defaultMaskStack); + } + this.sourceFrame.copyFrom(sourceFrame); + this.destinationFrame.copyFrom(destinationFrame); + } + clear(clearColor, mask) { + const fallbackColor = this.current ? this.current.baseTexture.clear : this.renderer.background.backgroundColor; + const color = Color.shared.setValue(clearColor ? clearColor : fallbackColor); + if (this.current && this.current.baseTexture.alphaMode > 0 || !this.current && this._rendererPremultipliedAlpha) { + color.premultiply(color.alpha); + } + const destinationFrame = this.destinationFrame; + const baseFrame = this.current ? this.current.baseTexture : this.renderer._view.screen; + const clearMask = destinationFrame.width !== baseFrame.width || destinationFrame.height !== baseFrame.height; + if (clearMask) { + let { x, y, width, height } = this.viewportFrame; + x = Math.round(x); + y = Math.round(y); + width = Math.round(width); + height = Math.round(height); + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + this.renderer.gl.scissor(x, y, width, height); + } + this.renderer.framebuffer.clear(color.red, color.green, color.blue, color.alpha, mask); + if (clearMask) { + this.renderer.scissor.pop(); + } + } + resize() { + this.bind(null); + } + reset() { + this.bind(null); + } + destroy() { + this.renderer = null; + } + } + RenderTextureSystem.extension = { + type: ExtensionType.RendererSystem, + name: "renderTexture" + }; + extensions$1.add(RenderTextureSystem); + + class IGLUniformData { + } + class GLProgram { + constructor(program, uniformData) { + this.program = program; + this.uniformData = uniformData; + this.uniformGroups = {}; + this.uniformDirtyGroups = {}; + this.uniformBufferBindings = {}; + } + destroy() { + this.uniformData = null; + this.uniformGroups = null; + this.uniformDirtyGroups = null; + this.uniformBufferBindings = null; + this.program = null; + } + } + + function getAttributeData(program, gl) { + const attributes = {}; + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + for (let i = 0; i < totalAttributes; i++) { + const attribData = gl.getActiveAttrib(program, i); + if (attribData.name.startsWith("gl_")) { + continue; + } + const type = mapType(gl, attribData.type); + const data = { + type, + name: attribData.name, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name) + }; + attributes[attribData.name] = data; + } + return attributes; + } + + function getUniformData(program, gl) { + const uniforms = {}; + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + for (let i = 0; i < totalUniforms; i++) { + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]$/, ""); + const isArray = !!uniformData.name.match(/\[.*?\]$/); + const type = mapType(gl, uniformData.type); + uniforms[name] = { + name, + index: i, + type, + size: uniformData.size, + isArray, + value: defaultValue(type, uniformData.size) + }; + } + return uniforms; + } + + function generateProgram(gl, program) { + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, program.vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, program.fragmentSrc); + const webGLProgram = gl.createProgram(); + gl.attachShader(webGLProgram, glVertShader); + gl.attachShader(webGLProgram, glFragShader); + const transformFeedbackVaryings = program.extra?.transformFeedbackVaryings; + if (transformFeedbackVaryings) { + if (typeof gl.transformFeedbackVaryings !== "function") { + console.warn(`TransformFeedback is not supported but TransformFeedbackVaryings are given.`); + } else { + gl.transformFeedbackVaryings(webGLProgram, transformFeedbackVaryings.names, transformFeedbackVaryings.bufferMode === "separate" ? gl.SEPARATE_ATTRIBS : gl.INTERLEAVED_ATTRIBS); + } + } + gl.linkProgram(webGLProgram); + if (!gl.getProgramParameter(webGLProgram, gl.LINK_STATUS)) { + logProgramError(gl, webGLProgram, glVertShader, glFragShader); + } + program.attributeData = getAttributeData(webGLProgram, gl); + program.uniformData = getUniformData(webGLProgram, gl); + if (!/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m.test(program.vertexSrc)) { + const keys = Object.keys(program.attributeData); + keys.sort((a, b) => a > b ? 1 : -1); + for (let i = 0; i < keys.length; i++) { + program.attributeData[keys[i]].location = i; + gl.bindAttribLocation(webGLProgram, i, keys[i]); + } + gl.linkProgram(webGLProgram); + } + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + const uniformData = {}; + for (const i in program.uniformData) { + const data = program.uniformData[i]; + uniformData[i] = { + location: gl.getUniformLocation(webGLProgram, i), + value: defaultValue(data.type, data.size) + }; + } + const glProgram = new GLProgram(webGLProgram, uniformData); + return glProgram; + } + + function uboUpdate(_ud, _uv, _renderer, _syncData, buffer) { + _renderer.buffer.update(buffer); + } + const UBO_TO_SINGLE_SETTERS = { + float: ` + data[offset] = v; + `, + vec2: ` + data[offset] = v[0]; + data[offset+1] = v[1]; + `, + vec3: ` + data[offset] = v[0]; + data[offset+1] = v[1]; + data[offset+2] = v[2]; + + `, + vec4: ` + data[offset] = v[0]; + data[offset+1] = v[1]; + data[offset+2] = v[2]; + data[offset+3] = v[3]; + `, + mat2: ` + data[offset] = v[0]; + data[offset+1] = v[1]; + + data[offset+4] = v[2]; + data[offset+5] = v[3]; + `, + mat3: ` + data[offset] = v[0]; + data[offset+1] = v[1]; + data[offset+2] = v[2]; + + data[offset + 4] = v[3]; + data[offset + 5] = v[4]; + data[offset + 6] = v[5]; + + data[offset + 8] = v[6]; + data[offset + 9] = v[7]; + data[offset + 10] = v[8]; + `, + mat4: ` + for(var i = 0; i < 16; i++) + { + data[offset + i] = v[i]; + } + ` + }; + const GLSL_TO_STD40_SIZE = { + float: 4, + vec2: 8, + vec3: 12, + vec4: 16, + int: 4, + ivec2: 8, + ivec3: 12, + ivec4: 16, + uint: 4, + uvec2: 8, + uvec3: 12, + uvec4: 16, + bool: 4, + bvec2: 8, + bvec3: 12, + bvec4: 16, + mat2: 16 * 2, + mat3: 16 * 3, + mat4: 16 * 4 + }; + function createUBOElements(uniformData) { + const uboElements = uniformData.map((data) => ({ + data, + offset: 0, + dataLen: 0, + dirty: 0 + })); + let size = 0; + let chunkSize = 0; + let offset = 0; + for (let i = 0; i < uboElements.length; i++) { + const uboElement = uboElements[i]; + size = GLSL_TO_STD40_SIZE[uboElement.data.type]; + if (uboElement.data.size > 1) { + size = Math.max(size, 16) * uboElement.data.size; + } + uboElement.dataLen = size; + if (chunkSize % size !== 0 && chunkSize < 16) { + const lineUpValue = chunkSize % size % 16; + chunkSize += lineUpValue; + offset += lineUpValue; + } + if (chunkSize + size > 16) { + offset = Math.ceil(offset / 16) * 16; + uboElement.offset = offset; + offset += size; + chunkSize = size; + } else { + uboElement.offset = offset; + chunkSize += size; + offset += size; + } + } + offset = Math.ceil(offset / 16) * 16; + return { uboElements, size: offset }; + } + function getUBOData(uniforms, uniformData) { + const usedUniformDatas = []; + for (const i in uniforms) { + if (uniformData[i]) { + usedUniformDatas.push(uniformData[i]); + } + } + usedUniformDatas.sort((a, b) => a.index - b.index); + return usedUniformDatas; + } + function generateUniformBufferSync(group, uniformData) { + if (!group.autoManage) { + return { size: 0, syncFunc: uboUpdate }; + } + const usedUniformDatas = getUBOData(group.uniforms, uniformData); + const { uboElements, size } = createUBOElements(usedUniformDatas); + const funcFragments = [` + var v = null; + var v2 = null; + var cv = null; + var t = 0; + var gl = renderer.gl + var index = 0; + var data = buffer.data; + `]; + for (let i = 0; i < uboElements.length; i++) { + const uboElement = uboElements[i]; + const uniform = group.uniforms[uboElement.data.name]; + const name = uboElement.data.name; + let parsed = false; + for (let j = 0; j < uniformParsers.length; j++) { + const uniformParser = uniformParsers[j]; + if (uniformParser.codeUbo && uniformParser.test(uboElement.data, uniform)) { + funcFragments.push(`offset = ${uboElement.offset / 4};`, uniformParsers[j].codeUbo(uboElement.data.name, uniform)); + parsed = true; + break; + } + } + if (!parsed) { + if (uboElement.data.size > 1) { + const size2 = mapSize(uboElement.data.type); + const rowSize = Math.max(GLSL_TO_STD40_SIZE[uboElement.data.type] / 16, 1); + const elementSize = size2 / rowSize; + const remainder = (4 - elementSize % 4) % 4; + funcFragments.push(` + cv = ud.${name}.value; + v = uv.${name}; + offset = ${uboElement.offset / 4}; + + t = 0; + + for(var i=0; i < ${uboElement.data.size * rowSize}; i++) + { + for(var j = 0; j < ${elementSize}; j++) + { + data[offset++] = v[t++]; + } + offset += ${remainder}; + } + + `); + } else { + const template = UBO_TO_SINGLE_SETTERS[uboElement.data.type]; + funcFragments.push(` + cv = ud.${name}.value; + v = uv.${name}; + offset = ${uboElement.offset / 4}; + ${template}; + `); + } + } + } + funcFragments.push(` + renderer.buffer.update(buffer); + `); + return { + size, + syncFunc: new Function("ud", "uv", "renderer", "syncData", "buffer", funcFragments.join("\n")) + }; + } + + let UID = 0; + const defaultSyncData = { textureCount: 0, uboCount: 0 }; + class ShaderSystem { + constructor(renderer) { + this.destroyed = false; + this.renderer = renderer; + this.systemCheck(); + this.gl = null; + this.shader = null; + this.program = null; + this.cache = {}; + this._uboCache = {}; + this.id = UID++; + } + systemCheck() { + if (!unsafeEvalSupported()) { + throw new Error("Current environment does not allow unsafe-eval, please use @pixi/unsafe-eval module to enable support."); + } + } + contextChange(gl) { + this.gl = gl; + this.reset(); + } + bind(shader, dontSync) { + shader.disposeRunner.add(this); + shader.uniforms.globals = this.renderer.globalUniforms; + const program = shader.program; + const glProgram = program.glPrograms[this.renderer.CONTEXT_UID] || this.generateProgram(shader); + this.shader = shader; + if (this.program !== program) { + this.program = program; + this.gl.useProgram(glProgram.program); + } + if (!dontSync) { + defaultSyncData.textureCount = 0; + defaultSyncData.uboCount = 0; + this.syncUniformGroup(shader.uniformGroup, defaultSyncData); + } + return glProgram; + } + setUniforms(uniforms) { + const shader = this.shader.program; + const glProgram = shader.glPrograms[this.renderer.CONTEXT_UID]; + shader.syncUniforms(glProgram.uniformData, uniforms, this.renderer); + } + syncUniformGroup(group, syncData) { + const glProgram = this.getGlProgram(); + if (!group.static || group.dirtyId !== glProgram.uniformDirtyGroups[group.id]) { + glProgram.uniformDirtyGroups[group.id] = group.dirtyId; + this.syncUniforms(group, glProgram, syncData); + } + } + syncUniforms(group, glProgram, syncData) { + const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); + syncFunc(glProgram.uniformData, group.uniforms, this.renderer, syncData); + } + createSyncGroups(group) { + const id = this.getSignature(group, this.shader.program.uniformData, "u"); + if (!this.cache[id]) { + this.cache[id] = generateUniformsSync(group, this.shader.program.uniformData); + } + group.syncUniforms[this.shader.program.id] = this.cache[id]; + return group.syncUniforms[this.shader.program.id]; + } + syncUniformBufferGroup(group, name) { + const glProgram = this.getGlProgram(); + if (!group.static || group.dirtyId !== 0 || !glProgram.uniformGroups[group.id]) { + group.dirtyId = 0; + const syncFunc = glProgram.uniformGroups[group.id] || this.createSyncBufferGroup(group, glProgram, name); + group.buffer.update(); + syncFunc(glProgram.uniformData, group.uniforms, this.renderer, defaultSyncData, group.buffer); + } + this.renderer.buffer.bindBufferBase(group.buffer, glProgram.uniformBufferBindings[name]); + } + createSyncBufferGroup(group, glProgram, name) { + const { gl } = this.renderer; + this.renderer.buffer.bind(group.buffer); + const uniformBlockIndex = this.gl.getUniformBlockIndex(glProgram.program, name); + glProgram.uniformBufferBindings[name] = this.shader.uniformBindCount; + gl.uniformBlockBinding(glProgram.program, uniformBlockIndex, this.shader.uniformBindCount); + this.shader.uniformBindCount++; + const id = this.getSignature(group, this.shader.program.uniformData, "ubo"); + let uboData = this._uboCache[id]; + if (!uboData) { + uboData = this._uboCache[id] = generateUniformBufferSync(group, this.shader.program.uniformData); + } + if (group.autoManage) { + const data = new Float32Array(uboData.size / 4); + group.buffer.update(data); + } + glProgram.uniformGroups[group.id] = uboData.syncFunc; + return glProgram.uniformGroups[group.id]; + } + getSignature(group, uniformData, preFix) { + const uniforms = group.uniforms; + const strings = [`${preFix}-`]; + for (const i in uniforms) { + strings.push(i); + if (uniformData[i]) { + strings.push(uniformData[i].type); + } + } + return strings.join("-"); + } + getGlProgram() { + if (this.shader) { + return this.shader.program.glPrograms[this.renderer.CONTEXT_UID]; + } + return null; + } + generateProgram(shader) { + const gl = this.gl; + const program = shader.program; + const glProgram = generateProgram(gl, program); + program.glPrograms[this.renderer.CONTEXT_UID] = glProgram; + return glProgram; + } + reset() { + this.program = null; + this.shader = null; + } + disposeShader(shader) { + if (this.shader === shader) { + this.shader = null; + } + } + destroy() { + this.renderer = null; + this.destroyed = true; + } + } + ShaderSystem.extension = { + type: ExtensionType.RendererSystem, + name: "shader" + }; + extensions$1.add(ShaderSystem); + + class StartupSystem { + constructor(renderer) { + this.renderer = renderer; + } + run(options) { + const { renderer } = this; + renderer.runners.init.emit(renderer.options); + if (options.hello) { + console.log(`PixiJS ${"7.2.4"} - ${renderer.rendererLogId} - https://pixijs.com`); + } + renderer.resize(renderer.screen.width, renderer.screen.height); + } + destroy() { + } + } + StartupSystem.defaultOptions = { + hello: false + }; + StartupSystem.extension = { + type: [ + ExtensionType.RendererSystem, + ExtensionType.CanvasRendererSystem + ], + name: "startup" + }; + extensions$1.add(StartupSystem); + + function mapWebGLBlendModesToPixi(gl, array = []) { + array[BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.ADD] = [gl.ONE, gl.ONE]; + array[BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.NONE] = [0, 0]; + array[BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE]; + array[BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.SRC_IN] = [gl.DST_ALPHA, gl.ZERO]; + array[BLEND_MODES.SRC_OUT] = [gl.ONE_MINUS_DST_ALPHA, gl.ZERO]; + array[BLEND_MODES.SRC_ATOP] = [gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.DST_OVER] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE]; + array[BLEND_MODES.DST_IN] = [gl.ZERO, gl.SRC_ALPHA]; + array[BLEND_MODES.DST_OUT] = [gl.ZERO, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.DST_ATOP] = [gl.ONE_MINUS_DST_ALPHA, gl.SRC_ALPHA]; + array[BLEND_MODES.XOR] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA]; + array[BLEND_MODES.SUBTRACT] = [gl.ONE, gl.ONE, gl.ONE, gl.ONE, gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD]; + return array; + } + + const BLEND = 0; + const OFFSET = 1; + const CULLING = 2; + const DEPTH_TEST = 3; + const WINDING = 4; + const DEPTH_MASK = 5; + const _StateSystem = class { + constructor() { + this.gl = null; + this.stateId = 0; + this.polygonOffset = 0; + this.blendMode = BLEND_MODES.NONE; + this._blendEq = false; + this.map = []; + this.map[BLEND] = this.setBlend; + this.map[OFFSET] = this.setOffset; + this.map[CULLING] = this.setCullFace; + this.map[DEPTH_TEST] = this.setDepthTest; + this.map[WINDING] = this.setFrontFace; + this.map[DEPTH_MASK] = this.setDepthMask; + this.checks = []; + this.defaultState = new State(); + this.defaultState.blend = true; + } + contextChange(gl) { + this.gl = gl; + this.blendModes = mapWebGLBlendModesToPixi(gl); + this.set(this.defaultState); + this.reset(); + } + set(state) { + state = state || this.defaultState; + if (this.stateId !== state.data) { + let diff = this.stateId ^ state.data; + let i = 0; + while (diff) { + if (diff & 1) { + this.map[i].call(this, !!(state.data & 1 << i)); + } + diff = diff >> 1; + i++; + } + this.stateId = state.data; + } + for (let i = 0; i < this.checks.length; i++) { + this.checks[i](this, state); + } + } + forceState(state) { + state = state || this.defaultState; + for (let i = 0; i < this.map.length; i++) { + this.map[i].call(this, !!(state.data & 1 << i)); + } + for (let i = 0; i < this.checks.length; i++) { + this.checks[i](this, state); + } + this.stateId = state.data; + } + setBlend(value) { + this.updateCheck(_StateSystem.checkBlendMode, value); + this.gl[value ? "enable" : "disable"](this.gl.BLEND); + } + setOffset(value) { + this.updateCheck(_StateSystem.checkPolygonOffset, value); + this.gl[value ? "enable" : "disable"](this.gl.POLYGON_OFFSET_FILL); + } + setDepthTest(value) { + this.gl[value ? "enable" : "disable"](this.gl.DEPTH_TEST); + } + setDepthMask(value) { + this.gl.depthMask(value); + } + setCullFace(value) { + this.gl[value ? "enable" : "disable"](this.gl.CULL_FACE); + } + setFrontFace(value) { + this.gl.frontFace(this.gl[value ? "CW" : "CCW"]); + } + setBlendMode(value) { + if (value === this.blendMode) { + return; + } + this.blendMode = value; + const mode = this.blendModes[value]; + const gl = this.gl; + if (mode.length === 2) { + gl.blendFunc(mode[0], mode[1]); + } else { + gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]); + } + if (mode.length === 6) { + this._blendEq = true; + gl.blendEquationSeparate(mode[4], mode[5]); + } else if (this._blendEq) { + this._blendEq = false; + gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); + } + } + setPolygonOffset(value, scale) { + this.gl.polygonOffset(value, scale); + } + reset() { + this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); + this.forceState(this.defaultState); + this._blendEq = true; + this.blendMode = -1; + this.setBlendMode(0); + } + updateCheck(func, value) { + const index = this.checks.indexOf(func); + if (value && index === -1) { + this.checks.push(func); + } else if (!value && index !== -1) { + this.checks.splice(index, 1); + } + } + static checkBlendMode(system, state) { + system.setBlendMode(state.blendMode); + } + static checkPolygonOffset(system, state) { + system.setPolygonOffset(1, state.polygonOffset); + } + destroy() { + this.gl = null; + } + }; + let StateSystem = _StateSystem; + StateSystem.extension = { + type: ExtensionType.RendererSystem, + name: "state" + }; + extensions$1.add(StateSystem); + + class SystemManager extends eventemitter3 { + constructor() { + super(...arguments); + this.runners = {}; + this._systemsHash = {}; + } + setup(config) { + this.addRunners(...config.runners); + const priority = (config.priority ?? []).filter((key) => config.systems[key]); + const orderByPriority = [ + ...priority, + ...Object.keys(config.systems).filter((key) => !priority.includes(key)) + ]; + for (const i of orderByPriority) { + this.addSystem(config.systems[i], i); + } + } + addRunners(...runnerIds) { + runnerIds.forEach((runnerId) => { + this.runners[runnerId] = new Runner(runnerId); + }); + } + addSystem(ClassRef, name) { + const system = new ClassRef(this); + if (this[name]) { + throw new Error(`Whoops! The name "${name}" is already in use`); + } + this[name] = system; + this._systemsHash[name] = system; + for (const i in this.runners) { + this.runners[i].add(system); + } + return this; + } + emitWithCustomOptions(runner, options) { + const systemHashKeys = Object.keys(this._systemsHash); + runner.items.forEach((system) => { + const systemName = systemHashKeys.find((systemId) => this._systemsHash[systemId] === system); + system[runner.name](options[systemName]); + }); + } + destroy() { + Object.values(this.runners).forEach((runner) => { + runner.destroy(); + }); + this._systemsHash = {}; + } + } + + const _TextureGCSystem = class { + constructor(renderer) { + this.renderer = renderer; + this.count = 0; + this.checkCount = 0; + this.maxIdle = _TextureGCSystem.defaultMaxIdle; + this.checkCountMax = _TextureGCSystem.defaultCheckCountMax; + this.mode = _TextureGCSystem.defaultMode; + } + postrender() { + if (!this.renderer.objectRenderer.renderingToScreen) { + return; + } + this.count++; + if (this.mode === GC_MODES.MANUAL) { + return; + } + this.checkCount++; + if (this.checkCount > this.checkCountMax) { + this.checkCount = 0; + this.run(); + } + } + run() { + const tm = this.renderer.texture; + const managedTextures = tm.managedTextures; + let wasRemoved = false; + for (let i = 0; i < managedTextures.length; i++) { + const texture = managedTextures[i]; + if (!texture.framebuffer && this.count - texture.touched > this.maxIdle) { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + if (wasRemoved) { + let j = 0; + for (let i = 0; i < managedTextures.length; i++) { + if (managedTextures[i] !== null) { + managedTextures[j++] = managedTextures[i]; + } + } + managedTextures.length = j; + } + } + unload(displayObject) { + const tm = this.renderer.texture; + const texture = displayObject._texture; + if (texture && !texture.framebuffer) { + tm.destroyTexture(texture); + } + for (let i = displayObject.children.length - 1; i >= 0; i--) { + this.unload(displayObject.children[i]); + } + } + destroy() { + this.renderer = null; + } + }; + let TextureGCSystem = _TextureGCSystem; + TextureGCSystem.defaultMode = GC_MODES.AUTO; + TextureGCSystem.defaultMaxIdle = 60 * 60; + TextureGCSystem.defaultCheckCountMax = 60 * 10; + TextureGCSystem.extension = { + type: ExtensionType.RendererSystem, + name: "textureGC" + }; + extensions$1.add(TextureGCSystem); + + class GLTexture { + constructor(texture) { + this.texture = texture; + this.width = -1; + this.height = -1; + this.dirtyId = -1; + this.dirtyStyleId = -1; + this.mipmap = false; + this.wrapMode = 33071; + this.type = TYPES.UNSIGNED_BYTE; + this.internalFormat = FORMATS.RGBA; + this.samplerType = 0; + } + } + + function mapTypeAndFormatToInternalFormat(gl) { + let table; + if ("WebGL2RenderingContext" in globalThis && gl instanceof globalThis.WebGL2RenderingContext) { + table = { + [TYPES.UNSIGNED_BYTE]: { + [FORMATS.RGBA]: gl.RGBA8, + [FORMATS.RGB]: gl.RGB8, + [FORMATS.RG]: gl.RG8, + [FORMATS.RED]: gl.R8, + [FORMATS.RGBA_INTEGER]: gl.RGBA8UI, + [FORMATS.RGB_INTEGER]: gl.RGB8UI, + [FORMATS.RG_INTEGER]: gl.RG8UI, + [FORMATS.RED_INTEGER]: gl.R8UI, + [FORMATS.ALPHA]: gl.ALPHA, + [FORMATS.LUMINANCE]: gl.LUMINANCE, + [FORMATS.LUMINANCE_ALPHA]: gl.LUMINANCE_ALPHA + }, + [TYPES.BYTE]: { + [FORMATS.RGBA]: gl.RGBA8_SNORM, + [FORMATS.RGB]: gl.RGB8_SNORM, + [FORMATS.RG]: gl.RG8_SNORM, + [FORMATS.RED]: gl.R8_SNORM, + [FORMATS.RGBA_INTEGER]: gl.RGBA8I, + [FORMATS.RGB_INTEGER]: gl.RGB8I, + [FORMATS.RG_INTEGER]: gl.RG8I, + [FORMATS.RED_INTEGER]: gl.R8I + }, + [TYPES.UNSIGNED_SHORT]: { + [FORMATS.RGBA_INTEGER]: gl.RGBA16UI, + [FORMATS.RGB_INTEGER]: gl.RGB16UI, + [FORMATS.RG_INTEGER]: gl.RG16UI, + [FORMATS.RED_INTEGER]: gl.R16UI, + [FORMATS.DEPTH_COMPONENT]: gl.DEPTH_COMPONENT16 + }, + [TYPES.SHORT]: { + [FORMATS.RGBA_INTEGER]: gl.RGBA16I, + [FORMATS.RGB_INTEGER]: gl.RGB16I, + [FORMATS.RG_INTEGER]: gl.RG16I, + [FORMATS.RED_INTEGER]: gl.R16I + }, + [TYPES.UNSIGNED_INT]: { + [FORMATS.RGBA_INTEGER]: gl.RGBA32UI, + [FORMATS.RGB_INTEGER]: gl.RGB32UI, + [FORMATS.RG_INTEGER]: gl.RG32UI, + [FORMATS.RED_INTEGER]: gl.R32UI, + [FORMATS.DEPTH_COMPONENT]: gl.DEPTH_COMPONENT24 + }, + [TYPES.INT]: { + [FORMATS.RGBA_INTEGER]: gl.RGBA32I, + [FORMATS.RGB_INTEGER]: gl.RGB32I, + [FORMATS.RG_INTEGER]: gl.RG32I, + [FORMATS.RED_INTEGER]: gl.R32I + }, + [TYPES.FLOAT]: { + [FORMATS.RGBA]: gl.RGBA32F, + [FORMATS.RGB]: gl.RGB32F, + [FORMATS.RG]: gl.RG32F, + [FORMATS.RED]: gl.R32F, + [FORMATS.DEPTH_COMPONENT]: gl.DEPTH_COMPONENT32F + }, + [TYPES.HALF_FLOAT]: { + [FORMATS.RGBA]: gl.RGBA16F, + [FORMATS.RGB]: gl.RGB16F, + [FORMATS.RG]: gl.RG16F, + [FORMATS.RED]: gl.R16F + }, + [TYPES.UNSIGNED_SHORT_5_6_5]: { + [FORMATS.RGB]: gl.RGB565 + }, + [TYPES.UNSIGNED_SHORT_4_4_4_4]: { + [FORMATS.RGBA]: gl.RGBA4 + }, + [TYPES.UNSIGNED_SHORT_5_5_5_1]: { + [FORMATS.RGBA]: gl.RGB5_A1 + }, + [TYPES.UNSIGNED_INT_2_10_10_10_REV]: { + [FORMATS.RGBA]: gl.RGB10_A2, + [FORMATS.RGBA_INTEGER]: gl.RGB10_A2UI + }, + [TYPES.UNSIGNED_INT_10F_11F_11F_REV]: { + [FORMATS.RGB]: gl.R11F_G11F_B10F + }, + [TYPES.UNSIGNED_INT_5_9_9_9_REV]: { + [FORMATS.RGB]: gl.RGB9_E5 + }, + [TYPES.UNSIGNED_INT_24_8]: { + [FORMATS.DEPTH_STENCIL]: gl.DEPTH24_STENCIL8 + }, + [TYPES.FLOAT_32_UNSIGNED_INT_24_8_REV]: { + [FORMATS.DEPTH_STENCIL]: gl.DEPTH32F_STENCIL8 + } + }; + } else { + table = { + [TYPES.UNSIGNED_BYTE]: { + [FORMATS.RGBA]: gl.RGBA, + [FORMATS.RGB]: gl.RGB, + [FORMATS.ALPHA]: gl.ALPHA, + [FORMATS.LUMINANCE]: gl.LUMINANCE, + [FORMATS.LUMINANCE_ALPHA]: gl.LUMINANCE_ALPHA + }, + [TYPES.UNSIGNED_SHORT_5_6_5]: { + [FORMATS.RGB]: gl.RGB + }, + [TYPES.UNSIGNED_SHORT_4_4_4_4]: { + [FORMATS.RGBA]: gl.RGBA + }, + [TYPES.UNSIGNED_SHORT_5_5_5_1]: { + [FORMATS.RGBA]: gl.RGBA + } + }; + } + return table; + } + + class TextureSystem { + constructor(renderer) { + this.renderer = renderer; + this.boundTextures = []; + this.currentLocation = -1; + this.managedTextures = []; + this._unknownBoundTextures = false; + this.unknownTexture = new BaseTexture(); + this.hasIntegerTextures = false; + } + contextChange() { + const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.webGLVersion = this.renderer.context.webGLVersion; + this.internalFormats = mapTypeAndFormatToInternalFormat(gl); + const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.boundTextures.length = maxTextures; + for (let i = 0; i < maxTextures; i++) { + this.boundTextures[i] = null; + } + this.emptyTextures = {}; + const emptyTexture2D = new GLTexture(gl.createTexture()); + gl.bindTexture(gl.TEXTURE_2D, emptyTexture2D.texture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4)); + this.emptyTextures[gl.TEXTURE_2D] = emptyTexture2D; + this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(gl.createTexture()); + gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); + for (let i = 0; i < 6; i++) { + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + } + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + for (let i = 0; i < this.boundTextures.length; i++) { + this.bind(null, i); + } + } + bind(texture, location = 0) { + const { gl } = this; + texture = texture?.castToBaseTexture(); + if (texture?.valid && !texture.parentTextureArray) { + texture.touched = this.renderer.textureGC.count; + const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + if (this.boundTextures[location] !== texture) { + if (this.currentLocation !== location) { + this.currentLocation = location; + gl.activeTexture(gl.TEXTURE0 + location); + } + gl.bindTexture(texture.target, glTexture.texture); + } + if (glTexture.dirtyId !== texture.dirtyId) { + if (this.currentLocation !== location) { + this.currentLocation = location; + gl.activeTexture(gl.TEXTURE0 + location); + } + this.updateTexture(texture); + } else if (glTexture.dirtyStyleId !== texture.dirtyStyleId) { + this.updateTextureStyle(texture); + } + this.boundTextures[location] = texture; + } else { + if (this.currentLocation !== location) { + this.currentLocation = location; + gl.activeTexture(gl.TEXTURE0 + location); + } + gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[gl.TEXTURE_2D].texture); + this.boundTextures[location] = null; + } + } + reset() { + this._unknownBoundTextures = true; + this.hasIntegerTextures = false; + this.currentLocation = -1; + for (let i = 0; i < this.boundTextures.length; i++) { + this.boundTextures[i] = this.unknownTexture; + } + } + unbind(texture) { + const { gl, boundTextures } = this; + if (this._unknownBoundTextures) { + this._unknownBoundTextures = false; + for (let i = 0; i < boundTextures.length; i++) { + if (boundTextures[i] === this.unknownTexture) { + this.bind(null, i); + } + } + } + for (let i = 0; i < boundTextures.length; i++) { + if (boundTextures[i] === texture) { + if (this.currentLocation !== i) { + gl.activeTexture(gl.TEXTURE0 + i); + this.currentLocation = i; + } + gl.bindTexture(texture.target, this.emptyTextures[texture.target].texture); + boundTextures[i] = null; + } + } + } + ensureSamplerType(maxTextures) { + const { boundTextures, hasIntegerTextures, CONTEXT_UID } = this; + if (!hasIntegerTextures) { + return; + } + for (let i = maxTextures - 1; i >= 0; --i) { + const tex = boundTextures[i]; + if (tex) { + const glTexture = tex._glTextures[CONTEXT_UID]; + if (glTexture.samplerType !== SAMPLER_TYPES.FLOAT) { + this.renderer.texture.unbind(tex); + } + } + } + } + initTexture(texture) { + const glTexture = new GLTexture(this.gl.createTexture()); + glTexture.dirtyId = -1; + texture._glTextures[this.CONTEXT_UID] = glTexture; + this.managedTextures.push(texture); + texture.on("dispose", this.destroyTexture, this); + return glTexture; + } + initTextureType(texture, glTexture) { + glTexture.internalFormat = this.internalFormats[texture.type]?.[texture.format] ?? texture.format; + if (this.webGLVersion === 2 && texture.type === TYPES.HALF_FLOAT) { + glTexture.type = this.gl.HALF_FLOAT; + } else { + glTexture.type = texture.type; + } + } + updateTexture(texture) { + const glTexture = texture._glTextures[this.CONTEXT_UID]; + if (!glTexture) { + return; + } + const renderer = this.renderer; + this.initTextureType(texture, glTexture); + if (texture.resource?.upload(renderer, texture, glTexture)) { + if (glTexture.samplerType !== SAMPLER_TYPES.FLOAT) { + this.hasIntegerTextures = true; + } + } else { + const width = texture.realWidth; + const height = texture.realHeight; + const gl = renderer.gl; + if (glTexture.width !== width || glTexture.height !== height || glTexture.dirtyId < 0) { + glTexture.width = width; + glTexture.height = height; + gl.texImage2D(texture.target, 0, glTexture.internalFormat, width, height, 0, texture.format, glTexture.type, null); + } + } + if (texture.dirtyStyleId !== glTexture.dirtyStyleId) { + this.updateTextureStyle(texture); + } + glTexture.dirtyId = texture.dirtyId; + } + destroyTexture(texture, skipRemove) { + const { gl } = this; + texture = texture.castToBaseTexture(); + if (texture._glTextures[this.CONTEXT_UID]) { + this.unbind(texture); + gl.deleteTexture(texture._glTextures[this.CONTEXT_UID].texture); + texture.off("dispose", this.destroyTexture, this); + delete texture._glTextures[this.CONTEXT_UID]; + if (!skipRemove) { + const i = this.managedTextures.indexOf(texture); + if (i !== -1) { + removeItems(this.managedTextures, i, 1); + } + } + } + } + updateTextureStyle(texture) { + const glTexture = texture._glTextures[this.CONTEXT_UID]; + if (!glTexture) { + return; + } + if ((texture.mipmap === MIPMAP_MODES.POW2 || this.webGLVersion !== 2) && !texture.isPowerOfTwo) { + glTexture.mipmap = false; + } else { + glTexture.mipmap = texture.mipmap >= 1; + } + if (this.webGLVersion !== 2 && !texture.isPowerOfTwo) { + glTexture.wrapMode = WRAP_MODES.CLAMP; + } else { + glTexture.wrapMode = texture.wrapMode; + } + if (texture.resource?.style(this.renderer, texture, glTexture)) { + } else { + this.setStyle(texture, glTexture); + } + glTexture.dirtyStyleId = texture.dirtyStyleId; + } + setStyle(texture, glTexture) { + const gl = this.gl; + if (glTexture.mipmap && texture.mipmap !== MIPMAP_MODES.ON_MANUAL) { + gl.generateMipmap(texture.target); + } + gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, glTexture.wrapMode); + gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, glTexture.wrapMode); + if (glTexture.mipmap) { + gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode === SCALE_MODES.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + const anisotropicExt = this.renderer.context.extensions.anisotropicFiltering; + if (anisotropicExt && texture.anisotropicLevel > 0 && texture.scaleMode === SCALE_MODES.LINEAR) { + const level = Math.min(texture.anisotropicLevel, gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT)); + gl.texParameterf(texture.target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, level); + } + } else { + gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode === SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST); + } + gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode === SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST); + } + destroy() { + this.renderer = null; + } + } + TextureSystem.extension = { + type: ExtensionType.RendererSystem, + name: "texture" + }; + extensions$1.add(TextureSystem); + + class TransformFeedbackSystem { + constructor(renderer) { + this.renderer = renderer; + } + contextChange() { + this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + } + bind(transformFeedback) { + const { gl, CONTEXT_UID } = this; + const glTransformFeedback = transformFeedback._glTransformFeedbacks[CONTEXT_UID] || this.createGLTransformFeedback(transformFeedback); + gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, glTransformFeedback); + } + unbind() { + const { gl } = this; + gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null); + } + beginTransformFeedback(drawMode, shader) { + const { gl, renderer } = this; + if (shader) { + renderer.shader.bind(shader); + } + gl.beginTransformFeedback(drawMode); + } + endTransformFeedback() { + const { gl } = this; + gl.endTransformFeedback(); + } + createGLTransformFeedback(tf) { + const { gl, renderer, CONTEXT_UID } = this; + const glTransformFeedback = gl.createTransformFeedback(); + tf._glTransformFeedbacks[CONTEXT_UID] = glTransformFeedback; + gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, glTransformFeedback); + for (let i = 0; i < tf.buffers.length; i++) { + const buffer = tf.buffers[i]; + if (!buffer) + continue; + renderer.buffer.update(buffer); + buffer._glBuffers[CONTEXT_UID].refCount++; + gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, i, buffer._glBuffers[CONTEXT_UID].buffer || null); + } + gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null); + tf.disposeRunner.add(this); + return glTransformFeedback; + } + disposeTransformFeedback(tf, contextLost) { + const glTF = tf._glTransformFeedbacks[this.CONTEXT_UID]; + const gl = this.gl; + tf.disposeRunner.remove(this); + const bufferSystem = this.renderer.buffer; + if (bufferSystem) { + for (let i = 0; i < tf.buffers.length; i++) { + const buffer = tf.buffers[i]; + if (!buffer) + continue; + const buf = buffer._glBuffers[this.CONTEXT_UID]; + if (buf) { + buf.refCount--; + if (buf.refCount === 0 && !contextLost) { + bufferSystem.dispose(buffer, contextLost); + } + } + } + } + if (!glTF) { + return; + } + if (!contextLost) { + gl.deleteTransformFeedback(glTF); + } + delete tf._glTransformFeedbacks[this.CONTEXT_UID]; + } + destroy() { + this.renderer = null; + } + } + TransformFeedbackSystem.extension = { + type: ExtensionType.RendererSystem, + name: "transformFeedback" + }; + extensions$1.add(TransformFeedbackSystem); + + class ViewSystem { + constructor(renderer) { + this.renderer = renderer; + } + init(options) { + this.screen = new Rectangle(0, 0, options.width, options.height); + this.element = options.view || settings.ADAPTER.createCanvas(); + this.resolution = options.resolution || settings.RESOLUTION; + this.autoDensity = !!options.autoDensity; + } + resizeView(desiredScreenWidth, desiredScreenHeight) { + this.element.width = Math.round(desiredScreenWidth * this.resolution); + this.element.height = Math.round(desiredScreenHeight * this.resolution); + const screenWidth = this.element.width / this.resolution; + const screenHeight = this.element.height / this.resolution; + this.screen.width = screenWidth; + this.screen.height = screenHeight; + if (this.autoDensity) { + this.element.style.width = `${screenWidth}px`; + this.element.style.height = `${screenHeight}px`; + } + this.renderer.emit("resize", screenWidth, screenHeight); + this.renderer.runners.resize.emit(this.screen.width, this.screen.height); + } + destroy(removeView) { + if (removeView) { + this.element.parentNode?.removeChild(this.element); + } + this.renderer = null; + this.element = null; + this.screen = null; + } + } + ViewSystem.defaultOptions = { + width: 800, + height: 600, + resolution: settings.RESOLUTION, + autoDensity: false + }; + ViewSystem.extension = { + type: [ + ExtensionType.RendererSystem, + ExtensionType.CanvasRendererSystem + ], + name: "_view" + }; + extensions$1.add(ViewSystem); + + settings.PREFER_ENV = ENV.WEBGL2; + settings.STRICT_TEXTURE_CACHE = false; + settings.RENDER_OPTIONS = { + ...ContextSystem.defaultOptions, + ...BackgroundSystem.defaultOptions, + ...ViewSystem.defaultOptions, + ...StartupSystem.defaultOptions + }; + Object.defineProperties(settings, { + WRAP_MODE: { + get() { + return BaseTexture.defaultOptions.wrapMode; + }, + set(value) { + deprecation$1("7.1.0", "settings.WRAP_MODE is deprecated, use BaseTexture.defaultOptions.wrapMode"); + BaseTexture.defaultOptions.wrapMode = value; + } + }, + SCALE_MODE: { + get() { + return BaseTexture.defaultOptions.scaleMode; + }, + set(value) { + deprecation$1("7.1.0", "settings.SCALE_MODE is deprecated, use BaseTexture.defaultOptions.scaleMode"); + BaseTexture.defaultOptions.scaleMode = value; + } + }, + MIPMAP_TEXTURES: { + get() { + return BaseTexture.defaultOptions.mipmap; + }, + set(value) { + deprecation$1("7.1.0", "settings.MIPMAP_TEXTURES is deprecated, use BaseTexture.defaultOptions.mipmap"); + BaseTexture.defaultOptions.mipmap = value; + } + }, + ANISOTROPIC_LEVEL: { + get() { + return BaseTexture.defaultOptions.anisotropicLevel; + }, + set(value) { + deprecation$1("7.1.0", "settings.ANISOTROPIC_LEVEL is deprecated, use BaseTexture.defaultOptions.anisotropicLevel"); + BaseTexture.defaultOptions.anisotropicLevel = value; + } + }, + FILTER_RESOLUTION: { + get() { + deprecation$1("7.1.0", "settings.FILTER_RESOLUTION is deprecated, use Filter.defaultResolution"); + return Filter.defaultResolution; + }, + set(value) { + Filter.defaultResolution = value; + } + }, + FILTER_MULTISAMPLE: { + get() { + deprecation$1("7.1.0", "settings.FILTER_MULTISAMPLE is deprecated, use Filter.defaultMultisample"); + return Filter.defaultMultisample; + }, + set(value) { + Filter.defaultMultisample = value; + } + }, + SPRITE_MAX_TEXTURES: { + get() { + return BatchRenderer.defaultMaxTextures; + }, + set(value) { + deprecation$1("7.1.0", "settings.SPRITE_MAX_TEXTURES is deprecated, use BatchRenderer.defaultMaxTextures"); + BatchRenderer.defaultMaxTextures = value; + } + }, + SPRITE_BATCH_SIZE: { + get() { + return BatchRenderer.defaultBatchSize; + }, + set(value) { + deprecation$1("7.1.0", "settings.SPRITE_BATCH_SIZE is deprecated, use BatchRenderer.defaultBatchSize"); + BatchRenderer.defaultBatchSize = value; + } + }, + CAN_UPLOAD_SAME_BUFFER: { + get() { + return BatchRenderer.canUploadSameBuffer; + }, + set(value) { + deprecation$1("7.1.0", "settings.CAN_UPLOAD_SAME_BUFFER is deprecated, use BatchRenderer.canUploadSameBuffer"); + BatchRenderer.canUploadSameBuffer = value; + } + }, + GC_MODE: { + get() { + return TextureGCSystem.defaultMode; + }, + set(value) { + deprecation$1("7.1.0", "settings.GC_MODE is deprecated, use TextureGCSystem.defaultMode"); + TextureGCSystem.defaultMode = value; + } + }, + GC_MAX_IDLE: { + get() { + return TextureGCSystem.defaultMaxIdle; + }, + set(value) { + deprecation$1("7.1.0", "settings.GC_MAX_IDLE is deprecated, use TextureGCSystem.defaultMaxIdle"); + TextureGCSystem.defaultMaxIdle = value; + } + }, + GC_MAX_CHECK_COUNT: { + get() { + return TextureGCSystem.defaultCheckCountMax; + }, + set(value) { + deprecation$1("7.1.0", "settings.GC_MAX_CHECK_COUNT is deprecated, use TextureGCSystem.defaultCheckCountMax"); + TextureGCSystem.defaultCheckCountMax = value; + } + }, + PRECISION_VERTEX: { + get() { + return Program.defaultVertexPrecision; + }, + set(value) { + deprecation$1("7.1.0", "settings.PRECISION_VERTEX is deprecated, use Program.defaultVertexPrecision"); + Program.defaultVertexPrecision = value; + } + }, + PRECISION_FRAGMENT: { + get() { + return Program.defaultFragmentPrecision; + }, + set(value) { + deprecation$1("7.1.0", "settings.PRECISION_FRAGMENT is deprecated, use Program.defaultFragmentPrecision"); + Program.defaultFragmentPrecision = value; + } + } + }); + + var UPDATE_PRIORITY = /* @__PURE__ */ ((UPDATE_PRIORITY2) => { + UPDATE_PRIORITY2[UPDATE_PRIORITY2["INTERACTION"] = 50] = "INTERACTION"; + UPDATE_PRIORITY2[UPDATE_PRIORITY2["HIGH"] = 25] = "HIGH"; + UPDATE_PRIORITY2[UPDATE_PRIORITY2["NORMAL"] = 0] = "NORMAL"; + UPDATE_PRIORITY2[UPDATE_PRIORITY2["LOW"] = -25] = "LOW"; + UPDATE_PRIORITY2[UPDATE_PRIORITY2["UTILITY"] = -50] = "UTILITY"; + return UPDATE_PRIORITY2; + })(UPDATE_PRIORITY || {}); + + class TickerListener { + constructor(fn, context = null, priority = 0, once = false) { + this.next = null; + this.previous = null; + this._destroyed = false; + this.fn = fn; + this.context = context; + this.priority = priority; + this.once = once; + } + match(fn, context = null) { + return this.fn === fn && this.context === context; + } + emit(deltaTime) { + if (this.fn) { + if (this.context) { + this.fn.call(this.context, deltaTime); + } else { + this.fn(deltaTime); + } + } + const redirect = this.next; + if (this.once) { + this.destroy(true); + } + if (this._destroyed) { + this.next = null; + } + return redirect; + } + connect(previous) { + this.previous = previous; + if (previous.next) { + previous.next.previous = this; + } + this.next = previous.next; + previous.next = this; + } + destroy(hard = false) { + this._destroyed = true; + this.fn = null; + this.context = null; + if (this.previous) { + this.previous.next = this.next; + } + if (this.next) { + this.next.previous = this.previous; + } + const redirect = this.next; + this.next = hard ? null : redirect; + this.previous = null; + return redirect; + } + } + + const _Ticker = class { + constructor() { + this.autoStart = false; + this.deltaTime = 1; + this.lastTime = -1; + this.speed = 1; + this.started = false; + this._requestId = null; + this._maxElapsedMS = 100; + this._minElapsedMS = 0; + this._protected = false; + this._lastFrame = -1; + this._head = new TickerListener(null, null, Infinity); + this.deltaMS = 1 / _Ticker.targetFPMS; + this.elapsedMS = 1 / _Ticker.targetFPMS; + this._tick = (time) => { + this._requestId = null; + if (this.started) { + this.update(time); + if (this.started && this._requestId === null && this._head.next) { + this._requestId = requestAnimationFrame(this._tick); + } + } + }; + } + _requestIfNeeded() { + if (this._requestId === null && this._head.next) { + this.lastTime = performance.now(); + this._lastFrame = this.lastTime; + this._requestId = requestAnimationFrame(this._tick); + } + } + _cancelIfNeeded() { + if (this._requestId !== null) { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } + } + _startIfPossible() { + if (this.started) { + this._requestIfNeeded(); + } else if (this.autoStart) { + this.start(); + } + } + add(fn, context, priority = UPDATE_PRIORITY.NORMAL) { + return this._addListener(new TickerListener(fn, context, priority)); + } + addOnce(fn, context, priority = UPDATE_PRIORITY.NORMAL) { + return this._addListener(new TickerListener(fn, context, priority, true)); + } + _addListener(listener) { + let current = this._head.next; + let previous = this._head; + if (!current) { + listener.connect(previous); + } else { + while (current) { + if (listener.priority > current.priority) { + listener.connect(previous); + break; + } + previous = current; + current = current.next; + } + if (!listener.previous) { + listener.connect(previous); + } + } + this._startIfPossible(); + return this; + } + remove(fn, context) { + let listener = this._head.next; + while (listener) { + if (listener.match(fn, context)) { + listener = listener.destroy(); + } else { + listener = listener.next; + } + } + if (!this._head.next) { + this._cancelIfNeeded(); + } + return this; + } + get count() { + if (!this._head) { + return 0; + } + let count = 0; + let current = this._head; + while (current = current.next) { + count++; + } + return count; + } + start() { + if (!this.started) { + this.started = true; + this._requestIfNeeded(); + } + } + stop() { + if (this.started) { + this.started = false; + this._cancelIfNeeded(); + } + } + destroy() { + if (!this._protected) { + this.stop(); + let listener = this._head.next; + while (listener) { + listener = listener.destroy(true); + } + this._head.destroy(); + this._head = null; + } + } + update(currentTime = performance.now()) { + let elapsedMS; + if (currentTime > this.lastTime) { + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + if (elapsedMS > this._maxElapsedMS) { + elapsedMS = this._maxElapsedMS; + } + elapsedMS *= this.speed; + if (this._minElapsedMS) { + const delta = currentTime - this._lastFrame | 0; + if (delta < this._minElapsedMS) { + return; + } + this._lastFrame = currentTime - delta % this._minElapsedMS; + } + this.deltaMS = elapsedMS; + this.deltaTime = this.deltaMS * _Ticker.targetFPMS; + const head = this._head; + let listener = head.next; + while (listener) { + listener = listener.emit(this.deltaTime); + } + if (!head.next) { + this._cancelIfNeeded(); + } + } else { + this.deltaTime = this.deltaMS = this.elapsedMS = 0; + } + this.lastTime = currentTime; + } + get FPS() { + return 1e3 / this.elapsedMS; + } + get minFPS() { + return 1e3 / this._maxElapsedMS; + } + set minFPS(fps) { + const minFPS = Math.min(this.maxFPS, fps); + const minFPMS = Math.min(Math.max(0, minFPS) / 1e3, _Ticker.targetFPMS); + this._maxElapsedMS = 1 / minFPMS; + } + get maxFPS() { + if (this._minElapsedMS) { + return Math.round(1e3 / this._minElapsedMS); + } + return 0; + } + set maxFPS(fps) { + if (fps === 0) { + this._minElapsedMS = 0; + } else { + const maxFPS = Math.max(this.minFPS, fps); + this._minElapsedMS = 1 / (maxFPS / 1e3); + } + } + static get shared() { + if (!_Ticker._shared) { + const shared = _Ticker._shared = new _Ticker(); + shared.autoStart = true; + shared._protected = true; + } + return _Ticker._shared; + } + static get system() { + if (!_Ticker._system) { + const system = _Ticker._system = new _Ticker(); + system.autoStart = true; + system._protected = true; + } + return _Ticker._system; + } + }; + let Ticker = _Ticker; + Ticker.targetFPMS = 0.06; + + Object.defineProperties(settings, { + TARGET_FPMS: { + get() { + return Ticker.targetFPMS; + }, + set(value) { + deprecation$1("7.1.0", "settings.TARGET_FPMS is deprecated, use Ticker.targetFPMS"); + Ticker.targetFPMS = value; + } + } + }); + + class TickerPlugin { + static init(options) { + options = Object.assign({ + autoStart: true, + sharedTicker: false + }, options); + Object.defineProperty(this, "ticker", { + set(ticker) { + if (this._ticker) { + this._ticker.remove(this.render, this); + } + this._ticker = ticker; + if (ticker) { + ticker.add(this.render, this, UPDATE_PRIORITY.LOW); + } + }, + get() { + return this._ticker; + } + }); + this.stop = () => { + this._ticker.stop(); + }; + this.start = () => { + this._ticker.start(); + }; + this._ticker = null; + this.ticker = options.sharedTicker ? Ticker.shared : new Ticker(); + if (options.autoStart) { + this.start(); + } + } + static destroy() { + if (this._ticker) { + const oldTicker = this._ticker; + this.ticker = null; + oldTicker.destroy(); + } + } + } + TickerPlugin.extension = ExtensionType.Application; + extensions$1.add(TickerPlugin); + + const renderers = []; + extensions$1.handleByList(ExtensionType.Renderer, renderers); + function autoDetectRenderer(options) { + for (const RendererType of renderers) { + if (RendererType.test(options)) { + return new RendererType(options); + } + } + throw new Error("Unable to auto-detect a suitable renderer."); + } + + var $defaultVertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}"; + + var $defaultFilterVertex = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"; + + const defaultVertex = $defaultVertex; + const defaultFilterVertex = $defaultFilterVertex; + + class MultisampleSystem { + constructor(renderer) { + this.renderer = renderer; + } + contextChange(gl) { + let samples; + if (this.renderer.context.webGLVersion === 1) { + const framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + samples = gl.getParameter(gl.SAMPLES); + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + } else { + const framebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null); + samples = gl.getParameter(gl.SAMPLES); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, framebuffer); + } + if (samples >= MSAA_QUALITY.HIGH) { + this.multisample = MSAA_QUALITY.HIGH; + } else if (samples >= MSAA_QUALITY.MEDIUM) { + this.multisample = MSAA_QUALITY.MEDIUM; + } else if (samples >= MSAA_QUALITY.LOW) { + this.multisample = MSAA_QUALITY.LOW; + } else { + this.multisample = MSAA_QUALITY.NONE; + } + } + destroy() { + } + } + MultisampleSystem.extension = { + type: ExtensionType.RendererSystem, + name: "_multisample" + }; + extensions$1.add(MultisampleSystem); + + class GLBuffer { + constructor(buffer) { + this.buffer = buffer || null; + this.updateID = -1; + this.byteLength = -1; + this.refCount = 0; + } + } + + class BufferSystem { + constructor(renderer) { + this.renderer = renderer; + this.managedBuffers = {}; + this.boundBufferBases = {}; + } + destroy() { + this.renderer = null; + } + contextChange() { + this.disposeAll(true); + this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + } + bind(buffer) { + const { gl, CONTEXT_UID } = this; + const glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer); + gl.bindBuffer(buffer.type, glBuffer.buffer); + } + unbind(type) { + const { gl } = this; + gl.bindBuffer(type, null); + } + bindBufferBase(buffer, index) { + const { gl, CONTEXT_UID } = this; + if (this.boundBufferBases[index] !== buffer) { + const glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer); + this.boundBufferBases[index] = buffer; + gl.bindBufferBase(gl.UNIFORM_BUFFER, index, glBuffer.buffer); + } + } + bindBufferRange(buffer, index, offset) { + const { gl, CONTEXT_UID } = this; + offset = offset || 0; + const glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer); + gl.bindBufferRange(gl.UNIFORM_BUFFER, index || 0, glBuffer.buffer, offset * 256, 256); + } + update(buffer) { + const { gl, CONTEXT_UID } = this; + const glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer); + if (buffer._updateID === glBuffer.updateID) { + return; + } + glBuffer.updateID = buffer._updateID; + gl.bindBuffer(buffer.type, glBuffer.buffer); + if (glBuffer.byteLength >= buffer.data.byteLength) { + gl.bufferSubData(buffer.type, 0, buffer.data); + } else { + const drawType = buffer.static ? gl.STATIC_DRAW : gl.DYNAMIC_DRAW; + glBuffer.byteLength = buffer.data.byteLength; + gl.bufferData(buffer.type, buffer.data, drawType); + } + } + dispose(buffer, contextLost) { + if (!this.managedBuffers[buffer.id]) { + return; + } + delete this.managedBuffers[buffer.id]; + const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; + const gl = this.gl; + buffer.disposeRunner.remove(this); + if (!glBuffer) { + return; + } + if (!contextLost) { + gl.deleteBuffer(glBuffer.buffer); + } + delete buffer._glBuffers[this.CONTEXT_UID]; + } + disposeAll(contextLost) { + const all = Object.keys(this.managedBuffers); + for (let i = 0; i < all.length; i++) { + this.dispose(this.managedBuffers[all[i]], contextLost); + } + } + createGLBuffer(buffer) { + const { CONTEXT_UID, gl } = this; + buffer._glBuffers[CONTEXT_UID] = new GLBuffer(gl.createBuffer()); + this.managedBuffers[buffer.id] = buffer; + buffer.disposeRunner.add(this); + return buffer._glBuffers[CONTEXT_UID]; + } + } + BufferSystem.extension = { + type: ExtensionType.RendererSystem, + name: "buffer" + }; + extensions$1.add(BufferSystem); + + class ObjectRendererSystem { + constructor(renderer) { + this.renderer = renderer; + } + render(displayObject, options) { + const renderer = this.renderer; + let renderTexture; + let clear; + let transform; + let skipUpdateTransform; + if (options) { + renderTexture = options.renderTexture; + clear = options.clear; + transform = options.transform; + skipUpdateTransform = options.skipUpdateTransform; + } + this.renderingToScreen = !renderTexture; + renderer.runners.prerender.emit(); + renderer.emit("prerender"); + renderer.projection.transform = transform; + if (renderer.context.isLost) { + return; + } + if (!renderTexture) { + this.lastObjectRendered = displayObject; + } + if (!skipUpdateTransform) { + const cacheParent = displayObject.enableTempParent(); + displayObject.updateTransform(); + displayObject.disableTempParent(cacheParent); + } + renderer.renderTexture.bind(renderTexture); + renderer.batch.currentRenderer.start(); + if (clear ?? renderer.background.clearBeforeRender) { + renderer.renderTexture.clear(); + } + displayObject.render(renderer); + renderer.batch.currentRenderer.flush(); + if (renderTexture) { + if (options.blit) { + renderer.framebuffer.blit(); + } + renderTexture.baseTexture.update(); + } + renderer.runners.postrender.emit(); + renderer.projection.transform = null; + renderer.emit("postrender"); + } + destroy() { + this.renderer = null; + this.lastObjectRendered = null; + } + } + ObjectRendererSystem.extension = { + type: ExtensionType.RendererSystem, + name: "objectRenderer" + }; + extensions$1.add(ObjectRendererSystem); + + const _Renderer = class extends SystemManager { + constructor(options) { + super(); + this.type = RENDERER_TYPE.WEBGL; + options = Object.assign({}, settings.RENDER_OPTIONS, options); + this.gl = null; + this.CONTEXT_UID = 0; + this.globalUniforms = new UniformGroup({ + projectionMatrix: new Matrix() + }, true); + const systemConfig = { + runners: [ + "init", + "destroy", + "contextChange", + "resolutionChange", + "reset", + "update", + "postrender", + "prerender", + "resize" + ], + systems: _Renderer.__systems, + priority: [ + "_view", + "textureGenerator", + "background", + "_plugin", + "startup", + "context", + "state", + "texture", + "buffer", + "geometry", + "framebuffer", + "transformFeedback", + "mask", + "scissor", + "stencil", + "projection", + "textureGC", + "filter", + "renderTexture", + "batch", + "objectRenderer", + "_multisample" + ] + }; + this.setup(systemConfig); + if ("useContextAlpha" in options) { + deprecation$1("7.0.0", "options.useContextAlpha is deprecated, use options.premultipliedAlpha and options.backgroundAlpha instead"); + options.premultipliedAlpha = options.useContextAlpha && options.useContextAlpha !== "notMultiplied"; + options.backgroundAlpha = options.useContextAlpha === false ? 1 : options.backgroundAlpha; + } + this._plugin.rendererPlugins = _Renderer.__plugins; + this.options = options; + this.startup.run(this.options); + } + static test(options) { + if (options?.forceCanvas) { + return false; + } + return isWebGLSupported(); + } + render(displayObject, options) { + this.objectRenderer.render(displayObject, options); + } + resize(desiredScreenWidth, desiredScreenHeight) { + this._view.resizeView(desiredScreenWidth, desiredScreenHeight); + } + reset() { + this.runners.reset.emit(); + return this; + } + clear() { + this.renderTexture.bind(); + this.renderTexture.clear(); + } + destroy(removeView = false) { + this.runners.destroy.items.reverse(); + this.emitWithCustomOptions(this.runners.destroy, { + _view: removeView + }); + super.destroy(); + } + get plugins() { + return this._plugin.plugins; + } + get multisample() { + return this._multisample.multisample; + } + get width() { + return this._view.element.width; + } + get height() { + return this._view.element.height; + } + get resolution() { + return this._view.resolution; + } + set resolution(value) { + this._view.resolution = value; + this.runners.resolutionChange.emit(value); + } + get autoDensity() { + return this._view.autoDensity; + } + get view() { + return this._view.element; + } + get screen() { + return this._view.screen; + } + get lastObjectRendered() { + return this.objectRenderer.lastObjectRendered; + } + get renderingToScreen() { + return this.objectRenderer.renderingToScreen; + } + get rendererLogId() { + return `WebGL ${this.context.webGLVersion}`; + } + get clearBeforeRender() { + deprecation$1("7.0.0", "renderer.clearBeforeRender has been deprecated, please use renderer.background.clearBeforeRender instead."); + return this.background.clearBeforeRender; + } + get useContextAlpha() { + deprecation$1("7.0.0", "renderer.useContextAlpha has been deprecated, please use renderer.context.premultipliedAlpha instead."); + return this.context.useContextAlpha; + } + get preserveDrawingBuffer() { + deprecation$1("7.0.0", "renderer.preserveDrawingBuffer has been deprecated, we cannot truly know this unless pixi created the context"); + return this.context.preserveDrawingBuffer; + } + get backgroundColor() { + deprecation$1("7.0.0", "renderer.backgroundColor has been deprecated, use renderer.background.color instead."); + return this.background.color; + } + set backgroundColor(value) { + deprecation$1("7.0.0", "renderer.backgroundColor has been deprecated, use renderer.background.color instead."); + this.background.color = value; + } + get backgroundAlpha() { + deprecation$1("7.0.0", "renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."); + return this.background.alpha; + } + set backgroundAlpha(value) { + deprecation$1("7.0.0", "renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."); + this.background.alpha = value; + } + get powerPreference() { + deprecation$1("7.0.0", "renderer.powerPreference has been deprecated, we can only know this if pixi creates the context"); + return this.context.powerPreference; + } + generateTexture(displayObject, options) { + return this.textureGenerator.generateTexture(displayObject, options); + } + }; + let Renderer = _Renderer; + Renderer.extension = { + type: ExtensionType.Renderer, + priority: 1 + }; + Renderer.__plugins = {}; + Renderer.__systems = {}; + extensions$1.handleByMap(ExtensionType.RendererPlugin, Renderer.__plugins); + extensions$1.handleByMap(ExtensionType.RendererSystem, Renderer.__systems); + extensions$1.add(Renderer); + + class AbstractMultiResource extends Resource { + constructor(length, options) { + const { width, height } = options || {}; + super(width, height); + this.items = []; + this.itemDirtyIds = []; + for (let i = 0; i < length; i++) { + const partTexture = new BaseTexture(); + this.items.push(partTexture); + this.itemDirtyIds.push(-2); + } + this.length = length; + this._load = null; + this.baseTexture = null; + } + initFromArray(resources, options) { + for (let i = 0; i < this.length; i++) { + if (!resources[i]) { + continue; + } + if (resources[i].castToBaseTexture) { + this.addBaseTextureAt(resources[i].castToBaseTexture(), i); + } else if (resources[i] instanceof Resource) { + this.addResourceAt(resources[i], i); + } else { + this.addResourceAt(autoDetectResource(resources[i], options), i); + } + } + } + dispose() { + for (let i = 0, len = this.length; i < len; i++) { + this.items[i].destroy(); + } + this.items = null; + this.itemDirtyIds = null; + this._load = null; + } + addResourceAt(resource, index) { + if (!this.items[index]) { + throw new Error(`Index ${index} is out of bounds`); + } + if (resource.valid && !this.valid) { + this.resize(resource.width, resource.height); + } + this.items[index].setResource(resource); + return this; + } + bind(baseTexture) { + if (this.baseTexture !== null) { + throw new Error("Only one base texture per TextureArray is allowed"); + } + super.bind(baseTexture); + for (let i = 0; i < this.length; i++) { + this.items[i].parentTextureArray = baseTexture; + this.items[i].on("update", baseTexture.update, baseTexture); + } + } + unbind(baseTexture) { + super.unbind(baseTexture); + for (let i = 0; i < this.length; i++) { + this.items[i].parentTextureArray = null; + this.items[i].off("update", baseTexture.update, baseTexture); + } + } + load() { + if (this._load) { + return this._load; + } + const resources = this.items.map((item) => item.resource).filter((item) => item); + const promises = resources.map((item) => item.load()); + this._load = Promise.all(promises).then(() => { + const { realWidth, realHeight } = this.items[0]; + this.resize(realWidth, realHeight); + return Promise.resolve(this); + }); + return this._load; + } + } + + class ArrayResource extends AbstractMultiResource { + constructor(source, options) { + const { width, height } = options || {}; + let urls; + let length; + if (Array.isArray(source)) { + urls = source; + length = source.length; + } else { + length = source; + } + super(length, { width, height }); + if (urls) { + this.initFromArray(urls, options); + } + } + addBaseTextureAt(baseTexture, index) { + if (baseTexture.resource) { + this.addResourceAt(baseTexture.resource, index); + } else { + throw new Error("ArrayResource does not support RenderTexture"); + } + return this; + } + bind(baseTexture) { + super.bind(baseTexture); + baseTexture.target = TARGETS.TEXTURE_2D_ARRAY; + } + upload(renderer, texture, glTexture) { + const { length, itemDirtyIds, items } = this; + const { gl } = renderer; + if (glTexture.dirtyId < 0) { + gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, glTexture.internalFormat, this._width, this._height, length, 0, texture.format, glTexture.type, null); + } + for (let i = 0; i < length; i++) { + const item = items[i]; + if (itemDirtyIds[i] < item.dirtyId) { + itemDirtyIds[i] = item.dirtyId; + if (item.valid) { + gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, 0, 0, i, item.resource.width, item.resource.height, 1, texture.format, glTexture.type, item.resource.source); + } + } + } + return true; + } + } + + class CanvasResource extends BaseImageResource { + constructor(source) { + super(source); + } + static test(source) { + const { OffscreenCanvas } = globalThis; + if (OffscreenCanvas && source instanceof OffscreenCanvas) { + return true; + } + return globalThis.HTMLCanvasElement && source instanceof HTMLCanvasElement; + } + } + + const _CubeResource = class extends AbstractMultiResource { + constructor(source, options) { + const { width, height, autoLoad, linkBaseTexture } = options || {}; + if (source && source.length !== _CubeResource.SIDES) { + throw new Error(`Invalid length. Got ${source.length}, expected 6`); + } + super(6, { width, height }); + for (let i = 0; i < _CubeResource.SIDES; i++) { + this.items[i].target = TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + i; + } + this.linkBaseTexture = linkBaseTexture !== false; + if (source) { + this.initFromArray(source, options); + } + if (autoLoad !== false) { + this.load(); + } + } + bind(baseTexture) { + super.bind(baseTexture); + baseTexture.target = TARGETS.TEXTURE_CUBE_MAP; + } + addBaseTextureAt(baseTexture, index, linkBaseTexture) { + if (linkBaseTexture === void 0) { + linkBaseTexture = this.linkBaseTexture; + } + if (!this.items[index]) { + throw new Error(`Index ${index} is out of bounds`); + } + if (!this.linkBaseTexture || baseTexture.parentTextureArray || Object.keys(baseTexture._glTextures).length > 0) { + if (baseTexture.resource) { + this.addResourceAt(baseTexture.resource, index); + } else { + throw new Error(`CubeResource does not support copying of renderTexture.`); + } + } else { + baseTexture.target = TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + index; + baseTexture.parentTextureArray = this.baseTexture; + this.items[index] = baseTexture; + } + if (baseTexture.valid && !this.valid) { + this.resize(baseTexture.realWidth, baseTexture.realHeight); + } + this.items[index] = baseTexture; + return this; + } + upload(renderer, _baseTexture, glTexture) { + const dirty = this.itemDirtyIds; + for (let i = 0; i < _CubeResource.SIDES; i++) { + const side = this.items[i]; + if (dirty[i] < side.dirtyId || glTexture.dirtyId < _baseTexture.dirtyId) { + if (side.valid && side.resource) { + side.resource.upload(renderer, side, glTexture); + dirty[i] = side.dirtyId; + } else if (dirty[i] < -1) { + renderer.gl.texImage2D(side.target, 0, glTexture.internalFormat, _baseTexture.realWidth, _baseTexture.realHeight, 0, _baseTexture.format, glTexture.type, null); + dirty[i] = -1; + } + } + } + return true; + } + static test(source) { + return Array.isArray(source) && source.length === _CubeResource.SIDES; + } + }; + let CubeResource = _CubeResource; + CubeResource.SIDES = 6; + + class ImageBitmapResource extends BaseImageResource { + constructor(source, options) { + options = options || {}; + let baseSource; + let url; + if (typeof source === "string") { + baseSource = ImageBitmapResource.EMPTY; + url = source; + } else { + baseSource = source; + url = null; + } + super(baseSource); + this.url = url; + this.crossOrigin = options.crossOrigin ?? true; + this.alphaMode = typeof options.alphaMode === "number" ? options.alphaMode : null; + this._load = null; + if (options.autoLoad !== false) { + this.load(); + } + } + load() { + if (this._load) { + return this._load; + } + this._load = new Promise(async (resolve, reject) => { + if (this.url === null) { + resolve(this); + return; + } + try { + const response = await settings.ADAPTER.fetch(this.url, { + mode: this.crossOrigin ? "cors" : "no-cors" + }); + if (this.destroyed) + return; + const imageBlob = await response.blob(); + if (this.destroyed) + return; + const imageBitmap = await createImageBitmap(imageBlob, { + premultiplyAlpha: this.alphaMode === null || this.alphaMode === ALPHA_MODES.UNPACK ? "premultiply" : "none" + }); + if (this.destroyed) + return; + this.source = imageBitmap; + this.update(); + resolve(this); + } catch (e) { + if (this.destroyed) + return; + reject(e); + this.onError.emit(e); + } + }); + return this._load; + } + upload(renderer, baseTexture, glTexture) { + if (!(this.source instanceof ImageBitmap)) { + this.load(); + return false; + } + if (typeof this.alphaMode === "number") { + baseTexture.alphaMode = this.alphaMode; + } + return super.upload(renderer, baseTexture, glTexture); + } + dispose() { + if (this.source instanceof ImageBitmap) { + this.source.close(); + } + super.dispose(); + this._load = null; + } + static test(source) { + return !!globalThis.createImageBitmap && typeof ImageBitmap !== "undefined" && (typeof source === "string" || source instanceof ImageBitmap); + } + static get EMPTY() { + ImageBitmapResource._EMPTY = ImageBitmapResource._EMPTY ?? settings.ADAPTER.createCanvas(0, 0); + return ImageBitmapResource._EMPTY; + } + } + + const _SVGResource = class extends BaseImageResource { + constructor(sourceBase64, options) { + options = options || {}; + super(settings.ADAPTER.createCanvas()); + this._width = 0; + this._height = 0; + this.svg = sourceBase64; + this.scale = options.scale || 1; + this._overrideWidth = options.width; + this._overrideHeight = options.height; + this._resolve = null; + this._crossorigin = options.crossorigin; + this._load = null; + if (options.autoLoad !== false) { + this.load(); + } + } + load() { + if (this._load) { + return this._load; + } + this._load = new Promise((resolve) => { + this._resolve = () => { + this.resize(this.source.width, this.source.height); + resolve(this); + }; + if (_SVGResource.SVG_XML.test(this.svg.trim())) { + if (!btoa) { + throw new Error("Your browser doesn't support base64 conversions."); + } + this.svg = `data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(this.svg)))}`; + } + this._loadSvg(); + }); + return this._load; + } + _loadSvg() { + const tempImage = new Image(); + BaseImageResource.crossOrigin(tempImage, this.svg, this._crossorigin); + tempImage.src = this.svg; + tempImage.onerror = (event) => { + if (!this._resolve) { + return; + } + tempImage.onerror = null; + this.onError.emit(event); + }; + tempImage.onload = () => { + if (!this._resolve) { + return; + } + const svgWidth = tempImage.width; + const svgHeight = tempImage.height; + if (!svgWidth || !svgHeight) { + throw new Error("The SVG image must have width and height defined (in pixels), canvas API needs them."); + } + let width = svgWidth * this.scale; + let height = svgHeight * this.scale; + if (this._overrideWidth || this._overrideHeight) { + width = this._overrideWidth || this._overrideHeight / svgHeight * svgWidth; + height = this._overrideHeight || this._overrideWidth / svgWidth * svgHeight; + } + width = Math.round(width); + height = Math.round(height); + const canvas = this.source; + canvas.width = width; + canvas.height = height; + canvas._pixiId = `canvas_${uid()}`; + canvas.getContext("2d").drawImage(tempImage, 0, 0, svgWidth, svgHeight, 0, 0, width, height); + this._resolve(); + this._resolve = null; + }; + } + static getSize(svgString) { + const sizeMatch = _SVGResource.SVG_SIZE.exec(svgString); + const size = {}; + if (sizeMatch) { + size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3])); + size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7])); + } + return size; + } + dispose() { + super.dispose(); + this._resolve = null; + this._crossorigin = null; + } + static test(source, extension) { + return extension === "svg" || typeof source === "string" && source.startsWith("data:image/svg+xml") || typeof source === "string" && _SVGResource.SVG_XML.test(source); + } + }; + let SVGResource = _SVGResource; + SVGResource.SVG_XML = /^(<\?xml[^?]+\?>)?\s*()]*-->)?\s*\]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; + + const _VideoResource = class extends BaseImageResource { + constructor(source, options) { + options = options || {}; + if (!(source instanceof HTMLVideoElement)) { + const videoElement = document.createElement("video"); + videoElement.setAttribute("preload", "auto"); + videoElement.setAttribute("webkit-playsinline", ""); + videoElement.setAttribute("playsinline", ""); + if (typeof source === "string") { + source = [source]; + } + const firstSrc = source[0].src || source[0]; + BaseImageResource.crossOrigin(videoElement, firstSrc, options.crossorigin); + for (let i = 0; i < source.length; ++i) { + const sourceElement = document.createElement("source"); + let { src, mime } = source[i]; + src = src || source[i]; + const baseSrc = src.split("?").shift().toLowerCase(); + const ext = baseSrc.slice(baseSrc.lastIndexOf(".") + 1); + mime = mime || _VideoResource.MIME_TYPES[ext] || `video/${ext}`; + sourceElement.src = src; + sourceElement.type = mime; + videoElement.appendChild(sourceElement); + } + source = videoElement; + } + super(source); + this.noSubImage = true; + this._autoUpdate = true; + this._isConnectedToTicker = false; + this._updateFPS = options.updateFPS || 0; + this._msToNextUpdate = 0; + this.autoPlay = options.autoPlay !== false; + this._load = null; + this._resolve = null; + this._onCanPlay = this._onCanPlay.bind(this); + this._onError = this._onError.bind(this); + if (options.autoLoad !== false) { + this.load(); + } + } + update(_deltaTime = 0) { + if (!this.destroyed) { + const elapsedMS = Ticker.shared.elapsedMS * this.source.playbackRate; + this._msToNextUpdate = Math.floor(this._msToNextUpdate - elapsedMS); + if (!this._updateFPS || this._msToNextUpdate <= 0) { + super.update(); + this._msToNextUpdate = this._updateFPS ? Math.floor(1e3 / this._updateFPS) : 0; + } + } + } + load() { + if (this._load) { + return this._load; + } + const source = this.source; + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + source.complete = true; + } + source.addEventListener("play", this._onPlayStart.bind(this)); + source.addEventListener("pause", this._onPlayStop.bind(this)); + if (!this._isSourceReady()) { + source.addEventListener("canplay", this._onCanPlay); + source.addEventListener("canplaythrough", this._onCanPlay); + source.addEventListener("error", this._onError, true); + } else { + this._onCanPlay(); + } + this._load = new Promise((resolve) => { + if (this.valid) { + resolve(this); + } else { + this._resolve = resolve; + source.load(); + } + }); + return this._load; + } + _onError(event) { + this.source.removeEventListener("error", this._onError, true); + this.onError.emit(event); + } + _isSourcePlaying() { + const source = this.source; + return !source.paused && !source.ended && this._isSourceReady(); + } + _isSourceReady() { + const source = this.source; + return source.readyState > 2; + } + _onPlayStart() { + if (!this.valid) { + this._onCanPlay(); + } + if (this.autoUpdate && !this._isConnectedToTicker) { + Ticker.shared.add(this.update, this); + this._isConnectedToTicker = true; + } + } + _onPlayStop() { + if (this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + } + _onCanPlay() { + const source = this.source; + source.removeEventListener("canplay", this._onCanPlay); + source.removeEventListener("canplaythrough", this._onCanPlay); + const valid = this.valid; + this.resize(source.videoWidth, source.videoHeight); + if (!valid && this._resolve) { + this._resolve(this); + this._resolve = null; + } + if (this._isSourcePlaying()) { + this._onPlayStart(); + } else if (this.autoPlay) { + source.play(); + } + } + dispose() { + if (this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + const source = this.source; + if (source) { + source.removeEventListener("error", this._onError, true); + source.pause(); + source.src = ""; + source.load(); + } + super.dispose(); + } + get autoUpdate() { + return this._autoUpdate; + } + set autoUpdate(value) { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + if (!this._autoUpdate && this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } else if (this._autoUpdate && !this._isConnectedToTicker && this._isSourcePlaying()) { + Ticker.shared.add(this.update, this); + this._isConnectedToTicker = true; + } + } + } + get updateFPS() { + return this._updateFPS; + } + set updateFPS(value) { + if (value !== this._updateFPS) { + this._updateFPS = value; + } + } + static test(source, extension) { + return globalThis.HTMLVideoElement && source instanceof HTMLVideoElement || _VideoResource.TYPES.includes(extension); + } + }; + let VideoResource = _VideoResource; + VideoResource.TYPES = ["mp4", "m4v", "webm", "ogg", "ogv", "h264", "avi", "mov"]; + VideoResource.MIME_TYPES = { + ogv: "video/ogg", + mov: "video/quicktime", + m4v: "video/mp4" + }; + + INSTALLED.push(ImageBitmapResource, ImageResource, CanvasResource, VideoResource, SVGResource, BufferResource, CubeResource, ArrayResource); + + class TransformFeedback { + constructor() { + this._glTransformFeedbacks = {}; + this.buffers = []; + this.disposeRunner = new Runner("disposeTransformFeedback"); + } + bindBuffer(index, buffer) { + this.buffers[index] = buffer; + } + destroy() { + this.disposeRunner.emit(this, false); + } + } + + const VERSION = "7.2.4"; + + BaseTexture.prototype.getDrawableSource = function getDrawableSource() { + const resource = this.resource; + return resource ? resource.bitmap || resource.source : null; + }; + BaseRenderTexture.prototype._canvasRenderTarget = null; + Texture.prototype.patternCache = null; + Texture.prototype.tintCache = null; + + let canUseNewCanvasBlendModesValue; + function createColoredCanvas(color) { + const canvas = settings.ADAPTER.createCanvas(6, 1); + const context = canvas.getContext("2d"); + context.fillStyle = color; + context.fillRect(0, 0, 6, 1); + return canvas; + } + function canUseNewCanvasBlendModes() { + if (typeof document === "undefined") { + return false; + } + if (canUseNewCanvasBlendModesValue !== void 0) { + return canUseNewCanvasBlendModesValue; + } + const magenta = createColoredCanvas("#ff00ff"); + const yellow = createColoredCanvas("#ffff00"); + const canvas = settings.ADAPTER.createCanvas(6, 1); + const context = canvas.getContext("2d"); + context.globalCompositeOperation = "multiply"; + context.drawImage(magenta, 0, 0); + context.drawImage(yellow, 2, 0); + const imageData = context.getImageData(2, 0, 1, 1); + if (!imageData) { + canUseNewCanvasBlendModesValue = false; + } else { + const data = imageData.data; + canUseNewCanvasBlendModesValue = data[0] === 255 && data[1] === 0 && data[2] === 0; + } + return canUseNewCanvasBlendModesValue; + } + + function mapCanvasBlendModesToPixi(array = []) { + if (canUseNewCanvasBlendModes()) { + array[BLEND_MODES.NORMAL] = "source-over"; + array[BLEND_MODES.ADD] = "lighter"; + array[BLEND_MODES.MULTIPLY] = "multiply"; + array[BLEND_MODES.SCREEN] = "screen"; + array[BLEND_MODES.OVERLAY] = "overlay"; + array[BLEND_MODES.DARKEN] = "darken"; + array[BLEND_MODES.LIGHTEN] = "lighten"; + array[BLEND_MODES.COLOR_DODGE] = "color-dodge"; + array[BLEND_MODES.COLOR_BURN] = "color-burn"; + array[BLEND_MODES.HARD_LIGHT] = "hard-light"; + array[BLEND_MODES.SOFT_LIGHT] = "soft-light"; + array[BLEND_MODES.DIFFERENCE] = "difference"; + array[BLEND_MODES.EXCLUSION] = "exclusion"; + array[BLEND_MODES.HUE] = "hue"; + array[BLEND_MODES.SATURATION] = "saturation"; + array[BLEND_MODES.COLOR] = "color"; + array[BLEND_MODES.LUMINOSITY] = "luminosity"; + } else { + array[BLEND_MODES.NORMAL] = "source-over"; + array[BLEND_MODES.ADD] = "lighter"; + array[BLEND_MODES.MULTIPLY] = "source-over"; + array[BLEND_MODES.SCREEN] = "source-over"; + array[BLEND_MODES.OVERLAY] = "source-over"; + array[BLEND_MODES.DARKEN] = "source-over"; + array[BLEND_MODES.LIGHTEN] = "source-over"; + array[BLEND_MODES.COLOR_DODGE] = "source-over"; + array[BLEND_MODES.COLOR_BURN] = "source-over"; + array[BLEND_MODES.HARD_LIGHT] = "source-over"; + array[BLEND_MODES.SOFT_LIGHT] = "source-over"; + array[BLEND_MODES.DIFFERENCE] = "source-over"; + array[BLEND_MODES.EXCLUSION] = "source-over"; + array[BLEND_MODES.HUE] = "source-over"; + array[BLEND_MODES.SATURATION] = "source-over"; + array[BLEND_MODES.COLOR] = "source-over"; + array[BLEND_MODES.LUMINOSITY] = "source-over"; + } + array[BLEND_MODES.NORMAL_NPM] = array[BLEND_MODES.NORMAL]; + array[BLEND_MODES.ADD_NPM] = array[BLEND_MODES.ADD]; + array[BLEND_MODES.SCREEN_NPM] = array[BLEND_MODES.SCREEN]; + array[BLEND_MODES.SRC_IN] = "source-in"; + array[BLEND_MODES.SRC_OUT] = "source-out"; + array[BLEND_MODES.SRC_ATOP] = "source-atop"; + array[BLEND_MODES.DST_OVER] = "destination-over"; + array[BLEND_MODES.DST_IN] = "destination-in"; + array[BLEND_MODES.DST_OUT] = "destination-out"; + array[BLEND_MODES.DST_ATOP] = "destination-atop"; + array[BLEND_MODES.XOR] = "xor"; + array[BLEND_MODES.SUBTRACT] = "source-over"; + return array; + } + + const tempMatrix$2 = new Matrix(); + class CanvasContextSystem { + constructor(renderer) { + this.activeResolution = 1; + this.smoothProperty = "imageSmoothingEnabled"; + this.blendModes = mapCanvasBlendModesToPixi(); + this._activeBlendMode = null; + this._projTransform = null; + this._outerBlend = false; + this.renderer = renderer; + } + init() { + const alpha = this.renderer.background.alpha < 1; + this.rootContext = this.renderer.view.getContext("2d", { alpha }); + this.activeContext = this.rootContext; + if (!this.rootContext.imageSmoothingEnabled) { + const rc = this.rootContext; + if (rc.webkitImageSmoothingEnabled) { + this.smoothProperty = "webkitImageSmoothingEnabled"; + } else if (rc.mozImageSmoothingEnabled) { + this.smoothProperty = "mozImageSmoothingEnabled"; + } else if (rc.oImageSmoothingEnabled) { + this.smoothProperty = "oImageSmoothingEnabled"; + } else if (rc.msImageSmoothingEnabled) { + this.smoothProperty = "msImageSmoothingEnabled"; + } + } + } + setContextTransform(transform, roundPixels, localResolution) { + let mat = transform; + const proj = this._projTransform; + const contextResolution = this.activeResolution; + localResolution = localResolution || contextResolution; + if (proj) { + mat = tempMatrix$2; + mat.copyFrom(transform); + mat.prepend(proj); + } + if (roundPixels) { + this.activeContext.setTransform(mat.a * localResolution, mat.b * localResolution, mat.c * localResolution, mat.d * localResolution, mat.tx * contextResolution | 0, mat.ty * contextResolution | 0); + } else { + this.activeContext.setTransform(mat.a * localResolution, mat.b * localResolution, mat.c * localResolution, mat.d * localResolution, mat.tx * contextResolution, mat.ty * contextResolution); + } + } + clear(clearColor, alpha) { + const { activeContext: context, renderer } = this; + const fillColor = clearColor ? Color.shared.setValue(clearColor) : this.renderer.background.backgroundColor; + context.clearRect(0, 0, renderer.width, renderer.height); + if (clearColor) { + context.globalAlpha = alpha ?? this.renderer.background.alpha; + context.fillStyle = fillColor.toHex(); + context.fillRect(0, 0, renderer.width, renderer.height); + context.globalAlpha = 1; + } + } + setBlendMode(blendMode, readyForOuterBlend) { + const outerBlend = blendMode === BLEND_MODES.SRC_IN || blendMode === BLEND_MODES.SRC_OUT || blendMode === BLEND_MODES.DST_IN || blendMode === BLEND_MODES.DST_ATOP; + if (!readyForOuterBlend && outerBlend) { + blendMode = BLEND_MODES.NORMAL; + } + if (this._activeBlendMode === blendMode) { + return; + } + this._activeBlendMode = blendMode; + this._outerBlend = outerBlend; + this.activeContext.globalCompositeOperation = this.blendModes[blendMode]; + } + resize() { + if (this.smoothProperty) { + this.rootContext[this.smoothProperty] = BaseTexture.defaultOptions.scaleMode === SCALE_MODES.LINEAR; + } + } + invalidateBlendMode() { + this._activeBlendMode = this.blendModes.indexOf(this.activeContext.globalCompositeOperation); + } + destroy() { + this.renderer = null; + this.rootContext = null; + this.activeContext = null; + this.smoothProperty = null; + } + } + CanvasContextSystem.extension = { + type: ExtensionType.CanvasRendererSystem, + name: "canvasContext" + }; + extensions$1.add(CanvasContextSystem); + + class CanvasMaskSystem { + constructor(renderer) { + this._foundShapes = []; + this.renderer = renderer; + } + pushMask(maskData) { + const renderer = this.renderer; + const maskObject = maskData.maskObject || maskData; + renderer.canvasContext.activeContext.save(); + const foundShapes = this._foundShapes; + this.recursiveFindShapes(maskObject, foundShapes); + if (foundShapes.length > 0) { + const context = renderer.canvasContext.activeContext; + context.beginPath(); + for (let i = 0; i < foundShapes.length; i++) { + const shape = foundShapes[i]; + const transform = shape.transform.worldTransform; + this.renderer.canvasContext.setContextTransform(transform); + this.renderGraphicsShape(shape); + } + foundShapes.length = 0; + context.clip(); + } + } + recursiveFindShapes(container, out) { + if (container.geometry && container.geometry.graphicsData) { + out.push(container); + } + const { children } = container; + if (children) { + for (let i = 0; i < children.length; i++) { + this.recursiveFindShapes(children[i], out); + } + } + } + renderGraphicsShape(graphics) { + graphics.finishPoly(); + const context = this.renderer.canvasContext.activeContext; + const graphicsData = graphics.geometry.graphicsData; + const len = graphicsData.length; + if (len === 0) { + return; + } + for (let i = 0; i < len; i++) { + const data = graphicsData[i]; + const shape = data.shape; + if (shape.type === SHAPES.POLY) { + let points = shape.points; + const holes = data.holes; + let outerArea; + let innerArea; + let px; + let py; + context.moveTo(points[0], points[1]); + for (let j = 1; j < points.length / 2; j++) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + if (holes.length > 0) { + outerArea = 0; + px = points[0]; + py = points[1]; + for (let j = 2; j + 2 < points.length; j += 2) { + outerArea += (points[j] - px) * (points[j + 3] - py) - (points[j + 2] - px) * (points[j + 1] - py); + } + for (let k = 0; k < holes.length; k++) { + points = holes[k].shape.points; + if (!points) { + continue; + } + innerArea = 0; + px = points[0]; + py = points[1]; + for (let j = 2; j + 2 < points.length; j += 2) { + innerArea += (points[j] - px) * (points[j + 3] - py) - (points[j + 2] - px) * (points[j + 1] - py); + } + if (innerArea * outerArea < 0) { + context.moveTo(points[0], points[1]); + for (let j = 2; j < points.length; j += 2) { + context.lineTo(points[j], points[j + 1]); + } + } else { + context.moveTo(points[points.length - 2], points[points.length - 1]); + for (let j = points.length - 4; j >= 0; j -= 2) { + context.lineTo(points[j], points[j + 1]); + } + } + if (holes[k].shape.closeStroke) { + context.closePath(); + } + } + } + if (points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) { + context.closePath(); + } + } else if (shape.type === SHAPES.RECT) { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } else if (shape.type === SHAPES.CIRC) { + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } else if (shape.type === SHAPES.ELIP) { + const w = shape.width * 2; + const h = shape.height * 2; + const x = shape.x - w / 2; + const y = shape.y - h / 2; + const kappa = 0.5522848; + const ox = w / 2 * kappa; + const oy = h / 2 * kappa; + const xe = x + w; + const ye = y + h; + const xm = x + w / 2; + const ym = y + h / 2; + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } else if (shape.type === SHAPES.RREC) { + const rx = shape.x; + const ry = shape.y; + const width = shape.width; + const height = shape.height; + let radius = shape.radius; + const maxRadius = Math.min(width, height) / 2; + radius = radius > maxRadius ? maxRadius : radius; + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } + } + popMask(renderer) { + renderer.canvasContext.activeContext.restore(); + renderer.canvasContext.invalidateBlendMode(); + } + destroy() { + } + } + CanvasMaskSystem.extension = { + type: ExtensionType.CanvasRendererSystem, + name: "mask" + }; + extensions$1.add(CanvasMaskSystem); + + class CanvasObjectRendererSystem { + constructor(renderer) { + this.renderer = renderer; + } + render(displayObject, options) { + const renderer = this.renderer; + if (!renderer.view) { + return; + } + const _context = renderer.canvasContext; + let renderTexture; + let clear; + let transform; + let skipUpdateTransform; + if (options) { + renderTexture = options.renderTexture; + clear = options.clear; + transform = options.transform; + skipUpdateTransform = options.skipUpdateTransform; + } + this.renderingToScreen = !renderTexture; + renderer.emit("prerender"); + const rootResolution = renderer.resolution; + if (renderTexture) { + renderTexture = renderTexture.castToBaseTexture(); + if (!renderTexture._canvasRenderTarget) { + renderTexture._canvasRenderTarget = new CanvasRenderTarget(renderTexture.width, renderTexture.height, renderTexture.resolution); + renderTexture.resource = new CanvasResource(renderTexture._canvasRenderTarget.canvas); + renderTexture.valid = true; + } + _context.activeContext = renderTexture._canvasRenderTarget.context; + renderer.canvasContext.activeResolution = renderTexture._canvasRenderTarget.resolution; + } else { + _context.activeContext = _context.rootContext; + _context.activeResolution = rootResolution; + } + const context2D = _context.activeContext; + _context._projTransform = transform || null; + if (!renderTexture) { + this.lastObjectRendered = displayObject; + } + if (!skipUpdateTransform) { + const cacheParent = displayObject.enableTempParent(); + displayObject.updateTransform(); + displayObject.disableTempParent(cacheParent); + } + context2D.save(); + context2D.setTransform(1, 0, 0, 1, 0, 0); + context2D.globalAlpha = 1; + _context._activeBlendMode = BLEND_MODES.NORMAL; + _context._outerBlend = false; + context2D.globalCompositeOperation = _context.blendModes[BLEND_MODES.NORMAL]; + if (clear ?? renderer.background.clearBeforeRender) { + if (this.renderingToScreen) { + context2D.clearRect(0, 0, renderer.width, renderer.height); + const background = renderer.background; + if (background.alpha > 0) { + context2D.globalAlpha = background.backgroundColor.alpha; + context2D.fillStyle = background.backgroundColor.toHex(); + context2D.fillRect(0, 0, renderer.width, renderer.height); + context2D.globalAlpha = 1; + } + } else { + renderTexture = renderTexture; + renderTexture._canvasRenderTarget.clear(); + if (renderTexture.clear.alpha > 0) { + context2D.globalAlpha = renderTexture.clear.alpha; + context2D.fillStyle = renderTexture.clear.toHex(); + context2D.fillRect(0, 0, renderTexture.realWidth, renderTexture.realHeight); + context2D.globalAlpha = 1; + } + } + } + const tempContext = _context.activeContext; + _context.activeContext = context2D; + displayObject.renderCanvas(renderer); + _context.activeContext = tempContext; + context2D.restore(); + _context.activeResolution = rootResolution; + _context._projTransform = null; + renderer.emit("postrender"); + } + destroy() { + this.lastObjectRendered = null; + this.render = null; + } + } + CanvasObjectRendererSystem.extension = { + type: ExtensionType.CanvasRendererSystem, + name: "objectRenderer" + }; + extensions$1.add(CanvasObjectRendererSystem); + + const { deprecation } = utils; + const _CanvasRenderer = class extends SystemManager { + constructor(options) { + super(); + this.type = RENDERER_TYPE.CANVAS; + this.rendererLogId = "Canvas"; + options = Object.assign({}, settings.RENDER_OPTIONS, options); + const systemConfig = { + runners: [ + "init", + "destroy", + "contextChange", + "resolutionChange", + "reset", + "update", + "postrender", + "prerender", + "resize" + ], + systems: _CanvasRenderer.__systems, + priority: [ + "textureGenerator", + "background", + "_view", + "_plugin", + "startup", + "mask", + "canvasContext", + "objectRenderer" + ] + }; + this.setup(systemConfig); + if ("useContextAlpha" in options) { + deprecation("7.0.0", "options.useContextAlpha is deprecated, use options.backgroundAlpha instead"); + options.backgroundAlpha = options.useContextAlpha === false ? 1 : options.backgroundAlpha; + } + this._plugin.rendererPlugins = _CanvasRenderer.__plugins; + this.options = options; + this.startup.run(this.options); + } + static test() { + return true; + } + generateTexture(displayObject, options) { + return this.textureGenerator.generateTexture(displayObject, options); + } + reset() { + } + render(displayObject, options) { + this.objectRenderer.render(displayObject, options); + } + clear() { + this.canvasContext.clear(); + } + destroy(removeView) { + this.runners.destroy.items.reverse(); + this.emitWithCustomOptions(this.runners.destroy, { + _view: removeView + }); + super.destroy(); + } + get plugins() { + return this._plugin.plugins; + } + resize(desiredScreenWidth, desiredScreenHeight) { + this._view.resizeView(desiredScreenWidth, desiredScreenHeight); + } + get width() { + return this._view.element.width; + } + get height() { + return this._view.element.height; + } + get resolution() { + return this._view.resolution; + } + set resolution(value) { + this._view.resolution = value; + this.runners.resolutionChange.emit(value); + } + get autoDensity() { + return this._view.autoDensity; + } + get view() { + return this._view.element; + } + get screen() { + return this._view.screen; + } + get lastObjectRendered() { + return this.objectRenderer.lastObjectRendered; + } + get renderingToScreen() { + return this.objectRenderer.renderingToScreen; + } + get clearBeforeRender() { + return this.background.clearBeforeRender; + } + get blendModes() { + deprecation("7.0.0", "renderer.blendModes has been deprecated, please use renderer.canvasContext.blendModes instead"); + return this.canvasContext.blendModes; + } + get maskManager() { + deprecation("7.0.0", "renderer.maskManager has been deprecated, please use renderer.mask instead"); + return this.mask; + } + get refresh() { + deprecation("7.0.0", "renderer.refresh has been deprecated"); + return true; + } + get rootContext() { + deprecation("7.0.0", "renderer.rootContext has been deprecated, please use renderer.canvasContext.rootContext instead"); + return this.canvasContext.rootContext; + } + get context() { + deprecation("7.0.0", "renderer.context has been deprecated, please use renderer.canvasContext.activeContext instead"); + return this.canvasContext.activeContext; + } + get smoothProperty() { + deprecation("7.0.0", "renderer.smoothProperty has been deprecated, please use renderer.canvasContext.smoothProperty instead"); + return this.canvasContext.smoothProperty; + } + setBlendMode(blendMode, readyForOuterBlend) { + deprecation("7.0.0", "renderer.setBlendMode has been deprecated, use renderer.canvasContext.setBlendMode instead"); + this.canvasContext.setBlendMode(blendMode, readyForOuterBlend); + } + invalidateBlendMode() { + deprecation("7.0.0", "renderer.invalidateBlendMode has been deprecated, use renderer.canvasContext.invalidateBlendMode instead"); + this.canvasContext.invalidateBlendMode(); + } + setContextTransform(transform, roundPixels, localResolution) { + deprecation("7.0.0", "renderer.setContextTransform has been deprecated, use renderer.canvasContext.setContextTransform instead"); + this.canvasContext.setContextTransform(transform, roundPixels, localResolution); + } + get backgroundColor() { + deprecation("7.0.0", "renderer.backgroundColor has been deprecated, use renderer.background.color instead."); + return this.background.color; + } + set backgroundColor(value) { + deprecation("7.0.0", "renderer.backgroundColor has been deprecated, use renderer.background.color instead."); + this.background.color = value; + } + get backgroundAlpha() { + deprecation("7.0.0", "renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."); + return this.background.alpha; + } + set backgroundAlpha(value) { + deprecation("7.0.0", "renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."); + this.background.alpha = value; + } + get preserveDrawingBuffer() { + deprecation("7.0.0", "renderer.preserveDrawingBuffer has been deprecated"); + return false; + } + get useContextAlpha() { + deprecation("7.0.0", "renderer.useContextAlpha has been deprecated"); + return false; + } + }; + let CanvasRenderer = _CanvasRenderer; + CanvasRenderer.extension = { + type: ExtensionType.Renderer, + priority: 0 + }; + CanvasRenderer.__plugins = {}; + CanvasRenderer.__systems = {}; + extensions$1.handleByMap(ExtensionType.CanvasRendererPlugin, CanvasRenderer.__plugins); + extensions$1.handleByMap(ExtensionType.CanvasRendererSystem, CanvasRenderer.__systems); + extensions$1.add(CanvasRenderer); + + const canvasUtils = { + canvas: null, + getTintedCanvas: (sprite, color) => { + const texture = sprite.texture; + color = canvasUtils.roundColor(color); + const stringColor = `#${`00000${(color | 0).toString(16)}`.slice(-6)}`; + texture.tintCache = texture.tintCache || {}; + const cachedCanvas = texture.tintCache[stringColor]; + let canvas; + if (cachedCanvas) { + if (cachedCanvas.tintId === texture._updateID) { + return texture.tintCache[stringColor]; + } + canvas = texture.tintCache[stringColor]; + } else { + canvas = settings.ADAPTER.createCanvas(); + } + canvasUtils.tintMethod(texture, color, canvas); + canvas.tintId = texture._updateID; + if (canvasUtils.convertTintToImage && canvas.toDataURL !== void 0) { + const tintImage = new Image(); + tintImage.src = canvas.toDataURL(); + texture.tintCache[stringColor] = tintImage; + } else { + texture.tintCache[stringColor] = canvas; + } + return canvas; + }, + getTintedPattern: (texture, color) => { + color = canvasUtils.roundColor(color); + const stringColor = `#${`00000${(color | 0).toString(16)}`.slice(-6)}`; + texture.patternCache = texture.patternCache || {}; + let pattern = texture.patternCache[stringColor]; + if (pattern?.tintId === texture._updateID) { + return pattern; + } + if (!canvasUtils.canvas) { + canvasUtils.canvas = settings.ADAPTER.createCanvas(); + } + canvasUtils.tintMethod(texture, color, canvasUtils.canvas); + pattern = canvasUtils.canvas.getContext("2d").createPattern(canvasUtils.canvas, "repeat"); + pattern.tintId = texture._updateID; + texture.patternCache[stringColor] = pattern; + return pattern; + }, + tintWithMultiply: (texture, color, canvas) => { + const context = canvas.getContext("2d"); + const crop = texture._frame.clone(); + const resolution = texture.baseTexture.resolution; + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + context.save(); + context.fillStyle = `#${`00000${(color | 0).toString(16)}`.slice(-6)}`; + context.fillRect(0, 0, crop.width, crop.height); + context.globalCompositeOperation = "multiply"; + const source = texture.baseTexture.getDrawableSource(); + context.drawImage(source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + context.globalCompositeOperation = "destination-atop"; + context.drawImage(source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + context.restore(); + }, + tintWithOverlay: (texture, color, canvas) => { + const context = canvas.getContext("2d"); + const crop = texture._frame.clone(); + const resolution = texture.baseTexture.resolution; + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + context.save(); + context.globalCompositeOperation = "copy"; + context.fillStyle = `#${`00000${(color | 0).toString(16)}`.slice(-6)}`; + context.fillRect(0, 0, crop.width, crop.height); + context.globalCompositeOperation = "destination-atop"; + context.drawImage(texture.baseTexture.getDrawableSource(), crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + context.restore(); + }, + tintWithPerPixel: (texture, color, canvas) => { + const context = canvas.getContext("2d"); + const crop = texture._frame.clone(); + const resolution = texture.baseTexture.resolution; + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + context.save(); + context.globalCompositeOperation = "copy"; + context.drawImage(texture.baseTexture.getDrawableSource(), crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + context.restore(); + const [r, g, b] = Color.shared.setValue(color).toArray(); + const pixelData = context.getImageData(0, 0, crop.width, crop.height); + const pixels = pixelData.data; + for (let i = 0; i < pixels.length; i += 4) { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + } + context.putImageData(pixelData, 0, 0); + }, + roundColor: (color) => Color.shared.setValue(color).round(canvasUtils.cacheStepsPerColorChannel).toNumber(), + cacheStepsPerColorChannel: 8, + convertTintToImage: false, + canUseMultiply: canUseNewCanvasBlendModes(), + tintMethod: null + }; + canvasUtils.tintMethod = canvasUtils.canUseMultiply ? canvasUtils.tintWithMultiply : canvasUtils.tintWithPerPixel; + + class Bounds { + constructor() { + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + this.rect = null; + this.updateID = -1; + } + isEmpty() { + return this.minX > this.maxX || this.minY > this.maxY; + } + clear() { + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + } + getRectangle(rect) { + if (this.minX > this.maxX || this.minY > this.maxY) { + return Rectangle.EMPTY; + } + rect = rect || new Rectangle(0, 0, 1, 1); + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + return rect; + } + addPoint(point) { + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); + } + addPointMatrix(matrix, point) { + const { a, b, c, d, tx, ty } = matrix; + const x = a * point.x + c * point.y + tx; + const y = b * point.x + d * point.y + ty; + this.minX = Math.min(this.minX, x); + this.maxX = Math.max(this.maxX, x); + this.minY = Math.min(this.minY, y); + this.maxY = Math.max(this.maxY, y); + } + addQuad(vertices) { + let minX = this.minX; + let minY = this.minY; + let maxX = this.maxX; + let maxY = this.maxY; + let x = vertices[0]; + let y = vertices[1]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + } + addFrame(transform, x0, y0, x1, y1) { + this.addFrameMatrix(transform.worldTransform, x0, y0, x1, y1); + } + addFrameMatrix(matrix, x0, y0, x1, y1) { + const a = matrix.a; + const b = matrix.b; + const c = matrix.c; + const d = matrix.d; + const tx = matrix.tx; + const ty = matrix.ty; + let minX = this.minX; + let minY = this.minY; + let maxX = this.maxX; + let maxY = this.maxY; + let x = a * x0 + c * y0 + tx; + let y = b * x0 + d * y0 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = a * x1 + c * y0 + tx; + y = b * x1 + d * y0 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = a * x0 + c * y1 + tx; + y = b * x0 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = a * x1 + c * y1 + tx; + y = b * x1 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + } + addVertexData(vertexData, beginOffset, endOffset) { + let minX = this.minX; + let minY = this.minY; + let maxX = this.maxX; + let maxY = this.maxY; + for (let i = beginOffset; i < endOffset; i += 2) { + const x = vertexData[i]; + const y = vertexData[i + 1]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + } + addVertices(transform, vertices, beginOffset, endOffset) { + this.addVerticesMatrix(transform.worldTransform, vertices, beginOffset, endOffset); + } + addVerticesMatrix(matrix, vertices, beginOffset, endOffset, padX = 0, padY = padX) { + const a = matrix.a; + const b = matrix.b; + const c = matrix.c; + const d = matrix.d; + const tx = matrix.tx; + const ty = matrix.ty; + let minX = this.minX; + let minY = this.minY; + let maxX = this.maxX; + let maxY = this.maxY; + for (let i = beginOffset; i < endOffset; i += 2) { + const rawX = vertices[i]; + const rawY = vertices[i + 1]; + const x = a * rawX + c * rawY + tx; + const y = d * rawY + b * rawX + ty; + minX = Math.min(minX, x - padX); + maxX = Math.max(maxX, x + padX); + minY = Math.min(minY, y - padY); + maxY = Math.max(maxY, y + padY); + } + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + } + addBounds(bounds) { + const minX = this.minX; + const minY = this.minY; + const maxX = this.maxX; + const maxY = this.maxY; + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; + } + addBoundsMask(bounds, mask) { + const _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; + const _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; + const _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; + const _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; + if (_minX <= _maxX && _minY <= _maxY) { + const minX = this.minX; + const minY = this.minY; + const maxX = this.maxX; + const maxY = this.maxY; + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + } + addBoundsMatrix(bounds, matrix) { + this.addFrameMatrix(matrix, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY); + } + addBoundsArea(bounds, area) { + const _minX = bounds.minX > area.x ? bounds.minX : area.x; + const _minY = bounds.minY > area.y ? bounds.minY : area.y; + const _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : area.x + area.width; + const _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : area.y + area.height; + if (_minX <= _maxX && _minY <= _maxY) { + const minX = this.minX; + const minY = this.minY; + const maxX = this.maxX; + const maxY = this.maxY; + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + } + pad(paddingX = 0, paddingY = paddingX) { + if (!this.isEmpty()) { + this.minX -= paddingX; + this.maxX += paddingX; + this.minY -= paddingY; + this.maxY += paddingY; + } + } + addFramePad(x0, y0, x1, y1, padX, padY) { + x0 -= padX; + y0 -= padY; + x1 += padX; + y1 += padY; + this.minX = this.minX < x0 ? this.minX : x0; + this.maxX = this.maxX > x1 ? this.maxX : x1; + this.minY = this.minY < y0 ? this.minY : y0; + this.maxY = this.maxY > y1 ? this.maxY : y1; + } + } + + class DisplayObject extends eventemitter3 { + constructor() { + super(); + this.tempDisplayObjectParent = null; + this.transform = new Transform(); + this.alpha = 1; + this.visible = true; + this.renderable = true; + this.cullable = false; + this.cullArea = null; + this.parent = null; + this.worldAlpha = 1; + this._lastSortedIndex = 0; + this._zIndex = 0; + this.filterArea = null; + this.filters = null; + this._enabledFilters = null; + this._bounds = new Bounds(); + this._localBounds = null; + this._boundsID = 0; + this._boundsRect = null; + this._localBoundsRect = null; + this._mask = null; + this._maskRefCount = 0; + this._destroyed = false; + this.isSprite = false; + this.isMask = false; + } + static mixin(source) { + const keys = Object.keys(source); + for (let i = 0; i < keys.length; ++i) { + const propertyName = keys[i]; + Object.defineProperty(DisplayObject.prototype, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); + } + } + get destroyed() { + return this._destroyed; + } + _recursivePostUpdateTransform() { + if (this.parent) { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); + } else { + this.transform.updateTransform(this._tempDisplayObjectParent.transform); + } + } + updateTransform() { + this._boundsID++; + this.transform.updateTransform(this.parent.transform); + this.worldAlpha = this.alpha * this.parent.worldAlpha; + } + getBounds(skipUpdate, rect) { + if (!skipUpdate) { + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + if (this._bounds.updateID !== this._boundsID) { + this.calculateBounds(); + this._bounds.updateID = this._boundsID; + } + if (!rect) { + if (!this._boundsRect) { + this._boundsRect = new Rectangle(); + } + rect = this._boundsRect; + } + return this._bounds.getRectangle(rect); + } + getLocalBounds(rect) { + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new Rectangle(); + } + rect = this._localBoundsRect; + } + if (!this._localBounds) { + this._localBounds = new Bounds(); + } + const transformRef = this.transform; + const parentRef = this.parent; + this.parent = null; + this.transform = this._tempDisplayObjectParent.transform; + const worldBounds = this._bounds; + const worldBoundsID = this._boundsID; + this._bounds = this._localBounds; + const bounds = this.getBounds(false, rect); + this.parent = parentRef; + this.transform = transformRef; + this._bounds = worldBounds; + this._bounds.updateID += this._boundsID - worldBoundsID; + return bounds; + } + toGlobal(position, point, skipUpdate = false) { + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + return this.worldTransform.apply(position, point); + } + toLocal(position, from, point, skipUpdate) { + if (from) { + position = from.toGlobal(position, point, skipUpdate); + } + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + return this.worldTransform.applyInverse(position, point); + } + setParent(container) { + if (!container || !container.addChild) { + throw new Error("setParent: Argument must be a Container"); + } + container.addChild(this); + return container; + } + removeFromParent() { + this.parent?.removeChild(this); + } + setTransform(x = 0, y = 0, scaleX = 1, scaleY = 1, rotation = 0, skewX = 0, skewY = 0, pivotX = 0, pivotY = 0) { + this.position.x = x; + this.position.y = y; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation; + this.skew.x = skewX; + this.skew.y = skewY; + this.pivot.x = pivotX; + this.pivot.y = pivotY; + return this; + } + destroy(_options) { + this.removeFromParent(); + this._destroyed = true; + this.transform = null; + this.parent = null; + this._bounds = null; + this.mask = null; + this.cullArea = null; + this.filters = null; + this.filterArea = null; + this.hitArea = null; + this.eventMode = "auto"; + this.interactiveChildren = false; + this.emit("destroyed"); + this.removeAllListeners(); + } + get _tempDisplayObjectParent() { + if (this.tempDisplayObjectParent === null) { + this.tempDisplayObjectParent = new TemporaryDisplayObject(); + } + return this.tempDisplayObjectParent; + } + enableTempParent() { + const myParent = this.parent; + this.parent = this._tempDisplayObjectParent; + return myParent; + } + disableTempParent(cacheParent) { + this.parent = cacheParent; + } + get x() { + return this.position.x; + } + set x(value) { + this.transform.position.x = value; + } + get y() { + return this.position.y; + } + set y(value) { + this.transform.position.y = value; + } + get worldTransform() { + return this.transform.worldTransform; + } + get localTransform() { + return this.transform.localTransform; + } + get position() { + return this.transform.position; + } + set position(value) { + this.transform.position.copyFrom(value); + } + get scale() { + return this.transform.scale; + } + set scale(value) { + this.transform.scale.copyFrom(value); + } + get pivot() { + return this.transform.pivot; + } + set pivot(value) { + this.transform.pivot.copyFrom(value); + } + get skew() { + return this.transform.skew; + } + set skew(value) { + this.transform.skew.copyFrom(value); + } + get rotation() { + return this.transform.rotation; + } + set rotation(value) { + this.transform.rotation = value; + } + get angle() { + return this.transform.rotation * RAD_TO_DEG; + } + set angle(value) { + this.transform.rotation = value * DEG_TO_RAD; + } + get zIndex() { + return this._zIndex; + } + set zIndex(value) { + this._zIndex = value; + if (this.parent) { + this.parent.sortDirty = true; + } + } + get worldVisible() { + let item = this; + do { + if (!item.visible) { + return false; + } + item = item.parent; + } while (item); + return true; + } + get mask() { + return this._mask; + } + set mask(value) { + if (this._mask === value) { + return; + } + if (this._mask) { + const maskObject = this._mask.isMaskData ? this._mask.maskObject : this._mask; + if (maskObject) { + maskObject._maskRefCount--; + if (maskObject._maskRefCount === 0) { + maskObject.renderable = true; + maskObject.isMask = false; + } + } + } + this._mask = value; + if (this._mask) { + const maskObject = this._mask.isMaskData ? this._mask.maskObject : this._mask; + if (maskObject) { + if (maskObject._maskRefCount === 0) { + maskObject.renderable = false; + maskObject.isMask = true; + } + maskObject._maskRefCount++; + } + } + } + } + class TemporaryDisplayObject extends DisplayObject { + constructor() { + super(...arguments); + this.sortDirty = null; + } + } + DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; + + const tempMatrix$1 = new Matrix(); + function sortChildren(a, b) { + if (a.zIndex === b.zIndex) { + return a._lastSortedIndex - b._lastSortedIndex; + } + return a.zIndex - b.zIndex; + } + const _Container = class extends DisplayObject { + constructor() { + super(); + this.children = []; + this.sortableChildren = _Container.defaultSortableChildren; + this.sortDirty = false; + } + onChildrenChange(_length) { + } + addChild(...children) { + if (children.length > 1) { + for (let i = 0; i < children.length; i++) { + this.addChild(children[i]); + } + } else { + const child = children[0]; + if (child.parent) { + child.parent.removeChild(child); + } + child.parent = this; + this.sortDirty = true; + child.transform._parentID = -1; + this.children.push(child); + this._boundsID++; + this.onChildrenChange(this.children.length - 1); + this.emit("childAdded", child, this, this.children.length - 1); + child.emit("added", this); + } + return children[0]; + } + addChildAt(child, index) { + if (index < 0 || index > this.children.length) { + throw new Error(`${child}addChildAt: The index ${index} supplied is out of bounds ${this.children.length}`); + } + if (child.parent) { + child.parent.removeChild(child); + } + child.parent = this; + this.sortDirty = true; + child.transform._parentID = -1; + this.children.splice(index, 0, child); + this._boundsID++; + this.onChildrenChange(index); + child.emit("added", this); + this.emit("childAdded", child, this, index); + return child; + } + swapChildren(child, child2) { + if (child === child2) { + return; + } + const index1 = this.getChildIndex(child); + const index2 = this.getChildIndex(child2); + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); + } + getChildIndex(child) { + const index = this.children.indexOf(child); + if (index === -1) { + throw new Error("The supplied DisplayObject must be a child of the caller"); + } + return index; + } + setChildIndex(child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error(`The index ${index} supplied is out of bounds ${this.children.length}`); + } + const currentIndex = this.getChildIndex(child); + removeItems(this.children, currentIndex, 1); + this.children.splice(index, 0, child); + this.onChildrenChange(index); + } + getChildAt(index) { + if (index < 0 || index >= this.children.length) { + throw new Error(`getChildAt: Index (${index}) does not exist.`); + } + return this.children[index]; + } + removeChild(...children) { + if (children.length > 1) { + for (let i = 0; i < children.length; i++) { + this.removeChild(children[i]); + } + } else { + const child = children[0]; + const index = this.children.indexOf(child); + if (index === -1) + return null; + child.parent = null; + child.transform._parentID = -1; + removeItems(this.children, index, 1); + this._boundsID++; + this.onChildrenChange(index); + child.emit("removed", this); + this.emit("childRemoved", child, this, index); + } + return children[0]; + } + removeChildAt(index) { + const child = this.getChildAt(index); + child.parent = null; + child.transform._parentID = -1; + removeItems(this.children, index, 1); + this._boundsID++; + this.onChildrenChange(index); + child.emit("removed", this); + this.emit("childRemoved", child, this, index); + return child; + } + removeChildren(beginIndex = 0, endIndex = this.children.length) { + const begin = beginIndex; + const end = endIndex; + const range = end - begin; + let removed; + if (range > 0 && range <= end) { + removed = this.children.splice(begin, range); + for (let i = 0; i < removed.length; ++i) { + removed[i].parent = null; + if (removed[i].transform) { + removed[i].transform._parentID = -1; + } + } + this._boundsID++; + this.onChildrenChange(beginIndex); + for (let i = 0; i < removed.length; ++i) { + removed[i].emit("removed", this); + this.emit("childRemoved", removed[i], this, i); + } + return removed; + } else if (range === 0 && this.children.length === 0) { + return []; + } + throw new RangeError("removeChildren: numeric values are outside the acceptable range."); + } + sortChildren() { + let sortRequired = false; + for (let i = 0, j = this.children.length; i < j; ++i) { + const child = this.children[i]; + child._lastSortedIndex = i; + if (!sortRequired && child.zIndex !== 0) { + sortRequired = true; + } + } + if (sortRequired && this.children.length > 1) { + this.children.sort(sortChildren); + } + this.sortDirty = false; + } + updateTransform() { + if (this.sortableChildren && this.sortDirty) { + this.sortChildren(); + } + this._boundsID++; + this.transform.updateTransform(this.parent.transform); + this.worldAlpha = this.alpha * this.parent.worldAlpha; + for (let i = 0, j = this.children.length; i < j; ++i) { + const child = this.children[i]; + if (child.visible) { + child.updateTransform(); + } + } + } + calculateBounds() { + this._bounds.clear(); + this._calculateBounds(); + for (let i = 0; i < this.children.length; i++) { + const child = this.children[i]; + if (!child.visible || !child.renderable) { + continue; + } + child.calculateBounds(); + if (child._mask) { + const maskObject = child._mask.isMaskData ? child._mask.maskObject : child._mask; + if (maskObject) { + maskObject.calculateBounds(); + this._bounds.addBoundsMask(child._bounds, maskObject._bounds); + } else { + this._bounds.addBounds(child._bounds); + } + } else if (child.filterArea) { + this._bounds.addBoundsArea(child._bounds, child.filterArea); + } else { + this._bounds.addBounds(child._bounds); + } + } + this._bounds.updateID = this._boundsID; + } + getLocalBounds(rect, skipChildrenUpdate = false) { + const result = super.getLocalBounds(rect); + if (!skipChildrenUpdate) { + for (let i = 0, j = this.children.length; i < j; ++i) { + const child = this.children[i]; + if (child.visible) { + child.updateTransform(); + } + } + } + return result; + } + _calculateBounds() { + } + _renderWithCulling(renderer) { + const sourceFrame = renderer.renderTexture.sourceFrame; + if (!(sourceFrame.width > 0 && sourceFrame.height > 0)) { + return; + } + let bounds; + let transform; + if (this.cullArea) { + bounds = this.cullArea; + transform = this.worldTransform; + } else if (this._render !== _Container.prototype._render) { + bounds = this.getBounds(true); + } + const projectionTransform = renderer.projection.transform; + if (projectionTransform) { + if (transform) { + transform = tempMatrix$1.copyFrom(transform); + transform.prepend(projectionTransform); + } else { + transform = projectionTransform; + } + } + if (bounds && sourceFrame.intersects(bounds, transform)) { + this._render(renderer); + } else if (this.cullArea) { + return; + } + for (let i = 0, j = this.children.length; i < j; ++i) { + const child = this.children[i]; + const childCullable = child.cullable; + child.cullable = childCullable || !this.cullArea; + child.render(renderer); + child.cullable = childCullable; + } + } + render(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + if (this._mask || this.filters?.length) { + this.renderAdvanced(renderer); + } else if (this.cullable) { + this._renderWithCulling(renderer); + } else { + this._render(renderer); + for (let i = 0, j = this.children.length; i < j; ++i) { + this.children[i].render(renderer); + } + } + } + renderAdvanced(renderer) { + const filters = this.filters; + const mask = this._mask; + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } + this._enabledFilters.length = 0; + for (let i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); + } + } + } + const flush = filters && this._enabledFilters?.length || mask && (!mask.isMaskData || mask.enabled && (mask.autoDetect || mask.type !== MASK_TYPES.NONE)); + if (flush) { + renderer.batch.flush(); + } + if (filters && this._enabledFilters?.length) { + renderer.filter.push(this, this._enabledFilters); + } + if (mask) { + renderer.mask.push(this, this._mask); + } + if (this.cullable) { + this._renderWithCulling(renderer); + } else { + this._render(renderer); + for (let i = 0, j = this.children.length; i < j; ++i) { + this.children[i].render(renderer); + } + } + if (flush) { + renderer.batch.flush(); + } + if (mask) { + renderer.mask.pop(this); + } + if (filters && this._enabledFilters?.length) { + renderer.filter.pop(); + } + } + _render(_renderer) { + } + destroy(options) { + super.destroy(); + this.sortDirty = false; + const destroyChildren = typeof options === "boolean" ? options : options?.children; + const oldChildren = this.removeChildren(0, this.children.length); + if (destroyChildren) { + for (let i = 0; i < oldChildren.length; ++i) { + oldChildren[i].destroy(options); + } + } + } + get width() { + return this.scale.x * this.getLocalBounds().width; + } + set width(value) { + const width = this.getLocalBounds().width; + if (width !== 0) { + this.scale.x = value / width; + } else { + this.scale.x = 1; + } + this._width = value; + } + get height() { + return this.scale.y * this.getLocalBounds().height; + } + set height(value) { + const height = this.getLocalBounds().height; + if (height !== 0) { + this.scale.y = value / height; + } else { + this.scale.y = 1; + } + this._height = value; + } + }; + let Container = _Container; + Container.defaultSortableChildren = false; + Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; + + Object.defineProperties(settings, { + SORTABLE_CHILDREN: { + get() { + return Container.defaultSortableChildren; + }, + set(value) { + deprecation$1("7.1.0", "settings.SORTABLE_CHILDREN is deprecated, use Container.defaultSortableChildren"); + Container.defaultSortableChildren = value; + } + } + }); + + const tempPoint$2 = new Point(); + const indices = new Uint16Array([0, 1, 2, 0, 2, 3]); + class Sprite extends Container { + constructor(texture) { + super(); + this._anchor = new ObservablePoint(this._onAnchorUpdate, this, texture ? texture.defaultAnchor.x : 0, texture ? texture.defaultAnchor.y : 0); + this._texture = null; + this._width = 0; + this._height = 0; + this._tintColor = new Color(16777215); + this._tintRGB = null; + this.tint = 16777215; + this.blendMode = BLEND_MODES.NORMAL; + this._cachedTint = 16777215; + this.uvs = null; + this.texture = texture || Texture.EMPTY; + this.vertexData = new Float32Array(8); + this.vertexTrimmedData = null; + this._transformID = -1; + this._textureID = -1; + this._transformTrimmedID = -1; + this._textureTrimmedID = -1; + this.indices = indices; + this.pluginName = "batch"; + this.isSprite = true; + this._roundPixels = settings.ROUND_PIXELS; + } + _onTextureUpdate() { + this._textureID = -1; + this._textureTrimmedID = -1; + this._cachedTint = 16777215; + if (this._width) { + this.scale.x = sign(this.scale.x) * this._width / this._texture.orig.width; + } + if (this._height) { + this.scale.y = sign(this.scale.y) * this._height / this._texture.orig.height; + } + } + _onAnchorUpdate() { + this._transformID = -1; + this._transformTrimmedID = -1; + } + calculateVertices() { + const texture = this._texture; + if (this._transformID === this.transform._worldID && this._textureID === texture._updateID) { + return; + } + if (this._textureID !== texture._updateID) { + this.uvs = this._texture._uvs.uvsFloat32; + } + this._transformID = this.transform._worldID; + this._textureID = texture._updateID; + const wt = this.transform.worldTransform; + const a = wt.a; + const b = wt.b; + const c = wt.c; + const d = wt.d; + const tx = wt.tx; + const ty = wt.ty; + const vertexData = this.vertexData; + const trim = texture.trim; + const orig = texture.orig; + const anchor = this._anchor; + let w0 = 0; + let w1 = 0; + let h0 = 0; + let h1 = 0; + if (trim) { + w1 = trim.x - anchor._x * orig.width; + w0 = w1 + trim.width; + h1 = trim.y - anchor._y * orig.height; + h0 = h1 + trim.height; + } else { + w1 = -anchor._x * orig.width; + w0 = w1 + orig.width; + h1 = -anchor._y * orig.height; + h0 = h1 + orig.height; + } + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + if (this._roundPixels) { + const resolution = settings.RESOLUTION; + for (let i = 0; i < vertexData.length; ++i) { + vertexData[i] = Math.round(vertexData[i] * resolution) / resolution; + } + } + } + calculateTrimmedVertices() { + if (!this.vertexTrimmedData) { + this.vertexTrimmedData = new Float32Array(8); + } else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { + return; + } + this._transformTrimmedID = this.transform._worldID; + this._textureTrimmedID = this._texture._updateID; + const texture = this._texture; + const vertexData = this.vertexTrimmedData; + const orig = texture.orig; + const anchor = this._anchor; + const wt = this.transform.worldTransform; + const a = wt.a; + const b = wt.b; + const c = wt.c; + const d = wt.d; + const tx = wt.tx; + const ty = wt.ty; + const w1 = -anchor._x * orig.width; + const w0 = w1 + orig.width; + const h1 = -anchor._y * orig.height; + const h0 = h1 + orig.height; + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + } + _render(renderer) { + this.calculateVertices(); + renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + } + _calculateBounds() { + const trim = this._texture.trim; + const orig = this._texture.orig; + if (!trim || trim.width === orig.width && trim.height === orig.height) { + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } else { + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } + } + getLocalBounds(rect) { + if (this.children.length === 0) { + if (!this._localBounds) { + this._localBounds = new Bounds(); + } + this._localBounds.minX = this._texture.orig.width * -this._anchor._x; + this._localBounds.minY = this._texture.orig.height * -this._anchor._y; + this._localBounds.maxX = this._texture.orig.width * (1 - this._anchor._x); + this._localBounds.maxY = this._texture.orig.height * (1 - this._anchor._y); + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new Rectangle(); + } + rect = this._localBoundsRect; + } + return this._localBounds.getRectangle(rect); + } + return super.getLocalBounds.call(this, rect); + } + containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint$2); + const width = this._texture.orig.width; + const height = this._texture.orig.height; + const x1 = -width * this.anchor.x; + let y1 = 0; + if (tempPoint$2.x >= x1 && tempPoint$2.x < x1 + width) { + y1 = -height * this.anchor.y; + if (tempPoint$2.y >= y1 && tempPoint$2.y < y1 + height) { + return true; + } + } + return false; + } + destroy(options) { + super.destroy(options); + this._texture.off("update", this._onTextureUpdate, this); + this._anchor = null; + const destroyTexture = typeof options === "boolean" ? options : options?.texture; + if (destroyTexture) { + const destroyBaseTexture = typeof options === "boolean" ? options : options?.baseTexture; + this._texture.destroy(!!destroyBaseTexture); + } + this._texture = null; + } + static from(source, options) { + const texture = source instanceof Texture ? source : Texture.from(source, options); + return new Sprite(texture); + } + set roundPixels(value) { + if (this._roundPixels !== value) { + this._transformID = -1; + } + this._roundPixels = value; + } + get roundPixels() { + return this._roundPixels; + } + get width() { + return Math.abs(this.scale.x) * this._texture.orig.width; + } + set width(value) { + const s = sign(this.scale.x) || 1; + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + get height() { + return Math.abs(this.scale.y) * this._texture.orig.height; + } + set height(value) { + const s = sign(this.scale.y) || 1; + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + get anchor() { + return this._anchor; + } + set anchor(value) { + this._anchor.copyFrom(value); + } + get tint() { + return this._tintColor.value; + } + set tint(value) { + this._tintColor.setValue(value); + this._tintRGB = this._tintColor.toLittleEndianNumber(); + } + get tintValue() { + return this._tintColor.toNumber(); + } + get texture() { + return this._texture; + } + set texture(value) { + if (this._texture === value) { + return; + } + if (this._texture) { + this._texture.off("update", this._onTextureUpdate, this); + } + this._texture = value || Texture.EMPTY; + this._cachedTint = 16777215; + this._textureID = -1; + this._textureTrimmedID = -1; + if (value) { + if (value.baseTexture.valid) { + this._onTextureUpdate(); + } else { + value.once("update", this._onTextureUpdate, this); + } + } + } + } + + const tempPoint$1 = new Point(); + class TilingSprite extends Sprite { + constructor(texture, width = 100, height = 100) { + super(texture); + this.tileTransform = new Transform(); + this._width = width; + this._height = height; + this.uvMatrix = this.texture.uvMatrix || new TextureMatrix(texture); + this.pluginName = "tilingSprite"; + this.uvRespectAnchor = false; + } + get clampMargin() { + return this.uvMatrix.clampMargin; + } + set clampMargin(value) { + this.uvMatrix.clampMargin = value; + this.uvMatrix.update(true); + } + get tileScale() { + return this.tileTransform.scale; + } + set tileScale(value) { + this.tileTransform.scale.copyFrom(value); + } + get tilePosition() { + return this.tileTransform.position; + } + set tilePosition(value) { + this.tileTransform.position.copyFrom(value); + } + _onTextureUpdate() { + if (this.uvMatrix) { + this.uvMatrix.texture = this._texture; + } + this._cachedTint = 16777215; + } + _render(renderer) { + const texture = this._texture; + if (!texture || !texture.valid) { + return; + } + this.tileTransform.updateLocalTransform(); + this.uvMatrix.update(); + renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + } + _calculateBounds() { + const minX = this._width * -this._anchor._x; + const minY = this._height * -this._anchor._y; + const maxX = this._width * (1 - this._anchor._x); + const maxY = this._height * (1 - this._anchor._y); + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + } + getLocalBounds(rect) { + if (this.children.length === 0) { + this._bounds.minX = this._width * -this._anchor._x; + this._bounds.minY = this._height * -this._anchor._y; + this._bounds.maxX = this._width * (1 - this._anchor._x); + this._bounds.maxY = this._height * (1 - this._anchor._y); + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new Rectangle(); + } + rect = this._localBoundsRect; + } + return this._bounds.getRectangle(rect); + } + return super.getLocalBounds.call(this, rect); + } + containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint$1); + const width = this._width; + const height = this._height; + const x1 = -width * this.anchor._x; + if (tempPoint$1.x >= x1 && tempPoint$1.x < x1 + width) { + const y1 = -height * this.anchor._y; + if (tempPoint$1.y >= y1 && tempPoint$1.y < y1 + height) { + return true; + } + } + return false; + } + destroy(options) { + super.destroy(options); + this.tileTransform = null; + this.uvMatrix = null; + } + static from(source, options) { + const texture = source instanceof Texture ? source : Texture.from(source, options); + return new TilingSprite(texture, options.width, options.height); + } + get width() { + return this._width; + } + set width(value) { + this._width = value; + } + get height() { + return this._height; + } + set height(value) { + this._height = value; + } + } + + var gl2FragmentSrc = "#version 300 es\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nin vec2 vTextureCoord;\n\nout vec4 fragmentColor;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = vTextureCoord + ceil(uClampOffset - vTextureCoord);\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n vec2 unclamped = coord;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 texSample = texture(uSampler, coord, unclamped == coord ? 0.0f : -32.0f);// lod-bias very negative to force lod 0\n\n fragmentColor = texSample * uColor;\n}\n"; + + var gl2VertexSrc = "#version 300 es\n#define SHADER_NAME Tiling-Sprite-300\n\nprecision lowp float;\n\nin vec2 aVertexPosition;\nin vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nout vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n"; + + var gl1FragmentSrc = "#version 100\n#ifdef GL_EXT_shader_texture_lod\n #extension GL_EXT_shader_texture_lod : enable\n#endif\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = vTextureCoord + ceil(uClampOffset - vTextureCoord);\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n vec2 unclamped = coord;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n #ifdef GL_EXT_shader_texture_lod\n vec4 texSample = unclamped == coord\n ? texture2D(uSampler, coord) \n : texture2DLodEXT(uSampler, coord, 0);\n #else\n vec4 texSample = texture2D(uSampler, coord);\n #endif\n\n gl_FragColor = texSample * uColor;\n}\n"; + + var gl1VertexSrc = "#version 100\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n"; + + var fragmentSimpleSrc = "#version 100\n#define SHADER_NAME Tiling-Sprite-Simple-100\n\nprecision lowp float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 texSample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = texSample * uColor;\n}\n"; + + const tempMat = new Matrix(); + class TilingSpriteRenderer extends ObjectRenderer { + constructor(renderer) { + super(renderer); + renderer.runners.contextChange.add(this); + this.quad = new QuadUv(); + this.state = State.for2d(); + } + contextChange() { + const renderer = this.renderer; + const uniforms = { globals: renderer.globalUniforms }; + this.simpleShader = Shader.from(gl1VertexSrc, fragmentSimpleSrc, uniforms); + this.shader = renderer.context.webGLVersion > 1 ? Shader.from(gl2VertexSrc, gl2FragmentSrc, uniforms) : Shader.from(gl1VertexSrc, gl1FragmentSrc, uniforms); + } + render(ts) { + const renderer = this.renderer; + const quad = this.quad; + let vertices = quad.vertices; + vertices[0] = vertices[6] = ts._width * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + vertices[2] = vertices[4] = ts._width * (1 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1 - ts.anchor.y); + const anchorX = ts.uvRespectAnchor ? ts.anchor.x : 0; + const anchorY = ts.uvRespectAnchor ? ts.anchor.y : 0; + vertices = quad.uvs; + vertices[0] = vertices[6] = -anchorX; + vertices[1] = vertices[3] = -anchorY; + vertices[2] = vertices[4] = 1 - anchorX; + vertices[5] = vertices[7] = 1 - anchorY; + quad.invalidate(); + const tex = ts._texture; + const baseTex = tex.baseTexture; + const premultiplied = baseTex.alphaMode > 0; + const lt = ts.tileTransform.localTransform; + const uv = ts.uvMatrix; + let isSimple = baseTex.isPowerOfTwo && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + if (isSimple) { + if (!baseTex._glTextures[renderer.CONTEXT_UID]) { + if (baseTex.wrapMode === WRAP_MODES.CLAMP) { + baseTex.wrapMode = WRAP_MODES.REPEAT; + } + } else { + isSimple = baseTex.wrapMode !== WRAP_MODES.CLAMP; + } + } + const shader = isSimple ? this.simpleShader : this.shader; + const w = tex.width; + const h = tex.height; + const W = ts._width; + const H = ts._height; + tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + tempMat.invert(); + if (isSimple) { + tempMat.prepend(uv.mapCoord); + } else { + shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); + shader.uniforms.uClampFrame = uv.uClampFrame; + shader.uniforms.uClampOffset = uv.uClampOffset; + } + shader.uniforms.uTransform = tempMat.toArray(true); + shader.uniforms.uColor = Color.shared.setValue(ts.tint).premultiply(ts.worldAlpha, premultiplied).toArray(shader.uniforms.uColor); + shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); + shader.uniforms.uSampler = tex; + renderer.shader.bind(shader); + renderer.geometry.bind(quad); + this.state.blendMode = correctBlendMode(ts.blendMode, premultiplied); + renderer.state.set(this.state); + renderer.geometry.draw(this.renderer.gl.TRIANGLES, 6, 0); + } + } + TilingSpriteRenderer.extension = { + name: "tilingSprite", + type: ExtensionType.RendererPlugin + }; + extensions$1.add(TilingSpriteRenderer); + + const worldMatrix = new Matrix(); + const patternMatrix = new Matrix(); + const patternRect = [new Point(), new Point(), new Point(), new Point()]; + TilingSprite.prototype._renderCanvas = function _renderCanvas(renderer) { + const texture = this._texture; + if (!texture.baseTexture.valid) { + return; + } + const context = renderer.canvasContext.activeContext; + const transform = this.worldTransform; + const baseTexture = texture.baseTexture; + const source = baseTexture.getDrawableSource(); + const baseTextureResolution = baseTexture.resolution; + if (this._textureID !== this._texture._updateID || this._cachedTint !== this.tintValue) { + this._textureID = this._texture._updateID; + const tempCanvas = new CanvasRenderTarget(texture._frame.width, texture._frame.height, baseTextureResolution); + if (this.tintValue !== 16777215) { + this._tintedCanvas = canvasUtils.getTintedCanvas(this, this.tintValue); + tempCanvas.context.drawImage(this._tintedCanvas, 0, 0); + } else { + tempCanvas.context.drawImage(source, -texture._frame.x * baseTextureResolution, -texture._frame.y * baseTextureResolution); + } + this._cachedTint = this.tintValue; + this._canvasPattern = tempCanvas.context.createPattern(tempCanvas.canvas, "repeat"); + } + context.globalAlpha = this.worldAlpha; + renderer.canvasContext.setBlendMode(this.blendMode); + this.tileTransform.updateLocalTransform(); + const lt = this.tileTransform.localTransform; + const W = this._width; + const H = this._height; + worldMatrix.identity(); + patternMatrix.copyFrom(lt); + if (!this.uvRespectAnchor) { + patternMatrix.translate(-this.anchor.x * W, -this.anchor.y * H); + } + patternMatrix.scale(1 / baseTextureResolution, 1 / baseTextureResolution); + worldMatrix.prepend(patternMatrix); + worldMatrix.prepend(transform); + renderer.canvasContext.setContextTransform(worldMatrix); + context.fillStyle = this._canvasPattern; + const lx = this.anchor.x * -W; + const ly = this.anchor.y * -H; + patternRect[0].set(lx, ly); + patternRect[1].set(lx + W, ly); + patternRect[2].set(lx + W, ly + H); + patternRect[3].set(lx, ly + H); + for (let i = 0; i < 4; i++) { + patternMatrix.applyInverse(patternRect[i], patternRect[i]); + } + context.beginPath(); + context.moveTo(patternRect[0].x, patternRect[0].y); + for (let i = 1; i < 4; i++) { + context.lineTo(patternRect[i].x, patternRect[i].y); + } + context.closePath(); + context.fill(); + }; + + class ParticleContainer extends Container { + constructor(maxSize = 1500, properties, batchSize = 16384, autoResize = false) { + super(); + const maxBatchSize = 16384; + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } + this._properties = [false, true, false, false, false]; + this._maxSize = maxSize; + this._batchSize = batchSize; + this._buffers = null; + this._bufferUpdateIDs = []; + this._updateID = 0; + this.interactiveChildren = false; + this.blendMode = BLEND_MODES.NORMAL; + this.autoResize = autoResize; + this.roundPixels = true; + this.baseTexture = null; + this.setProperties(properties); + this._tintColor = new Color(0); + this.tintRgb = new Float32Array(3); + this.tint = 16777215; + } + setProperties(properties) { + if (properties) { + this._properties[0] = "vertices" in properties || "scale" in properties ? !!properties.vertices || !!properties.scale : this._properties[0]; + this._properties[1] = "position" in properties ? !!properties.position : this._properties[1]; + this._properties[2] = "rotation" in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = "uvs" in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = "tint" in properties || "alpha" in properties ? !!properties.tint || !!properties.alpha : this._properties[4]; + } + } + updateTransform() { + this.displayObjectUpdateTransform(); + } + get tint() { + return this._tintColor.value; + } + set tint(value) { + this._tintColor.setValue(value); + this._tintColor.toRgbArray(this.tintRgb); + } + render(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + if (!this.baseTexture) { + this.baseTexture = this.children[0]._texture.baseTexture; + if (!this.baseTexture.valid) { + this.baseTexture.once("update", () => this.onChildrenChange(0)); + } + } + renderer.batch.setObjectRenderer(renderer.plugins.particle); + renderer.plugins.particle.render(this); + } + onChildrenChange(smallestChildIndex) { + const bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + while (this._bufferUpdateIDs.length < bufferIndex) { + this._bufferUpdateIDs.push(0); + } + this._bufferUpdateIDs[bufferIndex] = ++this._updateID; + } + dispose() { + if (this._buffers) { + for (let i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + this._buffers = null; + } + } + destroy(options) { + super.destroy(options); + this.dispose(); + this._properties = null; + this._buffers = null; + this._bufferUpdateIDs = null; + } + } + + class ParticleBuffer { + constructor(properties, dynamicPropertyFlags, size) { + this.geometry = new Geometry(); + this.indexBuffer = null; + this.size = size; + this.dynamicProperties = []; + this.staticProperties = []; + for (let i = 0; i < properties.length; ++i) { + let property = properties[i]; + property = { + attributeName: property.attributeName, + size: property.size, + uploadFunction: property.uploadFunction, + type: property.type || TYPES.FLOAT, + offset: property.offset + }; + if (dynamicPropertyFlags[i]) { + this.dynamicProperties.push(property); + } else { + this.staticProperties.push(property); + } + } + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + this._updateID = 0; + this.initBuffers(); + } + initBuffers() { + const geometry = this.geometry; + let dynamicOffset = 0; + this.indexBuffer = new Buffer(createIndicesForQuads(this.size), true, true); + geometry.addIndex(this.indexBuffer); + this.dynamicStride = 0; + for (let i = 0; i < this.dynamicProperties.length; ++i) { + const property = this.dynamicProperties[i]; + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + const dynBuffer = new ArrayBuffer(this.size * this.dynamicStride * 4 * 4); + this.dynamicData = new Float32Array(dynBuffer); + this.dynamicDataUint32 = new Uint32Array(dynBuffer); + this.dynamicBuffer = new Buffer(this.dynamicData, false, false); + let staticOffset = 0; + this.staticStride = 0; + for (let i = 0; i < this.staticProperties.length; ++i) { + const property = this.staticProperties[i]; + property.offset = staticOffset; + staticOffset += property.size; + this.staticStride += property.size; + } + const statBuffer = new ArrayBuffer(this.size * this.staticStride * 4 * 4); + this.staticData = new Float32Array(statBuffer); + this.staticDataUint32 = new Uint32Array(statBuffer); + this.staticBuffer = new Buffer(this.staticData, true, false); + for (let i = 0; i < this.dynamicProperties.length; ++i) { + const property = this.dynamicProperties[i]; + geometry.addAttribute(property.attributeName, this.dynamicBuffer, 0, property.type === TYPES.UNSIGNED_BYTE, property.type, this.dynamicStride * 4, property.offset * 4); + } + for (let i = 0; i < this.staticProperties.length; ++i) { + const property = this.staticProperties[i]; + geometry.addAttribute(property.attributeName, this.staticBuffer, 0, property.type === TYPES.UNSIGNED_BYTE, property.type, this.staticStride * 4, property.offset * 4); + } + } + uploadDynamic(children, startIndex, amount) { + for (let i = 0; i < this.dynamicProperties.length; i++) { + const property = this.dynamicProperties[i]; + property.uploadFunction(children, startIndex, amount, property.type === TYPES.UNSIGNED_BYTE ? this.dynamicDataUint32 : this.dynamicData, this.dynamicStride, property.offset); + } + this.dynamicBuffer._updateID++; + } + uploadStatic(children, startIndex, amount) { + for (let i = 0; i < this.staticProperties.length; i++) { + const property = this.staticProperties[i]; + property.uploadFunction(children, startIndex, amount, property.type === TYPES.UNSIGNED_BYTE ? this.staticDataUint32 : this.staticData, this.staticStride, property.offset); + } + this.staticBuffer._updateID++; + } + destroy() { + this.indexBuffer = null; + this.dynamicProperties = null; + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + this.staticProperties = null; + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + this.geometry.destroy(); + } + } + + var fragment$6 = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n vec4 color = texture2D(uSampler, vTextureCoord) * vColor;\n gl_FragColor = color;\n}"; + + var vertex$3 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\n\nattribute vec2 aPositionCoord;\nattribute float aRotation;\n\nuniform mat3 translationMatrix;\nuniform vec4 uColor;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nvoid main(void){\n float x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);\n float y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);\n\n vec2 v = vec2(x, y);\n v = v + aPositionCoord;\n\n gl_Position = vec4((translationMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vColor = aColor * uColor;\n}\n"; + + class ParticleRenderer extends ObjectRenderer { + constructor(renderer) { + super(renderer); + this.shader = null; + this.properties = null; + this.tempMatrix = new Matrix(); + this.properties = [ + { + attributeName: "aVertexPosition", + size: 2, + uploadFunction: this.uploadVertices, + offset: 0 + }, + { + attributeName: "aPositionCoord", + size: 2, + uploadFunction: this.uploadPosition, + offset: 0 + }, + { + attributeName: "aRotation", + size: 1, + uploadFunction: this.uploadRotation, + offset: 0 + }, + { + attributeName: "aTextureCoord", + size: 2, + uploadFunction: this.uploadUvs, + offset: 0 + }, + { + attributeName: "aColor", + size: 1, + type: TYPES.UNSIGNED_BYTE, + uploadFunction: this.uploadTint, + offset: 0 + } + ]; + this.shader = Shader.from(vertex$3, fragment$6, {}); + this.state = State.for2d(); + } + render(container) { + const children = container.children; + const maxSize = container._maxSize; + const batchSize = container._batchSize; + const renderer = this.renderer; + let totalChildren = children.length; + if (totalChildren === 0) { + return; + } else if (totalChildren > maxSize && !container.autoResize) { + totalChildren = maxSize; + } + let buffers = container._buffers; + if (!buffers) { + buffers = container._buffers = this.generateBuffers(container); + } + const baseTexture = children[0]._texture.baseTexture; + const premultiplied = baseTexture.alphaMode > 0; + this.state.blendMode = correctBlendMode(container.blendMode, premultiplied); + renderer.state.set(this.state); + const gl = renderer.gl; + const m = container.worldTransform.copyTo(this.tempMatrix); + m.prepend(renderer.globalUniforms.uniforms.projectionMatrix); + this.shader.uniforms.translationMatrix = m.toArray(true); + this.shader.uniforms.uColor = Color.shared.setValue(container.tintRgb).premultiply(container.worldAlpha, premultiplied).toArray(this.shader.uniforms.uColor); + this.shader.uniforms.uSampler = baseTexture; + this.renderer.shader.bind(this.shader); + let updateStatic = false; + for (let i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { + let amount = totalChildren - i; + if (amount > batchSize) { + amount = batchSize; + } + if (j >= buffers.length) { + buffers.push(this._generateOneMoreBuffer(container)); + } + const buffer = buffers[j]; + buffer.uploadDynamic(children, i, amount); + const bid = container._bufferUpdateIDs[j] || 0; + updateStatic = updateStatic || buffer._updateID < bid; + if (updateStatic) { + buffer._updateID = container._updateID; + buffer.uploadStatic(children, i, amount); + } + renderer.geometry.bind(buffer.geometry); + gl.drawElements(gl.TRIANGLES, amount * 6, gl.UNSIGNED_SHORT, 0); + } + } + generateBuffers(container) { + const buffers = []; + const size = container._maxSize; + const batchSize = container._batchSize; + const dynamicPropertyFlags = container._properties; + for (let i = 0; i < size; i += batchSize) { + buffers.push(new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize)); + } + return buffers; + } + _generateOneMoreBuffer(container) { + const batchSize = container._batchSize; + const dynamicPropertyFlags = container._properties; + return new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize); + } + uploadVertices(children, startIndex, amount, array, stride, offset) { + let w0 = 0; + let w1 = 0; + let h0 = 0; + let h1 = 0; + for (let i = 0; i < amount; ++i) { + const sprite = children[startIndex + i]; + const texture = sprite._texture; + const sx = sprite.scale.x; + const sy = sprite.scale.y; + const trim = texture.trim; + const orig = texture.orig; + if (trim) { + w1 = trim.x - sprite.anchor.x * orig.width; + w0 = w1 + trim.width; + h1 = trim.y - sprite.anchor.y * orig.height; + h0 = h1 + trim.height; + } else { + w0 = orig.width * (1 - sprite.anchor.x); + w1 = orig.width * -sprite.anchor.x; + h0 = orig.height * (1 - sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + array[offset + stride * 2] = w0 * sx; + array[offset + stride * 2 + 1] = h0 * sy; + array[offset + stride * 3] = w1 * sx; + array[offset + stride * 3 + 1] = h0 * sy; + offset += stride * 4; + } + } + uploadPosition(children, startIndex, amount, array, stride, offset) { + for (let i = 0; i < amount; i++) { + const spritePosition = children[startIndex + i].position; + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + array[offset + stride * 2] = spritePosition.x; + array[offset + stride * 2 + 1] = spritePosition.y; + array[offset + stride * 3] = spritePosition.x; + array[offset + stride * 3 + 1] = spritePosition.y; + offset += stride * 4; + } + } + uploadRotation(children, startIndex, amount, array, stride, offset) { + for (let i = 0; i < amount; i++) { + const spriteRotation = children[startIndex + i].rotation; + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + stride * 2] = spriteRotation; + array[offset + stride * 3] = spriteRotation; + offset += stride * 4; + } + } + uploadUvs(children, startIndex, amount, array, stride, offset) { + for (let i = 0; i < amount; ++i) { + const textureUvs = children[startIndex + i]._texture._uvs; + if (textureUvs) { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + array[offset + stride * 2] = textureUvs.x2; + array[offset + stride * 2 + 1] = textureUvs.y2; + array[offset + stride * 3] = textureUvs.x3; + array[offset + stride * 3 + 1] = textureUvs.y3; + offset += stride * 4; + } else { + array[offset] = 0; + array[offset + 1] = 0; + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + array[offset + stride * 2] = 0; + array[offset + stride * 2 + 1] = 0; + array[offset + stride * 3] = 0; + array[offset + stride * 3 + 1] = 0; + offset += stride * 4; + } + } + } + uploadTint(children, startIndex, amount, array, stride, offset) { + for (let i = 0; i < amount; ++i) { + const sprite = children[startIndex + i]; + const result = Color.shared.setValue(sprite._tintRGB).toPremultiplied(sprite.alpha, sprite.texture.baseTexture.alphaMode > 0); + array[offset] = result; + array[offset + stride] = result; + array[offset + stride * 2] = result; + array[offset + stride * 3] = result; + offset += stride * 4; + } + } + destroy() { + super.destroy(); + if (this.shader) { + this.shader.destroy(); + this.shader = null; + } + this.tempMatrix = null; + } + } + ParticleRenderer.extension = { + name: "particle", + type: ExtensionType.RendererPlugin + }; + extensions$1.add(ParticleRenderer); + + ParticleContainer.prototype.renderCanvas = function renderCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + const context = renderer.canvasContext.activeContext; + const transform = this.worldTransform; + let isRotated = true; + let positionX = 0; + let positionY = 0; + let finalWidth = 0; + let finalHeight = 0; + renderer.canvasContext.setBlendMode(this.blendMode); + context.globalAlpha = this.worldAlpha; + this.displayObjectUpdateTransform(); + for (let i = 0; i < this.children.length; ++i) { + const child = this.children[i]; + if (!child.visible) { + continue; + } + if (!child._texture.valid) { + continue; + } + const frame = child._texture.frame; + context.globalAlpha = this.worldAlpha * child.alpha; + if (child.rotation % (Math.PI * 2) === 0) { + if (isRotated) { + renderer.canvasContext.setContextTransform(transform, false, 1); + isRotated = false; + } + positionX = child.anchor.x * (-frame.width * child.scale.x) + child.position.x + 0.5; + positionY = child.anchor.y * (-frame.height * child.scale.y) + child.position.y + 0.5; + finalWidth = frame.width * child.scale.x; + finalHeight = frame.height * child.scale.y; + } else { + if (!isRotated) { + isRotated = true; + } + child.displayObjectUpdateTransform(); + const childTransform = child.worldTransform; + renderer.canvasContext.setContextTransform(childTransform, this.roundPixels, 1); + positionX = child.anchor.x * -frame.width + 0.5; + positionY = child.anchor.y * -frame.height + 0.5; + finalWidth = frame.width; + finalHeight = frame.height; + } + const resolution = child._texture.baseTexture.resolution; + const contextResolution = renderer.canvasContext.activeResolution; + context.drawImage(child._texture.baseTexture.getDrawableSource(), frame.x * resolution, frame.y * resolution, frame.width * resolution, frame.height * resolution, positionX * contextResolution, positionY * contextResolution, finalWidth * contextResolution, finalHeight * contextResolution); + } + }; + + Container.prototype._renderCanvas = function _renderCanvas(_renderer) { + }; + Container.prototype.renderCanvas = function renderCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + if (this._mask) { + renderer.mask.pushMask(this._mask); + } + this._renderCanvas(renderer); + for (let i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderCanvas(renderer); + } + if (this._mask) { + renderer.mask.popMask(renderer); + } + }; + + DisplayObject.prototype.renderCanvas = function renderCanvas(_renderer) { + }; + + var TEXT_GRADIENT = /* @__PURE__ */ ((TEXT_GRADIENT2) => { + TEXT_GRADIENT2[TEXT_GRADIENT2["LINEAR_VERTICAL"] = 0] = "LINEAR_VERTICAL"; + TEXT_GRADIENT2[TEXT_GRADIENT2["LINEAR_HORIZONTAL"] = 1] = "LINEAR_HORIZONTAL"; + return TEXT_GRADIENT2; + })(TEXT_GRADIENT || {}); + + const contextSettings = { + willReadFrequently: true + }; + const _TextMetrics = class { + static get experimentalLetterSpacingSupported() { + let result = _TextMetrics._experimentalLetterSpacingSupported; + if (result !== void 0) { + const proto = settings.ADAPTER.getCanvasRenderingContext2D().prototype; + result = _TextMetrics._experimentalLetterSpacingSupported = "letterSpacing" in proto || "textLetterSpacing" in proto; + } + return result; + } + constructor(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) { + this.text = text; + this.style = style; + this.width = width; + this.height = height; + this.lines = lines; + this.lineWidths = lineWidths; + this.lineHeight = lineHeight; + this.maxLineWidth = maxLineWidth; + this.fontProperties = fontProperties; + } + static measureText(text, style, wordWrap, canvas = _TextMetrics._canvas) { + wordWrap = wordWrap === void 0 || wordWrap === null ? style.wordWrap : wordWrap; + const font = style.toFontString(); + const fontProperties = _TextMetrics.measureFont(font); + if (fontProperties.fontSize === 0) { + fontProperties.fontSize = style.fontSize; + fontProperties.ascent = style.fontSize; + } + const context = canvas.getContext("2d", contextSettings); + context.font = font; + const outputText = wordWrap ? _TextMetrics.wordWrap(text, style, canvas) : text; + const lines = outputText.split(/(?:\r\n|\r|\n)/); + const lineWidths = new Array(lines.length); + let maxLineWidth = 0; + for (let i = 0; i < lines.length; i++) { + const lineWidth = _TextMetrics._measureText(lines[i], style.letterSpacing, context); + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + let width = maxLineWidth + style.strokeThickness; + if (style.dropShadow) { + width += style.dropShadowDistance; + } + const lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; + let height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness * 2) + (lines.length - 1) * (lineHeight + style.leading); + if (style.dropShadow) { + height += style.dropShadowDistance; + } + return new _TextMetrics(text, style, width, height, lines, lineWidths, lineHeight + style.leading, maxLineWidth, fontProperties); + } + static _measureText(text, letterSpacing, context) { + let useExperimentalLetterSpacing = false; + if (_TextMetrics.experimentalLetterSpacingSupported) { + if (_TextMetrics.experimentalLetterSpacing) { + context.letterSpacing = `${letterSpacing}px`; + context.textLetterSpacing = `${letterSpacing}px`; + useExperimentalLetterSpacing = true; + } else { + context.letterSpacing = "0px"; + context.textLetterSpacing = "0px"; + } + } + let width = context.measureText(text).width; + if (width > 0) { + if (useExperimentalLetterSpacing) { + width -= letterSpacing; + } else { + width += (_TextMetrics.graphemeSegmenter(text).length - 1) * letterSpacing; + } + } + return width; + } + static wordWrap(text, style, canvas = _TextMetrics._canvas) { + const context = canvas.getContext("2d", contextSettings); + let width = 0; + let line = ""; + let lines = ""; + const cache = /* @__PURE__ */ Object.create(null); + const { letterSpacing, whiteSpace } = style; + const collapseSpaces = _TextMetrics.collapseSpaces(whiteSpace); + const collapseNewlines = _TextMetrics.collapseNewlines(whiteSpace); + let canPrependSpaces = !collapseSpaces; + const wordWrapWidth = style.wordWrapWidth + letterSpacing; + const tokens = _TextMetrics.tokenize(text); + for (let i = 0; i < tokens.length; i++) { + let token = tokens[i]; + if (_TextMetrics.isNewline(token)) { + if (!collapseNewlines) { + lines += _TextMetrics.addLine(line); + canPrependSpaces = !collapseSpaces; + line = ""; + width = 0; + continue; + } + token = " "; + } + if (collapseSpaces) { + const currIsBreakingSpace = _TextMetrics.isBreakingSpace(token); + const lastIsBreakingSpace = _TextMetrics.isBreakingSpace(line[line.length - 1]); + if (currIsBreakingSpace && lastIsBreakingSpace) { + continue; + } + } + const tokenWidth = _TextMetrics.getFromCache(token, letterSpacing, cache, context); + if (tokenWidth > wordWrapWidth) { + if (line !== "") { + lines += _TextMetrics.addLine(line); + line = ""; + width = 0; + } + if (_TextMetrics.canBreakWords(token, style.breakWords)) { + const characters = _TextMetrics.wordWrapSplit(token); + for (let j = 0; j < characters.length; j++) { + let char = characters[j]; + let lastChar = char; + let k = 1; + while (characters[j + k]) { + const nextChar = characters[j + k]; + if (!_TextMetrics.canBreakChars(lastChar, nextChar, token, j, style.breakWords)) { + char += nextChar; + } else { + break; + } + lastChar = nextChar; + k++; + } + j += k - 1; + const characterWidth = _TextMetrics.getFromCache(char, letterSpacing, cache, context); + if (characterWidth + width > wordWrapWidth) { + lines += _TextMetrics.addLine(line); + canPrependSpaces = false; + line = ""; + width = 0; + } + line += char; + width += characterWidth; + } + } else { + if (line.length > 0) { + lines += _TextMetrics.addLine(line); + line = ""; + width = 0; + } + const isLastToken = i === tokens.length - 1; + lines += _TextMetrics.addLine(token, !isLastToken); + canPrependSpaces = false; + line = ""; + width = 0; + } + } else { + if (tokenWidth + width > wordWrapWidth) { + canPrependSpaces = false; + lines += _TextMetrics.addLine(line); + line = ""; + width = 0; + } + if (line.length > 0 || !_TextMetrics.isBreakingSpace(token) || canPrependSpaces) { + line += token; + width += tokenWidth; + } + } + } + lines += _TextMetrics.addLine(line, false); + return lines; + } + static addLine(line, newLine = true) { + line = _TextMetrics.trimRight(line); + line = newLine ? `${line} +` : line; + return line; + } + static getFromCache(key, letterSpacing, cache, context) { + let width = cache[key]; + if (typeof width !== "number") { + width = _TextMetrics._measureText(key, letterSpacing, context) + letterSpacing; + cache[key] = width; + } + return width; + } + static collapseSpaces(whiteSpace) { + return whiteSpace === "normal" || whiteSpace === "pre-line"; + } + static collapseNewlines(whiteSpace) { + return whiteSpace === "normal"; + } + static trimRight(text) { + if (typeof text !== "string") { + return ""; + } + for (let i = text.length - 1; i >= 0; i--) { + const char = text[i]; + if (!_TextMetrics.isBreakingSpace(char)) { + break; + } + text = text.slice(0, -1); + } + return text; + } + static isNewline(char) { + if (typeof char !== "string") { + return false; + } + return _TextMetrics._newlines.includes(char.charCodeAt(0)); + } + static isBreakingSpace(char, _nextChar) { + if (typeof char !== "string") { + return false; + } + return _TextMetrics._breakingSpaces.includes(char.charCodeAt(0)); + } + static tokenize(text) { + const tokens = []; + let token = ""; + if (typeof text !== "string") { + return tokens; + } + for (let i = 0; i < text.length; i++) { + const char = text[i]; + const nextChar = text[i + 1]; + if (_TextMetrics.isBreakingSpace(char, nextChar) || _TextMetrics.isNewline(char)) { + if (token !== "") { + tokens.push(token); + token = ""; + } + tokens.push(char); + continue; + } + token += char; + } + if (token !== "") { + tokens.push(token); + } + return tokens; + } + static canBreakWords(_token, breakWords) { + return breakWords; + } + static canBreakChars(_char, _nextChar, _token, _index, _breakWords) { + return true; + } + static wordWrapSplit(token) { + return _TextMetrics.graphemeSegmenter(token); + } + static measureFont(font) { + if (_TextMetrics._fonts[font]) { + return _TextMetrics._fonts[font]; + } + const properties = { + ascent: 0, + descent: 0, + fontSize: 0 + }; + const canvas = _TextMetrics._canvas; + const context = _TextMetrics._context; + context.font = font; + const metricsString = _TextMetrics.METRICS_STRING + _TextMetrics.BASELINE_SYMBOL; + const width = Math.ceil(context.measureText(metricsString).width); + let baseline = Math.ceil(context.measureText(_TextMetrics.BASELINE_SYMBOL).width); + const height = Math.ceil(_TextMetrics.HEIGHT_MULTIPLIER * baseline); + baseline = baseline * _TextMetrics.BASELINE_MULTIPLIER | 0; + if (width === 0 || height === 0) { + _TextMetrics._fonts[font] = properties; + return properties; + } + canvas.width = width; + canvas.height = height; + context.fillStyle = "#f00"; + context.fillRect(0, 0, width, height); + context.font = font; + context.textBaseline = "alphabetic"; + context.fillStyle = "#000"; + context.fillText(metricsString, 0, baseline); + const imagedata = context.getImageData(0, 0, width, height).data; + const pixels = imagedata.length; + const line = width * 4; + let i = 0; + let idx = 0; + let stop = false; + for (i = 0; i < baseline; ++i) { + for (let j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx += line; + } else { + break; + } + } + properties.ascent = baseline - i; + idx = pixels - line; + stop = false; + for (i = height; i > baseline; --i) { + for (let j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx -= line; + } else { + break; + } + } + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + _TextMetrics._fonts[font] = properties; + return properties; + } + static clearMetrics(font = "") { + if (font) { + delete _TextMetrics._fonts[font]; + } else { + _TextMetrics._fonts = {}; + } + } + static get _canvas() { + if (!_TextMetrics.__canvas) { + let canvas; + try { + const c = new OffscreenCanvas(0, 0); + const context = c.getContext("2d", contextSettings); + if (context?.measureText) { + _TextMetrics.__canvas = c; + return c; + } + canvas = settings.ADAPTER.createCanvas(); + } catch (ex) { + canvas = settings.ADAPTER.createCanvas(); + } + canvas.width = canvas.height = 10; + _TextMetrics.__canvas = canvas; + } + return _TextMetrics.__canvas; + } + static get _context() { + if (!_TextMetrics.__context) { + _TextMetrics.__context = _TextMetrics._canvas.getContext("2d", contextSettings); + } + return _TextMetrics.__context; + } + }; + let TextMetrics = _TextMetrics; + TextMetrics.METRICS_STRING = "|\xC9q\xC5"; + TextMetrics.BASELINE_SYMBOL = "M"; + TextMetrics.BASELINE_MULTIPLIER = 1.4; + TextMetrics.HEIGHT_MULTIPLIER = 2; + TextMetrics.graphemeSegmenter = (() => { + if (typeof Intl?.Segmenter === "function") { + const segmenter = new Intl.Segmenter(); + return (s) => [...segmenter.segment(s)].map((x) => x.segment); + } + return (s) => [...s]; + })(); + TextMetrics.experimentalLetterSpacing = false; + TextMetrics._fonts = {}; + TextMetrics._newlines = [ + 10, + 13 + ]; + TextMetrics._breakingSpaces = [ + 9, + 32, + 8192, + 8193, + 8194, + 8195, + 8196, + 8197, + 8198, + 8200, + 8201, + 8202, + 8287, + 12288 + ]; + + const genericFontFamilies = [ + "serif", + "sans-serif", + "monospace", + "cursive", + "fantasy", + "system-ui" + ]; + const _TextStyle = class { + constructor(style) { + this.styleID = 0; + this.reset(); + deepCopyProperties(this, style, style); + } + clone() { + const clonedProperties = {}; + deepCopyProperties(clonedProperties, this, _TextStyle.defaultStyle); + return new _TextStyle(clonedProperties); + } + reset() { + deepCopyProperties(this, _TextStyle.defaultStyle, _TextStyle.defaultStyle); + } + get align() { + return this._align; + } + set align(align) { + if (this._align !== align) { + this._align = align; + this.styleID++; + } + } + get breakWords() { + return this._breakWords; + } + set breakWords(breakWords) { + if (this._breakWords !== breakWords) { + this._breakWords = breakWords; + this.styleID++; + } + } + get dropShadow() { + return this._dropShadow; + } + set dropShadow(dropShadow) { + if (this._dropShadow !== dropShadow) { + this._dropShadow = dropShadow; + this.styleID++; + } + } + get dropShadowAlpha() { + return this._dropShadowAlpha; + } + set dropShadowAlpha(dropShadowAlpha) { + if (this._dropShadowAlpha !== dropShadowAlpha) { + this._dropShadowAlpha = dropShadowAlpha; + this.styleID++; + } + } + get dropShadowAngle() { + return this._dropShadowAngle; + } + set dropShadowAngle(dropShadowAngle) { + if (this._dropShadowAngle !== dropShadowAngle) { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + } + get dropShadowBlur() { + return this._dropShadowBlur; + } + set dropShadowBlur(dropShadowBlur) { + if (this._dropShadowBlur !== dropShadowBlur) { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + } + get dropShadowColor() { + return this._dropShadowColor; + } + set dropShadowColor(dropShadowColor) { + const outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) { + this._dropShadowColor = outputColor; + this.styleID++; + } + } + get dropShadowDistance() { + return this._dropShadowDistance; + } + set dropShadowDistance(dropShadowDistance) { + if (this._dropShadowDistance !== dropShadowDistance) { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + } + get fill() { + return this._fill; + } + set fill(fill) { + const outputColor = getColor(fill); + if (this._fill !== outputColor) { + this._fill = outputColor; + this.styleID++; + } + } + get fillGradientType() { + return this._fillGradientType; + } + set fillGradientType(fillGradientType) { + if (this._fillGradientType !== fillGradientType) { + this._fillGradientType = fillGradientType; + this.styleID++; + } + } + get fillGradientStops() { + return this._fillGradientStops; + } + set fillGradientStops(fillGradientStops) { + if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) { + this._fillGradientStops = fillGradientStops; + this.styleID++; + } + } + get fontFamily() { + return this._fontFamily; + } + set fontFamily(fontFamily) { + if (this.fontFamily !== fontFamily) { + this._fontFamily = fontFamily; + this.styleID++; + } + } + get fontSize() { + return this._fontSize; + } + set fontSize(fontSize) { + if (this._fontSize !== fontSize) { + this._fontSize = fontSize; + this.styleID++; + } + } + get fontStyle() { + return this._fontStyle; + } + set fontStyle(fontStyle) { + if (this._fontStyle !== fontStyle) { + this._fontStyle = fontStyle; + this.styleID++; + } + } + get fontVariant() { + return this._fontVariant; + } + set fontVariant(fontVariant) { + if (this._fontVariant !== fontVariant) { + this._fontVariant = fontVariant; + this.styleID++; + } + } + get fontWeight() { + return this._fontWeight; + } + set fontWeight(fontWeight) { + if (this._fontWeight !== fontWeight) { + this._fontWeight = fontWeight; + this.styleID++; + } + } + get letterSpacing() { + return this._letterSpacing; + } + set letterSpacing(letterSpacing) { + if (this._letterSpacing !== letterSpacing) { + this._letterSpacing = letterSpacing; + this.styleID++; + } + } + get lineHeight() { + return this._lineHeight; + } + set lineHeight(lineHeight) { + if (this._lineHeight !== lineHeight) { + this._lineHeight = lineHeight; + this.styleID++; + } + } + get leading() { + return this._leading; + } + set leading(leading) { + if (this._leading !== leading) { + this._leading = leading; + this.styleID++; + } + } + get lineJoin() { + return this._lineJoin; + } + set lineJoin(lineJoin) { + if (this._lineJoin !== lineJoin) { + this._lineJoin = lineJoin; + this.styleID++; + } + } + get miterLimit() { + return this._miterLimit; + } + set miterLimit(miterLimit) { + if (this._miterLimit !== miterLimit) { + this._miterLimit = miterLimit; + this.styleID++; + } + } + get padding() { + return this._padding; + } + set padding(padding) { + if (this._padding !== padding) { + this._padding = padding; + this.styleID++; + } + } + get stroke() { + return this._stroke; + } + set stroke(stroke) { + const outputColor = getColor(stroke); + if (this._stroke !== outputColor) { + this._stroke = outputColor; + this.styleID++; + } + } + get strokeThickness() { + return this._strokeThickness; + } + set strokeThickness(strokeThickness) { + if (this._strokeThickness !== strokeThickness) { + this._strokeThickness = strokeThickness; + this.styleID++; + } + } + get textBaseline() { + return this._textBaseline; + } + set textBaseline(textBaseline) { + if (this._textBaseline !== textBaseline) { + this._textBaseline = textBaseline; + this.styleID++; + } + } + get trim() { + return this._trim; + } + set trim(trim) { + if (this._trim !== trim) { + this._trim = trim; + this.styleID++; + } + } + get whiteSpace() { + return this._whiteSpace; + } + set whiteSpace(whiteSpace) { + if (this._whiteSpace !== whiteSpace) { + this._whiteSpace = whiteSpace; + this.styleID++; + } + } + get wordWrap() { + return this._wordWrap; + } + set wordWrap(wordWrap) { + if (this._wordWrap !== wordWrap) { + this._wordWrap = wordWrap; + this.styleID++; + } + } + get wordWrapWidth() { + return this._wordWrapWidth; + } + set wordWrapWidth(wordWrapWidth) { + if (this._wordWrapWidth !== wordWrapWidth) { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + } + toFontString() { + const fontSizeString = typeof this.fontSize === "number" ? `${this.fontSize}px` : this.fontSize; + let fontFamilies = this.fontFamily; + if (!Array.isArray(this.fontFamily)) { + fontFamilies = this.fontFamily.split(","); + } + for (let i = fontFamilies.length - 1; i >= 0; i--) { + let fontFamily = fontFamilies[i].trim(); + if (!/([\"\'])[^\'\"]+\1/.test(fontFamily) && !genericFontFamilies.includes(fontFamily)) { + fontFamily = `"${fontFamily}"`; + } + fontFamilies[i] = fontFamily; + } + return `${this.fontStyle} ${this.fontVariant} ${this.fontWeight} ${fontSizeString} ${fontFamilies.join(",")}`; + } + }; + let TextStyle = _TextStyle; + TextStyle.defaultStyle = { + align: "left", + breakWords: false, + dropShadow: false, + dropShadowAlpha: 1, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: "black", + dropShadowDistance: 5, + fill: "black", + fillGradientType: TEXT_GRADIENT.LINEAR_VERTICAL, + fillGradientStops: [], + fontFamily: "Arial", + fontSize: 26, + fontStyle: "normal", + fontVariant: "normal", + fontWeight: "normal", + leading: 0, + letterSpacing: 0, + lineHeight: 0, + lineJoin: "miter", + miterLimit: 10, + padding: 0, + stroke: "black", + strokeThickness: 0, + textBaseline: "alphabetic", + trim: false, + whiteSpace: "pre", + wordWrap: false, + wordWrapWidth: 100 + }; + function getColor(color) { + const temp = Color.shared; + if (!Array.isArray(color)) { + return temp.setValue(color).toHex(); + } else { + return color.map((c) => temp.setValue(c).toHex()); + } + } + function areArraysEqual(array1, array2) { + if (!Array.isArray(array1) || !Array.isArray(array2)) { + return false; + } + if (array1.length !== array2.length) { + return false; + } + for (let i = 0; i < array1.length; ++i) { + if (array1[i] !== array2[i]) { + return false; + } + } + return true; + } + function deepCopyProperties(target, source, propertyObj) { + for (const prop in propertyObj) { + if (Array.isArray(source[prop])) { + target[prop] = source[prop].slice(); + } else { + target[prop] = source[prop]; + } + } + } + + const defaultDestroyOptions = { + texture: true, + children: false, + baseTexture: true + }; + const _Text = class extends Sprite { + constructor(text, style, canvas) { + let ownCanvas = false; + if (!canvas) { + canvas = settings.ADAPTER.createCanvas(); + ownCanvas = true; + } + canvas.width = 3; + canvas.height = 3; + const texture = Texture.from(canvas); + texture.orig = new Rectangle(); + texture.trim = new Rectangle(); + super(texture); + this._ownCanvas = ownCanvas; + this.canvas = canvas; + this.context = canvas.getContext("2d", { + willReadFrequently: true + }); + this._resolution = _Text.defaultResolution ?? settings.RESOLUTION; + this._autoResolution = _Text.defaultAutoResolution; + this._text = null; + this._style = null; + this._styleListener = null; + this._font = ""; + this.text = text; + this.style = style; + this.localStyleID = -1; + } + static get experimentalLetterSpacing() { + return TextMetrics.experimentalLetterSpacing; + } + static set experimentalLetterSpacing(value) { + deprecation$1("7.1.0", "Text.experimentalLetterSpacing is deprecated, use TextMetrics.experimentalLetterSpacing"); + TextMetrics.experimentalLetterSpacing = value; + } + updateText(respectDirty) { + const style = this._style; + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } + if (!this.dirty && respectDirty) { + return; + } + this._font = this._style.toFontString(); + const context = this.context; + const measured = TextMetrics.measureText(this._text || " ", this._style, this._style.wordWrap, this.canvas); + const width = measured.width; + const height = measured.height; + const lines = measured.lines; + const lineHeight = measured.lineHeight; + const lineWidths = measured.lineWidths; + const maxLineWidth = measured.maxLineWidth; + const fontProperties = measured.fontProperties; + this.canvas.width = Math.ceil(Math.ceil(Math.max(1, width) + style.padding * 2) * this._resolution); + this.canvas.height = Math.ceil(Math.ceil(Math.max(1, height) + style.padding * 2) * this._resolution); + context.scale(this._resolution, this._resolution); + context.clearRect(0, 0, this.canvas.width, this.canvas.height); + context.font = this._font; + context.lineWidth = style.strokeThickness; + context.textBaseline = style.textBaseline; + context.lineJoin = style.lineJoin; + context.miterLimit = style.miterLimit; + let linePositionX; + let linePositionY; + const passesCount = style.dropShadow ? 2 : 1; + for (let i = 0; i < passesCount; ++i) { + const isShadowPass = style.dropShadow && i === 0; + const dsOffsetText = isShadowPass ? Math.ceil(Math.max(1, height) + style.padding * 2) : 0; + const dsOffsetShadow = dsOffsetText * this._resolution; + if (isShadowPass) { + context.fillStyle = "black"; + context.strokeStyle = "black"; + const dropShadowColor = style.dropShadowColor; + const dropShadowBlur = style.dropShadowBlur * this._resolution; + const dropShadowDistance = style.dropShadowDistance * this._resolution; + context.shadowColor = Color.shared.setValue(dropShadowColor).setAlpha(style.dropShadowAlpha).toRgbaString(); + context.shadowBlur = dropShadowBlur; + context.shadowOffsetX = Math.cos(style.dropShadowAngle) * dropShadowDistance; + context.shadowOffsetY = Math.sin(style.dropShadowAngle) * dropShadowDistance + dsOffsetShadow; + } else { + context.fillStyle = this._generateFillStyle(style, lines, measured); + context.strokeStyle = style.stroke; + context.shadowColor = "black"; + context.shadowBlur = 0; + context.shadowOffsetX = 0; + context.shadowOffsetY = 0; + } + let linePositionYShift = (lineHeight - fontProperties.fontSize) / 2; + if (lineHeight - fontProperties.fontSize < 0) { + linePositionYShift = 0; + } + for (let i2 = 0; i2 < lines.length; i2++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + i2 * lineHeight + fontProperties.ascent + linePositionYShift; + if (style.align === "right") { + linePositionX += maxLineWidth - lineWidths[i2]; + } else if (style.align === "center") { + linePositionX += (maxLineWidth - lineWidths[i2]) / 2; + } + if (style.stroke && style.strokeThickness) { + this.drawLetterSpacing(lines[i2], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText, true); + } + if (style.fill) { + this.drawLetterSpacing(lines[i2], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText); + } + } + } + this.updateTexture(); + } + drawLetterSpacing(text, x, y, isStroke = false) { + const style = this._style; + const letterSpacing = style.letterSpacing; + let useExperimentalLetterSpacing = false; + if (TextMetrics.experimentalLetterSpacingSupported) { + if (TextMetrics.experimentalLetterSpacing) { + this.context.letterSpacing = `${letterSpacing}px`; + this.context.textLetterSpacing = `${letterSpacing}px`; + useExperimentalLetterSpacing = true; + } else { + this.context.letterSpacing = "0px"; + this.context.textLetterSpacing = "0px"; + } + } + if (letterSpacing === 0 || useExperimentalLetterSpacing) { + if (isStroke) { + this.context.strokeText(text, x, y); + } else { + this.context.fillText(text, x, y); + } + return; + } + let currentPosition = x; + const stringArray = TextMetrics.graphemeSegmenter(text); + let previousWidth = this.context.measureText(text).width; + let currentWidth = 0; + for (let i = 0; i < stringArray.length; ++i) { + const currentChar = stringArray[i]; + if (isStroke) { + this.context.strokeText(currentChar, currentPosition, y); + } else { + this.context.fillText(currentChar, currentPosition, y); + } + let textStr = ""; + for (let j = i + 1; j < stringArray.length; ++j) { + textStr += stringArray[j]; + } + currentWidth = this.context.measureText(textStr).width; + currentPosition += previousWidth - currentWidth + letterSpacing; + previousWidth = currentWidth; + } + } + updateTexture() { + const canvas = this.canvas; + if (this._style.trim) { + const trimmed = trimCanvas(canvas); + if (trimmed.data) { + canvas.width = trimmed.width; + canvas.height = trimmed.height; + this.context.putImageData(trimmed.data, 0, 0); + } + } + const texture = this._texture; + const style = this._style; + const padding = style.trim ? 0 : style.padding; + const baseTexture = texture.baseTexture; + texture.trim.width = texture._frame.width = canvas.width / this._resolution; + texture.trim.height = texture._frame.height = canvas.height / this._resolution; + texture.trim.x = -padding; + texture.trim.y = -padding; + texture.orig.width = texture._frame.width - padding * 2; + texture.orig.height = texture._frame.height - padding * 2; + this._onTextureUpdate(); + baseTexture.setRealSize(canvas.width, canvas.height, this._resolution); + texture.updateUvs(); + this.dirty = false; + } + _render(renderer) { + if (this._autoResolution && this._resolution !== renderer.resolution) { + this._resolution = renderer.resolution; + this.dirty = true; + } + this.updateText(true); + super._render(renderer); + } + updateTransform() { + this.updateText(true); + super.updateTransform(); + } + getBounds(skipUpdate, rect) { + this.updateText(true); + if (this._textureID === -1) { + skipUpdate = false; + } + return super.getBounds(skipUpdate, rect); + } + getLocalBounds(rect) { + this.updateText(true); + return super.getLocalBounds.call(this, rect); + } + _calculateBounds() { + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } + _generateFillStyle(style, lines, metrics) { + const fillStyle = style.fill; + if (!Array.isArray(fillStyle)) { + return fillStyle; + } else if (fillStyle.length === 1) { + return fillStyle[0]; + } + let gradient; + const dropShadowCorrection = style.dropShadow ? style.dropShadowDistance : 0; + const padding = style.padding || 0; + const width = this.canvas.width / this._resolution - dropShadowCorrection - padding * 2; + const height = this.canvas.height / this._resolution - dropShadowCorrection - padding * 2; + const fill = fillStyle.slice(); + const fillGradientStops = style.fillGradientStops.slice(); + if (!fillGradientStops.length) { + const lengthPlus1 = fill.length + 1; + for (let i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + fill.unshift(fillStyle[0]); + fillGradientStops.unshift(0); + fill.push(fillStyle[fillStyle.length - 1]); + fillGradientStops.push(1); + if (style.fillGradientType === TEXT_GRADIENT.LINEAR_VERTICAL) { + gradient = this.context.createLinearGradient(width / 2, padding, width / 2, height + padding); + const textHeight = metrics.fontProperties.fontSize + style.strokeThickness; + for (let i = 0; i < lines.length; i++) { + const lastLineBottom = metrics.lineHeight * (i - 1) + textHeight; + const thisLineTop = metrics.lineHeight * i; + let thisLineGradientStart = thisLineTop; + if (i > 0 && lastLineBottom > thisLineTop) { + thisLineGradientStart = (thisLineTop + lastLineBottom) / 2; + } + const thisLineBottom = thisLineTop + textHeight; + const nextLineTop = metrics.lineHeight * (i + 1); + let thisLineGradientEnd = thisLineBottom; + if (i + 1 < lines.length && nextLineTop < thisLineBottom) { + thisLineGradientEnd = (thisLineBottom + nextLineTop) / 2; + } + const gradStopLineHeight = (thisLineGradientEnd - thisLineGradientStart) / height; + for (let j = 0; j < fill.length; j++) { + let lineStop = 0; + if (typeof fillGradientStops[j] === "number") { + lineStop = fillGradientStops[j]; + } else { + lineStop = j / fill.length; + } + let globalStop = Math.min(1, Math.max(0, thisLineGradientStart / height + lineStop * gradStopLineHeight)); + globalStop = Number(globalStop.toFixed(5)); + gradient.addColorStop(globalStop, fill[j]); + } + } + } else { + gradient = this.context.createLinearGradient(padding, height / 2, width + padding, height / 2); + const totalIterations = fill.length + 1; + let currentIteration = 1; + for (let i = 0; i < fill.length; i++) { + let stop; + if (typeof fillGradientStops[i] === "number") { + stop = fillGradientStops[i]; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[i]); + currentIteration++; + } + } + return gradient; + } + destroy(options) { + if (typeof options === "boolean") { + options = { children: options }; + } + options = Object.assign({}, defaultDestroyOptions, options); + super.destroy(options); + if (this._ownCanvas) { + this.canvas.height = this.canvas.width = 0; + } + this.context = null; + this.canvas = null; + this._style = null; + } + get width() { + this.updateText(true); + return Math.abs(this.scale.x) * this._texture.orig.width; + } + set width(value) { + this.updateText(true); + const s = sign(this.scale.x) || 1; + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + get height() { + this.updateText(true); + return Math.abs(this.scale.y) * this._texture.orig.height; + } + set height(value) { + this.updateText(true); + const s = sign(this.scale.y) || 1; + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + get style() { + return this._style; + } + set style(style) { + style = style || {}; + if (style instanceof TextStyle) { + this._style = style; + } else { + this._style = new TextStyle(style); + } + this.localStyleID = -1; + this.dirty = true; + } + get text() { + return this._text; + } + set text(text) { + text = String(text === null || text === void 0 ? "" : text); + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + } + get resolution() { + return this._resolution; + } + set resolution(value) { + this._autoResolution = false; + if (this._resolution === value) { + return; + } + this._resolution = value; + this.dirty = true; + } + }; + let Text = _Text; + Text.defaultAutoResolution = true; + + Text.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this._autoResolution && this._resolution !== renderer.resolution) { + this._resolution = renderer.resolution; + this.dirty = true; + } + this.updateText(true); + Sprite.prototype._renderCanvas.call(this, renderer); + }; + + const _tempMatrix = new Matrix(); + DisplayObject.prototype._cacheAsBitmap = false; + DisplayObject.prototype._cacheData = null; + DisplayObject.prototype._cacheAsBitmapResolution = null; + DisplayObject.prototype._cacheAsBitmapMultisample = null; + class CacheData { + constructor() { + this.textureCacheId = null; + this.originalRender = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + this.originalUpdateTransform = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.originalContainsPoint = null; + this.sprite = null; + } + } + Object.defineProperties(DisplayObject.prototype, { + cacheAsBitmapResolution: { + get() { + return this._cacheAsBitmapResolution; + }, + set(resolution) { + if (resolution === this._cacheAsBitmapResolution) { + return; + } + this._cacheAsBitmapResolution = resolution; + if (this.cacheAsBitmap) { + this.cacheAsBitmap = false; + this.cacheAsBitmap = true; + } + } + }, + cacheAsBitmapMultisample: { + get() { + return this._cacheAsBitmapMultisample; + }, + set(multisample) { + if (multisample === this._cacheAsBitmapMultisample) { + return; + } + this._cacheAsBitmapMultisample = multisample; + if (this.cacheAsBitmap) { + this.cacheAsBitmap = false; + this.cacheAsBitmap = true; + } + } + }, + cacheAsBitmap: { + get() { + return this._cacheAsBitmap; + }, + set(value) { + if (this._cacheAsBitmap === value) { + return; + } + this._cacheAsBitmap = value; + let data; + if (value) { + if (!this._cacheData) { + this._cacheData = new CacheData(); + } + data = this._cacheData; + data.originalRender = this.render; + data.originalRenderCanvas = this.renderCanvas; + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this.calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + data.originalDestroy = this.destroy; + data.originalContainsPoint = this.containsPoint; + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + this.render = this._renderCached; + this.renderCanvas = this._renderCachedCanvas; + this.destroy = this._cacheAsBitmapDestroy; + } else { + data = this._cacheData; + if (data.sprite) { + this._destroyCachedDisplayObject(); + } + this.render = data.originalRender; + this.renderCanvas = data.originalRenderCanvas; + this.calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + this.destroy = data.originalDestroy; + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + } + } + }); + DisplayObject.prototype._renderCached = function _renderCached(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + this._initCachedDisplayObject(renderer); + this._cacheData.sprite.transform._worldID = this.transform._worldID; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._render(renderer); + }; + DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { + if (this._cacheData?.sprite) { + return; + } + const cacheAlpha = this.alpha; + this.alpha = 1; + renderer.batch.flush(); + const bounds = this.getLocalBounds(null, true).clone(); + if (this.filters?.length) { + const padding = this.filters[0].padding; + bounds.pad(padding); + } + bounds.ceil(settings.RESOLUTION); + const cachedRenderTexture = renderer.renderTexture.current; + const cachedSourceFrame = renderer.renderTexture.sourceFrame.clone(); + const cachedDestinationFrame = renderer.renderTexture.destinationFrame.clone(); + const cachedProjectionTransform = renderer.projection.transform; + const renderTexture = RenderTexture.create({ + width: bounds.width, + height: bounds.height, + resolution: this.cacheAsBitmapResolution || renderer.resolution, + multisample: this.cacheAsBitmapMultisample ?? renderer.multisample + }); + const textureCacheId = `cacheAsBitmap_${uid()}`; + this._cacheData.textureCacheId = textureCacheId; + BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId); + Texture.addToCache(renderTexture, textureCacheId); + const m = this.transform.localTransform.copyTo(_tempMatrix).invert().translate(-bounds.x, -bounds.y); + this.render = this._cacheData.originalRender; + renderer.render(this, { renderTexture, clear: true, transform: m, skipUpdateTransform: false }); + renderer.framebuffer.blit(); + renderer.projection.transform = cachedProjectionTransform; + renderer.renderTexture.bind(cachedRenderTexture, cachedSourceFrame, cachedDestinationFrame); + this.render = this._renderCached; + this.updateTransform = this.displayObjectUpdateTransform; + this.calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + this._mask = null; + this.filterArea = null; + this.alpha = cacheAlpha; + const cachedSprite = new Sprite(renderTexture); + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + this._cacheData.sprite = cachedSprite; + this.transform._parentID = -1; + if (!this.parent) { + this.enableTempParent(); + this.updateTransform(); + this.disableTempParent(null); + } else { + this.updateTransform(); + } + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); + }; + DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + this._initCachedDisplayObjectCanvas(renderer); + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderCanvas(renderer); + }; + DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { + if (this._cacheData?.sprite) { + return; + } + const bounds = this.getLocalBounds(null, true); + const cacheAlpha = this.alpha; + this.alpha = 1; + const cachedRenderTarget = renderer.canvasContext.activeContext; + const cachedProjectionTransform = renderer._projTransform; + bounds.ceil(settings.RESOLUTION); + const renderTexture = RenderTexture.create({ width: bounds.width, height: bounds.height }); + const textureCacheId = `cacheAsBitmap_${uid()}`; + this._cacheData.textureCacheId = textureCacheId; + BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId); + Texture.addToCache(renderTexture, textureCacheId); + const m = _tempMatrix; + this.transform.localTransform.copyTo(m); + m.invert(); + m.tx -= bounds.x; + m.ty -= bounds.y; + this.renderCanvas = this._cacheData.originalRenderCanvas; + renderer.render(this, { renderTexture, clear: true, transform: m, skipUpdateTransform: false }); + renderer.canvasContext.activeContext = cachedRenderTarget; + renderer._projTransform = cachedProjectionTransform; + this.renderCanvas = this._renderCachedCanvas; + this.updateTransform = this.displayObjectUpdateTransform; + this.calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + this._mask = null; + this.filterArea = null; + this.alpha = cacheAlpha; + const cachedSprite = new Sprite(renderTexture); + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + this._cacheData.sprite = cachedSprite; + this.transform._parentID = -1; + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this.updateTransform(); + } + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); + }; + DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { + this._bounds.clear(); + this._cacheData.sprite.transform._worldID = this.transform._worldID; + this._cacheData.sprite._calculateBounds(); + this._bounds.updateID = this._boundsID; + }; + DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { + return this._cacheData.sprite.getLocalBounds(null); + }; + DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; + BaseTexture.removeFromCache(this._cacheData.textureCacheId); + Texture.removeFromCache(this._cacheData.textureCacheId); + this._cacheData.textureCacheId = null; + }; + DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) { + this.cacheAsBitmap = false; + this.destroy(options); + }; + + DisplayObject.prototype.name = null; + Container.prototype.getChildByName = function getChildByName(name, deep) { + for (let i = 0, j = this.children.length; i < j; i++) { + if (this.children[i].name === name) { + return this.children[i]; + } + } + if (deep) { + for (let i = 0, j = this.children.length; i < j; i++) { + const child = this.children[i]; + if (!child.getChildByName) { + continue; + } + const target = child.getChildByName(name, true); + if (target) { + return target; + } + } + } + return null; + }; + + DisplayObject.prototype.getGlobalPosition = function getGlobalPosition(point = new Point(), skipUpdate = false) { + if (this.parent) { + this.parent.toGlobal(this.position, point, skipUpdate); + } else { + point.x = this.position.x; + point.y = this.position.y; + } + return point; + }; + + var fragment$5 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n"; + + class AlphaFilter extends Filter { + constructor(alpha = 1) { + super(defaultVertex, fragment$5, { uAlpha: 1 }); + this.alpha = alpha; + } + get alpha() { + return this.uniforms.uAlpha; + } + set alpha(value) { + this.uniforms.uAlpha = value; + } + } + + const GAUSSIAN_VALUES = { + 5: [0.153388, 0.221461, 0.250301], + 7: [0.071303, 0.131514, 0.189879, 0.214607], + 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11: [93e-4, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13: [2406e-6, 9255e-6, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15: [489e-6, 2403e-6, 9246e-6, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448] + }; + const fragTemplate = [ + "varying vec2 vBlurTexCoords[%size%];", + "uniform sampler2D uSampler;", + "void main(void)", + "{", + " gl_FragColor = vec4(0.0);", + " %blur%", + "}" + ].join("\n"); + function generateBlurFragSource(kernelSize) { + const kernel = GAUSSIAN_VALUES[kernelSize]; + const halfLength = kernel.length; + let fragSource = fragTemplate; + let blurLoop = ""; + const template = "gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;"; + let value; + for (let i = 0; i < kernelSize; i++) { + let blur = template.replace("%index%", i.toString()); + value = i; + if (i >= halfLength) { + value = kernelSize - i - 1; + } + blur = blur.replace("%value%", kernel[value].toString()); + blurLoop += blur; + blurLoop += "\n"; + } + fragSource = fragSource.replace("%blur%", blurLoop); + fragSource = fragSource.replace("%size%", kernelSize.toString()); + return fragSource; + } + + const vertTemplate = ` + attribute vec2 aVertexPosition; + + uniform mat3 projectionMatrix; + + uniform float strength; + + varying vec2 vBlurTexCoords[%size%]; + + uniform vec4 inputSize; + uniform vec4 outputFrame; + + vec4 filterVertexPosition( void ) + { + vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy; + + return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0); + } + + vec2 filterTextureCoord( void ) + { + return aVertexPosition * (outputFrame.zw * inputSize.zw); + } + + void main(void) + { + gl_Position = filterVertexPosition(); + + vec2 textureCoord = filterTextureCoord(); + %blur% + }`; + function generateBlurVertSource(kernelSize, x) { + const halfLength = Math.ceil(kernelSize / 2); + let vertSource = vertTemplate; + let blurLoop = ""; + let template; + if (x) { + template = "vBlurTexCoords[%index%] = textureCoord + vec2(%sampleIndex% * strength, 0.0);"; + } else { + template = "vBlurTexCoords[%index%] = textureCoord + vec2(0.0, %sampleIndex% * strength);"; + } + for (let i = 0; i < kernelSize; i++) { + let blur = template.replace("%index%", i.toString()); + blur = blur.replace("%sampleIndex%", `${i - (halfLength - 1)}.0`); + blurLoop += blur; + blurLoop += "\n"; + } + vertSource = vertSource.replace("%blur%", blurLoop); + vertSource = vertSource.replace("%size%", kernelSize.toString()); + return vertSource; + } + + class BlurFilterPass extends Filter { + constructor(horizontal, strength = 8, quality = 4, resolution = Filter.defaultResolution, kernelSize = 5) { + const vertSrc = generateBlurVertSource(kernelSize, horizontal); + const fragSrc = generateBlurFragSource(kernelSize); + super(vertSrc, fragSrc); + this.horizontal = horizontal; + this.resolution = resolution; + this._quality = 0; + this.quality = quality; + this.blur = strength; + } + apply(filterManager, input, output, clearMode) { + if (output) { + if (this.horizontal) { + this.uniforms.strength = 1 / output.width * (output.width / input.width); + } else { + this.uniforms.strength = 1 / output.height * (output.height / input.height); + } + } else { + if (this.horizontal) { + this.uniforms.strength = 1 / filterManager.renderer.width * (filterManager.renderer.width / input.width); + } else { + this.uniforms.strength = 1 / filterManager.renderer.height * (filterManager.renderer.height / input.height); + } + } + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clearMode); + } else { + const renderTarget = filterManager.getFilterTexture(); + const renderer = filterManager.renderer; + let flip = input; + let flop = renderTarget; + this.state.blend = false; + filterManager.applyFilter(this, flip, flop, CLEAR_MODES.CLEAR); + for (let i = 1; i < this.passes - 1; i++) { + filterManager.bindAndClear(flip, CLEAR_MODES.BLIT); + this.uniforms.uSampler = flop; + const temp = flop; + flop = flip; + flip = temp; + renderer.shader.bind(this); + renderer.geometry.draw(5); + } + this.state.blend = true; + filterManager.applyFilter(this, flop, output, clearMode); + filterManager.returnFilterTexture(renderTarget); + } + } + get blur() { + return this.strength; + } + set blur(value) { + this.padding = 1 + Math.abs(value) * 2; + this.strength = value; + } + get quality() { + return this._quality; + } + set quality(value) { + this._quality = value; + this.passes = value; + } + } + + class BlurFilter extends Filter { + constructor(strength = 8, quality = 4, resolution = Filter.defaultResolution, kernelSize = 5) { + super(); + this._repeatEdgePixels = false; + this.blurXFilter = new BlurFilterPass(true, strength, quality, resolution, kernelSize); + this.blurYFilter = new BlurFilterPass(false, strength, quality, resolution, kernelSize); + this.resolution = resolution; + this.quality = quality; + this.blur = strength; + this.repeatEdgePixels = false; + } + apply(filterManager, input, output, clearMode) { + const xStrength = Math.abs(this.blurXFilter.strength); + const yStrength = Math.abs(this.blurYFilter.strength); + if (xStrength && yStrength) { + const renderTarget = filterManager.getFilterTexture(); + this.blurXFilter.apply(filterManager, input, renderTarget, CLEAR_MODES.CLEAR); + this.blurYFilter.apply(filterManager, renderTarget, output, clearMode); + filterManager.returnFilterTexture(renderTarget); + } else if (yStrength) { + this.blurYFilter.apply(filterManager, input, output, clearMode); + } else { + this.blurXFilter.apply(filterManager, input, output, clearMode); + } + } + updatePadding() { + if (this._repeatEdgePixels) { + this.padding = 0; + } else { + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + } + get blur() { + return this.blurXFilter.blur; + } + set blur(value) { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.updatePadding(); + } + get quality() { + return this.blurXFilter.quality; + } + set quality(value) { + this.blurXFilter.quality = this.blurYFilter.quality = value; + } + get blurX() { + return this.blurXFilter.blur; + } + set blurX(value) { + this.blurXFilter.blur = value; + this.updatePadding(); + } + get blurY() { + return this.blurYFilter.blur; + } + set blurY(value) { + this.blurYFilter.blur = value; + this.updatePadding(); + } + get blendMode() { + return this.blurYFilter.blendMode; + } + set blendMode(value) { + this.blurYFilter.blendMode = value; + } + get repeatEdgePixels() { + return this._repeatEdgePixels; + } + set repeatEdgePixels(value) { + this._repeatEdgePixels = value; + this.updatePadding(); + } + } + + var fragment$4 = "varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n"; + + class ColorMatrixFilter extends Filter { + constructor() { + const uniforms = { + m: new Float32Array([ + 1, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 1, + 0 + ]), + uAlpha: 1 + }; + super(defaultFilterVertex, fragment$4, uniforms); + this.alpha = 1; + } + _loadMatrix(matrix, multiply = false) { + let newMatrix = matrix; + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } + this.uniforms.m = newMatrix; + } + _multiply(out, a, b) { + out[0] = a[0] * b[0] + a[1] * b[5] + a[2] * b[10] + a[3] * b[15]; + out[1] = a[0] * b[1] + a[1] * b[6] + a[2] * b[11] + a[3] * b[16]; + out[2] = a[0] * b[2] + a[1] * b[7] + a[2] * b[12] + a[3] * b[17]; + out[3] = a[0] * b[3] + a[1] * b[8] + a[2] * b[13] + a[3] * b[18]; + out[4] = a[0] * b[4] + a[1] * b[9] + a[2] * b[14] + a[3] * b[19] + a[4]; + out[5] = a[5] * b[0] + a[6] * b[5] + a[7] * b[10] + a[8] * b[15]; + out[6] = a[5] * b[1] + a[6] * b[6] + a[7] * b[11] + a[8] * b[16]; + out[7] = a[5] * b[2] + a[6] * b[7] + a[7] * b[12] + a[8] * b[17]; + out[8] = a[5] * b[3] + a[6] * b[8] + a[7] * b[13] + a[8] * b[18]; + out[9] = a[5] * b[4] + a[6] * b[9] + a[7] * b[14] + a[8] * b[19] + a[9]; + out[10] = a[10] * b[0] + a[11] * b[5] + a[12] * b[10] + a[13] * b[15]; + out[11] = a[10] * b[1] + a[11] * b[6] + a[12] * b[11] + a[13] * b[16]; + out[12] = a[10] * b[2] + a[11] * b[7] + a[12] * b[12] + a[13] * b[17]; + out[13] = a[10] * b[3] + a[11] * b[8] + a[12] * b[13] + a[13] * b[18]; + out[14] = a[10] * b[4] + a[11] * b[9] + a[12] * b[14] + a[13] * b[19] + a[14]; + out[15] = a[15] * b[0] + a[16] * b[5] + a[17] * b[10] + a[18] * b[15]; + out[16] = a[15] * b[1] + a[16] * b[6] + a[17] * b[11] + a[18] * b[16]; + out[17] = a[15] * b[2] + a[16] * b[7] + a[17] * b[12] + a[18] * b[17]; + out[18] = a[15] * b[3] + a[16] * b[8] + a[17] * b[13] + a[18] * b[18]; + out[19] = a[15] * b[4] + a[16] * b[9] + a[17] * b[14] + a[18] * b[19] + a[19]; + return out; + } + _colorMatrix(matrix) { + const m = new Float32Array(matrix); + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + return m; + } + brightness(b, multiply) { + const matrix = [ + b, + 0, + 0, + 0, + 0, + 0, + b, + 0, + 0, + 0, + 0, + 0, + b, + 0, + 0, + 0, + 0, + 0, + 1, + 0 + ]; + this._loadMatrix(matrix, multiply); + } + tint(color, multiply) { + const [r, g, b] = Color.shared.setValue(color).toArray(); + const matrix = [ + r, + 0, + 0, + 0, + 0, + 0, + g, + 0, + 0, + 0, + 0, + 0, + b, + 0, + 0, + 0, + 0, + 0, + 1, + 0 + ]; + this._loadMatrix(matrix, multiply); + } + greyscale(scale, multiply) { + const matrix = [ + scale, + scale, + scale, + 0, + 0, + scale, + scale, + scale, + 0, + 0, + scale, + scale, + scale, + 0, + 0, + 0, + 0, + 0, + 1, + 0 + ]; + this._loadMatrix(matrix, multiply); + } + blackAndWhite(multiply) { + const matrix = [ + 0.3, + 0.6, + 0.1, + 0, + 0, + 0.3, + 0.6, + 0.1, + 0, + 0, + 0.3, + 0.6, + 0.1, + 0, + 0, + 0, + 0, + 0, + 1, + 0 + ]; + this._loadMatrix(matrix, multiply); + } + hue(rotation, multiply) { + rotation = (rotation || 0) / 180 * Math.PI; + const cosR = Math.cos(rotation); + const sinR = Math.sin(rotation); + const sqrt = Math.sqrt; + const w = 1 / 3; + const sqrW = sqrt(w); + const a00 = cosR + (1 - cosR) * w; + const a01 = w * (1 - cosR) - sqrW * sinR; + const a02 = w * (1 - cosR) + sqrW * sinR; + const a10 = w * (1 - cosR) + sqrW * sinR; + const a11 = cosR + w * (1 - cosR); + const a12 = w * (1 - cosR) - sqrW * sinR; + const a20 = w * (1 - cosR) - sqrW * sinR; + const a21 = w * (1 - cosR) + sqrW * sinR; + const a22 = cosR + w * (1 - cosR); + const matrix = [ + a00, + a01, + a02, + 0, + 0, + a10, + a11, + a12, + 0, + 0, + a20, + a21, + a22, + 0, + 0, + 0, + 0, + 0, + 1, + 0 + ]; + this._loadMatrix(matrix, multiply); + } + contrast(amount, multiply) { + const v = (amount || 0) + 1; + const o = -0.5 * (v - 1); + const matrix = [ + v, + 0, + 0, + 0, + o, + 0, + v, + 0, + 0, + o, + 0, + 0, + v, + 0, + o, + 0, + 0, + 0, + 1, + 0 + ]; + this._loadMatrix(matrix, multiply); + } + saturate(amount = 0, multiply) { + const x = amount * 2 / 3 + 1; + const y = (x - 1) * -0.5; + const matrix = [ + x, + y, + y, + 0, + 0, + y, + x, + y, + 0, + 0, + y, + y, + x, + 0, + 0, + 0, + 0, + 0, + 1, + 0 + ]; + this._loadMatrix(matrix, multiply); + } + desaturate() { + this.saturate(-1); + } + negative(multiply) { + const matrix = [ + -1, + 0, + 0, + 1, + 0, + 0, + -1, + 0, + 1, + 0, + 0, + 0, + -1, + 1, + 0, + 0, + 0, + 0, + 1, + 0 + ]; + this._loadMatrix(matrix, multiply); + } + sepia(multiply) { + const matrix = [ + 0.393, + 0.7689999, + 0.18899999, + 0, + 0, + 0.349, + 0.6859999, + 0.16799999, + 0, + 0, + 0.272, + 0.5339999, + 0.13099999, + 0, + 0, + 0, + 0, + 0, + 1, + 0 + ]; + this._loadMatrix(matrix, multiply); + } + technicolor(multiply) { + const matrix = [ + 1.9125277891456083, + -0.8545344976951645, + -0.09155508482755585, + 0, + 11.793603434377337, + -0.3087833385928097, + 1.7658908555458428, + -0.10601743074722245, + 0, + -70.35205161461398, + -0.231103377548616, + -0.7501899197440212, + 1.847597816108189, + 0, + 30.950940869491138, + 0, + 0, + 0, + 1, + 0 + ]; + this._loadMatrix(matrix, multiply); + } + polaroid(multiply) { + const matrix = [ + 1.438, + -0.062, + -0.062, + 0, + 0, + -0.122, + 1.378, + -0.122, + 0, + 0, + -0.016, + -0.016, + 1.483, + 0, + 0, + 0, + 0, + 0, + 1, + 0 + ]; + this._loadMatrix(matrix, multiply); + } + toBGR(multiply) { + const matrix = [ + 0, + 0, + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0 + ]; + this._loadMatrix(matrix, multiply); + } + kodachrome(multiply) { + const matrix = [ + 1.1285582396593525, + -0.3967382283601348, + -0.03992559172921793, + 0, + 63.72958762196502, + -0.16404339962244616, + 1.0835251566291304, + -0.05498805115633132, + 0, + 24.732407896706203, + -0.16786010706155763, + -0.5603416277695248, + 1.6014850761964943, + 0, + 35.62982807460946, + 0, + 0, + 0, + 1, + 0 + ]; + this._loadMatrix(matrix, multiply); + } + browni(multiply) { + const matrix = [ + 0.5997023498159715, + 0.34553243048391263, + -0.2708298674538042, + 0, + 47.43192855600873, + -0.037703249837783157, + 0.8609577587992641, + 0.15059552388459913, + 0, + -36.96841498319127, + 0.24113635128153335, + -0.07441037908422492, + 0.44972182064877153, + 0, + -7.562075277591283, + 0, + 0, + 0, + 1, + 0 + ]; + this._loadMatrix(matrix, multiply); + } + vintage(multiply) { + const matrix = [ + 0.6279345635605994, + 0.3202183420819367, + -0.03965408211312453, + 0, + 9.651285835294123, + 0.02578397704808868, + 0.6441188644374771, + 0.03259127616149294, + 0, + 7.462829176470591, + 0.0466055556782719, + -0.0851232987247891, + 0.5241648018700465, + 0, + 5.159190588235296, + 0, + 0, + 0, + 1, + 0 + ]; + this._loadMatrix(matrix, multiply); + } + colorTone(desaturation, toned, lightColor, darkColor, multiply) { + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 16770432; + darkColor = darkColor || 3375104; + const temp = Color.shared; + const [lR, lG, lB] = temp.setValue(lightColor).toArray(); + const [dR, dG, dB] = temp.setValue(darkColor).toArray(); + const matrix = [ + 0.3, + 0.59, + 0.11, + 0, + 0, + lR, + lG, + lB, + desaturation, + 0, + dR, + dG, + dB, + toned, + 0, + lR - dR, + lG - dG, + lB - dB, + 0, + 0 + ]; + this._loadMatrix(matrix, multiply); + } + night(intensity, multiply) { + intensity = intensity || 0.1; + const matrix = [ + intensity * -2, + -intensity, + 0, + 0, + 0, + -intensity, + 0, + intensity, + 0, + 0, + 0, + intensity, + intensity * 2, + 0, + 0, + 0, + 0, + 0, + 1, + 0 + ]; + this._loadMatrix(matrix, multiply); + } + predator(amount, multiply) { + const matrix = [ + 11.224130630493164 * amount, + -4.794486999511719 * amount, + -2.8746118545532227 * amount, + 0 * amount, + 0.40342438220977783 * amount, + -3.6330697536468506 * amount, + 9.193157196044922 * amount, + -2.951810836791992 * amount, + 0 * amount, + -1.316135048866272 * amount, + -3.2184197902679443 * amount, + -4.2375030517578125 * amount, + 7.476448059082031 * amount, + 0 * amount, + 0.8044459223747253 * amount, + 0, + 0, + 0, + 1, + 0 + ]; + this._loadMatrix(matrix, multiply); + } + lsd(multiply) { + const matrix = [ + 2, + -0.4, + 0.5, + 0, + 0, + -0.5, + 2, + -0.4, + 0, + 0, + -0.4, + -0.5, + 3, + 0, + 0, + 0, + 0, + 0, + 1, + 0 + ]; + this._loadMatrix(matrix, multiply); + } + reset() { + const matrix = [ + 1, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 1, + 0 + ]; + this._loadMatrix(matrix, false); + } + get matrix() { + return this.uniforms.m; + } + set matrix(value) { + this.uniforms.m = value; + } + get alpha() { + return this.uniforms.uAlpha; + } + set alpha(value) { + this.uniforms.uAlpha = value; + } + } + ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + + var fragment$3 = "varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\nuniform mat2 rotation;\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform highp vec4 inputSize;\nuniform vec4 inputClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy = scale * inputSize.zw * (rotation * map.xy);\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), inputClamp.xy, inputClamp.zw));\n}\n"; + + var vertex$2 = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n\tgl_Position = filterVertexPosition();\n\tvTextureCoord = filterTextureCoord();\n\tvFilterCoord = ( filterMatrix * vec3( vTextureCoord, 1.0) ).xy;\n}\n"; + + class DisplacementFilter extends Filter { + constructor(sprite, scale) { + const maskMatrix = new Matrix(); + sprite.renderable = false; + super(vertex$2, fragment$3, { + mapSampler: sprite._texture, + filterMatrix: maskMatrix, + scale: { x: 1, y: 1 }, + rotation: new Float32Array([1, 0, 0, 1]) + }); + this.maskSprite = sprite; + this.maskMatrix = maskMatrix; + if (scale === null || scale === void 0) { + scale = 20; + } + this.scale = new Point(scale, scale); + } + apply(filterManager, input, output, clearMode) { + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x; + this.uniforms.scale.y = this.scale.y; + const wt = this.maskSprite.worldTransform; + const lenX = Math.sqrt(wt.a * wt.a + wt.b * wt.b); + const lenY = Math.sqrt(wt.c * wt.c + wt.d * wt.d); + if (lenX !== 0 && lenY !== 0) { + this.uniforms.rotation[0] = wt.a / lenX; + this.uniforms.rotation[1] = wt.b / lenX; + this.uniforms.rotation[2] = wt.c / lenY; + this.uniforms.rotation[3] = wt.d / lenY; + } + filterManager.applyFilter(this, input, output, clearMode); + } + get map() { + return this.uniforms.mapSampler; + } + set map(value) { + this.uniforms.mapSampler = value; + } + } + + var fragment$2 = "varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\nuniform sampler2D uSampler;\nuniform highp vec4 inputSize;\n\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it's\n unsupported by WebGL.\n\n --\n\n From:\n https://github.com/mitsuhiko/webgl-meincraft\n\n Copyright (c) 2011 by Armin Ronacher.\n\n Some rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n\n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 inverseVP,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n\n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n\n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec4 color;\n\n color = fxaa(uSampler, vFragCoord, inputSize.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n"; + + var vertex$1 = "\nattribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvoid texcoords(vec2 fragCoord, vec2 inverseVP,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = filterVertexPosition();\n\n vFragCoord = aVertexPosition * outputFrame.zw;\n\n texcoords(vFragCoord, inputSize.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}\n"; + + class FXAAFilter extends Filter { + constructor() { + super(vertex$1, fragment$2); + } + } + + var fragment$1 = "precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n"; + + class NoiseFilter extends Filter { + constructor(noise = 0.5, seed = Math.random()) { + super(defaultFilterVertex, fragment$1, { + uNoise: 0, + uSeed: 0 + }); + this.noise = noise; + this.seed = seed; + } + get noise() { + return this.uniforms.uNoise; + } + set noise(value) { + this.uniforms.uNoise = value; + } + get seed() { + return this.uniforms.uSeed; + } + set seed(value) { + this.uniforms.uSeed = value; + } + } + + const filters = { + AlphaFilter, + BlurFilter, + BlurFilterPass, + ColorMatrixFilter, + DisplacementFilter, + FXAAFilter, + NoiseFilter + }; + Object.entries(filters).forEach(([key, FilterClass]) => { + Object.defineProperty(filters, key, { + get() { + deprecation$1("7.1.0", `filters.${key} has moved to ${key}`); + return FilterClass; + } + }); + }); + + class EventsTickerClass { + constructor() { + this.interactionFrequency = 10; + this._deltaTime = 0; + this._didMove = false; + this.tickerAdded = false; + this._pauseUpdate = true; + } + init(events) { + this.removeTickerListener(); + this.events = events; + this.interactionFrequency = 10; + this._deltaTime = 0; + this._didMove = false; + this.tickerAdded = false; + this._pauseUpdate = true; + } + get pauseUpdate() { + return this._pauseUpdate; + } + set pauseUpdate(paused) { + this._pauseUpdate = paused; + } + addTickerListener() { + if (this.tickerAdded || !this.domElement) { + return; + } + Ticker.system.add(this.tickerUpdate, this, UPDATE_PRIORITY.INTERACTION); + this.tickerAdded = true; + } + removeTickerListener() { + if (!this.tickerAdded) { + return; + } + Ticker.system.remove(this.tickerUpdate, this); + this.tickerAdded = false; + } + pointerMoved() { + this._didMove = true; + } + update() { + if (!this.domElement || this._pauseUpdate) { + return; + } + if (this._didMove) { + this._didMove = false; + return; + } + const rootPointerEvent = this.events["rootPointerEvent"]; + if (this.events.supportsTouchEvents && rootPointerEvent.pointerType === "touch") { + return; + } + globalThis.document.dispatchEvent(new PointerEvent("pointermove", { + clientX: rootPointerEvent.clientX, + clientY: rootPointerEvent.clientY + })); + } + tickerUpdate(deltaTime) { + this._deltaTime += deltaTime; + if (this._deltaTime < this.interactionFrequency) { + return; + } + this._deltaTime = 0; + this.update(); + } + } + const EventsTicker = new EventsTickerClass(); + + class FederatedEvent { + constructor(manager) { + this.bubbles = true; + this.cancelBubble = true; + this.cancelable = false; + this.composed = false; + this.defaultPrevented = false; + this.eventPhase = FederatedEvent.prototype.NONE; + this.propagationStopped = false; + this.propagationImmediatelyStopped = false; + this.layer = new Point(); + this.page = new Point(); + this.NONE = 0; + this.CAPTURING_PHASE = 1; + this.AT_TARGET = 2; + this.BUBBLING_PHASE = 3; + this.manager = manager; + } + get layerX() { + return this.layer.x; + } + get layerY() { + return this.layer.y; + } + get pageX() { + return this.page.x; + } + get pageY() { + return this.page.y; + } + get data() { + return this; + } + composedPath() { + if (this.manager && (!this.path || this.path[this.path.length - 1] !== this.target)) { + this.path = this.target ? this.manager.propagationPath(this.target) : []; + } + return this.path; + } + initEvent(_type, _bubbles, _cancelable) { + throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API."); + } + initUIEvent(_typeArg, _bubblesArg, _cancelableArg, _viewArg, _detailArg) { + throw new Error("initUIEvent() is a legacy DOM API. It is not implemented in the Federated Events API."); + } + preventDefault() { + if (this.nativeEvent instanceof Event && this.nativeEvent.cancelable) { + this.nativeEvent.preventDefault(); + } + this.defaultPrevented = true; + } + stopImmediatePropagation() { + this.propagationImmediatelyStopped = true; + } + stopPropagation() { + this.propagationStopped = true; + } + } + + class FederatedMouseEvent extends FederatedEvent { + constructor() { + super(...arguments); + this.client = new Point(); + this.movement = new Point(); + this.offset = new Point(); + this.global = new Point(); + this.screen = new Point(); + } + get clientX() { + return this.client.x; + } + get clientY() { + return this.client.y; + } + get x() { + return this.clientX; + } + get y() { + return this.clientY; + } + get movementX() { + return this.movement.x; + } + get movementY() { + return this.movement.y; + } + get offsetX() { + return this.offset.x; + } + get offsetY() { + return this.offset.y; + } + get globalX() { + return this.global.x; + } + get globalY() { + return this.global.y; + } + get screenX() { + return this.screen.x; + } + get screenY() { + return this.screen.y; + } + getLocalPosition(displayObject, point, globalPos) { + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); + } + getModifierState(key) { + return "getModifierState" in this.nativeEvent && this.nativeEvent.getModifierState(key); + } + initMouseEvent(_typeArg, _canBubbleArg, _cancelableArg, _viewArg, _detailArg, _screenXArg, _screenYArg, _clientXArg, _clientYArg, _ctrlKeyArg, _altKeyArg, _shiftKeyArg, _metaKeyArg, _buttonArg, _relatedTargetArg) { + throw new Error("Method not implemented."); + } + } + + class FederatedPointerEvent extends FederatedMouseEvent { + constructor() { + super(...arguments); + this.width = 0; + this.height = 0; + this.isPrimary = false; + } + getCoalescedEvents() { + if (this.type === "pointermove" || this.type === "mousemove" || this.type === "touchmove") { + return [this]; + } + return []; + } + getPredictedEvents() { + throw new Error("getPredictedEvents is not supported!"); + } + } + + class FederatedWheelEvent extends FederatedMouseEvent { + constructor() { + super(...arguments); + this.DOM_DELTA_PIXEL = 0; + this.DOM_DELTA_LINE = 1; + this.DOM_DELTA_PAGE = 2; + } + } + FederatedWheelEvent.DOM_DELTA_PIXEL = 0; + FederatedWheelEvent.DOM_DELTA_LINE = 1; + FederatedWheelEvent.DOM_DELTA_PAGE = 2; + + const PROPAGATION_LIMIT = 2048; + const tempHitLocation = new Point(); + const tempLocalMapping = new Point(); + class EventBoundary { + constructor(rootTarget) { + this.dispatch = new eventemitter3(); + this.moveOnAll = false; + this.enableGlobalMoveEvents = true; + this.mappingState = { + trackingData: {} + }; + this.eventPool = /* @__PURE__ */ new Map(); + this._allInteractiveElements = []; + this._hitElements = []; + this._isPointerMoveEvent = false; + this.rootTarget = rootTarget; + this.hitPruneFn = this.hitPruneFn.bind(this); + this.hitTestFn = this.hitTestFn.bind(this); + this.mapPointerDown = this.mapPointerDown.bind(this); + this.mapPointerMove = this.mapPointerMove.bind(this); + this.mapPointerOut = this.mapPointerOut.bind(this); + this.mapPointerOver = this.mapPointerOver.bind(this); + this.mapPointerUp = this.mapPointerUp.bind(this); + this.mapPointerUpOutside = this.mapPointerUpOutside.bind(this); + this.mapWheel = this.mapWheel.bind(this); + this.mappingTable = {}; + this.addEventMapping("pointerdown", this.mapPointerDown); + this.addEventMapping("pointermove", this.mapPointerMove); + this.addEventMapping("pointerout", this.mapPointerOut); + this.addEventMapping("pointerleave", this.mapPointerOut); + this.addEventMapping("pointerover", this.mapPointerOver); + this.addEventMapping("pointerup", this.mapPointerUp); + this.addEventMapping("pointerupoutside", this.mapPointerUpOutside); + this.addEventMapping("wheel", this.mapWheel); + } + addEventMapping(type, fn) { + if (!this.mappingTable[type]) { + this.mappingTable[type] = []; + } + this.mappingTable[type].push({ + fn, + priority: 0 + }); + this.mappingTable[type].sort((a, b) => a.priority - b.priority); + } + dispatchEvent(e, type) { + e.propagationStopped = false; + e.propagationImmediatelyStopped = false; + this.propagate(e, type); + this.dispatch.emit(type || e.type, e); + } + mapEvent(e) { + if (!this.rootTarget) { + return; + } + const mappers = this.mappingTable[e.type]; + if (mappers) { + for (let i = 0, j = mappers.length; i < j; i++) { + mappers[i].fn(e); + } + } else { + console.warn(`[EventBoundary]: Event mapping not defined for ${e.type}`); + } + } + hitTest(x, y) { + EventsTicker.pauseUpdate = true; + const useMove = this._isPointerMoveEvent && this.enableGlobalMoveEvents; + const fn = useMove ? "hitTestMoveRecursive" : "hitTestRecursive"; + const invertedPath = this[fn](this.rootTarget, this.rootTarget.eventMode, tempHitLocation.set(x, y), this.hitTestFn, this.hitPruneFn); + return invertedPath && invertedPath[0]; + } + propagate(e, type) { + if (!e.target) { + return; + } + const composedPath = e.composedPath(); + e.eventPhase = e.CAPTURING_PHASE; + for (let i = 0, j = composedPath.length - 1; i < j; i++) { + e.currentTarget = composedPath[i]; + this.notifyTarget(e, type); + if (e.propagationStopped || e.propagationImmediatelyStopped) + return; + } + e.eventPhase = e.AT_TARGET; + e.currentTarget = e.target; + this.notifyTarget(e, type); + if (e.propagationStopped || e.propagationImmediatelyStopped) + return; + e.eventPhase = e.BUBBLING_PHASE; + for (let i = composedPath.length - 2; i >= 0; i--) { + e.currentTarget = composedPath[i]; + this.notifyTarget(e, type); + if (e.propagationStopped || e.propagationImmediatelyStopped) + return; + } + } + all(e, type, targets = this._allInteractiveElements) { + if (targets.length === 0) + return; + e.eventPhase = e.BUBBLING_PHASE; + const events = Array.isArray(type) ? type : [type]; + for (let i = targets.length - 1; i >= 0; i--) { + events.forEach((event) => { + e.currentTarget = targets[i]; + this.notifyTarget(e, event); + }); + } + } + propagationPath(target) { + const propagationPath = [target]; + for (let i = 0; i < PROPAGATION_LIMIT && target !== this.rootTarget; i++) { + if (!target.parent) { + throw new Error("Cannot find propagation path to disconnected target"); + } + propagationPath.push(target.parent); + target = target.parent; + } + propagationPath.reverse(); + return propagationPath; + } + hitTestMoveRecursive(currentTarget, eventMode, location, testFn, pruneFn, ignore = false) { + let shouldReturn = false; + if (this._interactivePrune(currentTarget)) + return null; + if (currentTarget.eventMode === "dynamic" || eventMode === "dynamic") { + EventsTicker.pauseUpdate = false; + } + if (currentTarget.interactiveChildren && currentTarget.children) { + const children = currentTarget.children; + for (let i = children.length - 1; i >= 0; i--) { + const child = children[i]; + const nestedHit = this.hitTestMoveRecursive(child, this._isInteractive(eventMode) ? eventMode : child.eventMode, location, testFn, pruneFn, ignore || pruneFn(currentTarget, location)); + if (nestedHit) { + if (nestedHit.length > 0 && !nestedHit[nestedHit.length - 1].parent) { + continue; + } + const isInteractive = currentTarget.isInteractive(); + if (nestedHit.length > 0 || isInteractive) { + if (isInteractive) + this._allInteractiveElements.push(currentTarget); + nestedHit.push(currentTarget); + } + if (this._hitElements.length === 0) + this._hitElements = nestedHit; + shouldReturn = true; + } + } + } + const isInteractiveMode = this._isInteractive(eventMode); + const isInteractiveTarget = currentTarget.isInteractive(); + if (isInteractiveTarget && isInteractiveTarget) + this._allInteractiveElements.push(currentTarget); + if (ignore || this._hitElements.length > 0) + return null; + if (shouldReturn) + return this._hitElements; + if (isInteractiveMode && (!pruneFn(currentTarget, location) && testFn(currentTarget, location))) { + return isInteractiveTarget ? [currentTarget] : []; + } + return null; + } + hitTestRecursive(currentTarget, eventMode, location, testFn, pruneFn) { + if (this._interactivePrune(currentTarget) || pruneFn(currentTarget, location)) { + return null; + } + if (currentTarget.eventMode === "dynamic" || eventMode === "dynamic") { + EventsTicker.pauseUpdate = false; + } + if (currentTarget.interactiveChildren && currentTarget.children) { + const children = currentTarget.children; + for (let i = children.length - 1; i >= 0; i--) { + const child = children[i]; + const nestedHit = this.hitTestRecursive(child, this._isInteractive(eventMode) ? eventMode : child.eventMode, location, testFn, pruneFn); + if (nestedHit) { + if (nestedHit.length > 0 && !nestedHit[nestedHit.length - 1].parent) { + continue; + } + const isInteractive = currentTarget.isInteractive(); + if (nestedHit.length > 0 || isInteractive) + nestedHit.push(currentTarget); + return nestedHit; + } + } + } + const isInteractiveMode = this._isInteractive(eventMode); + const isInteractiveTarget = currentTarget.isInteractive(); + if (isInteractiveMode && testFn(currentTarget, location)) { + return isInteractiveTarget ? [currentTarget] : []; + } + return null; + } + _isInteractive(int) { + return int === "static" || int === "dynamic"; + } + _interactivePrune(displayObject) { + if (!displayObject || displayObject.isMask || !displayObject.visible || !displayObject.renderable) { + return true; + } + if (displayObject.eventMode === "none") { + return true; + } + if (displayObject.eventMode === "passive" && !displayObject.interactiveChildren) { + return true; + } + if (displayObject.isMask) { + return true; + } + return false; + } + hitPruneFn(displayObject, location) { + if (displayObject.hitArea) { + displayObject.worldTransform.applyInverse(location, tempLocalMapping); + if (!displayObject.hitArea.contains(tempLocalMapping.x, tempLocalMapping.y)) { + return true; + } + } + if (displayObject._mask) { + const maskObject = displayObject._mask.isMaskData ? displayObject._mask.maskObject : displayObject._mask; + if (maskObject && !maskObject.containsPoint?.(location)) { + return true; + } + } + return false; + } + hitTestFn(displayObject, location) { + if (displayObject.eventMode === "passive") { + return false; + } + if (displayObject.hitArea) { + return true; + } + if (displayObject.containsPoint) { + return displayObject.containsPoint(location); + } + return false; + } + notifyTarget(e, type) { + type = type ?? e.type; + const handlerKey = `on${type}`; + e.currentTarget[handlerKey]?.(e); + const key = e.eventPhase === e.CAPTURING_PHASE || e.eventPhase === e.AT_TARGET ? `${type}capture` : type; + this.notifyListeners(e, key); + if (e.eventPhase === e.AT_TARGET) { + this.notifyListeners(e, type); + } + } + mapPointerDown(from) { + if (!(from instanceof FederatedPointerEvent)) { + console.warn("EventBoundary cannot map a non-pointer event as a pointer event"); + return; + } + const e = this.createPointerEvent(from); + this.dispatchEvent(e, "pointerdown"); + if (e.pointerType === "touch") { + this.dispatchEvent(e, "touchstart"); + } else if (e.pointerType === "mouse" || e.pointerType === "pen") { + const isRightButton = e.button === 2; + this.dispatchEvent(e, isRightButton ? "rightdown" : "mousedown"); + } + const trackingData = this.trackingData(from.pointerId); + trackingData.pressTargetsByButton[from.button] = e.composedPath(); + this.freeEvent(e); + } + mapPointerMove(from) { + if (!(from instanceof FederatedPointerEvent)) { + console.warn("EventBoundary cannot map a non-pointer event as a pointer event"); + return; + } + this._allInteractiveElements.length = 0; + this._hitElements.length = 0; + this._isPointerMoveEvent = true; + const e = this.createPointerEvent(from); + this._isPointerMoveEvent = false; + const isMouse = e.pointerType === "mouse" || e.pointerType === "pen"; + const trackingData = this.trackingData(from.pointerId); + const outTarget = this.findMountedTarget(trackingData.overTargets); + if (trackingData.overTargets?.length > 0 && outTarget !== e.target) { + const outType = from.type === "mousemove" ? "mouseout" : "pointerout"; + const outEvent = this.createPointerEvent(from, outType, outTarget); + this.dispatchEvent(outEvent, "pointerout"); + if (isMouse) + this.dispatchEvent(outEvent, "mouseout"); + if (!e.composedPath().includes(outTarget)) { + const leaveEvent = this.createPointerEvent(from, "pointerleave", outTarget); + leaveEvent.eventPhase = leaveEvent.AT_TARGET; + while (leaveEvent.target && !e.composedPath().includes(leaveEvent.target)) { + leaveEvent.currentTarget = leaveEvent.target; + this.notifyTarget(leaveEvent); + if (isMouse) + this.notifyTarget(leaveEvent, "mouseleave"); + leaveEvent.target = leaveEvent.target.parent; + } + this.freeEvent(leaveEvent); + } + this.freeEvent(outEvent); + } + if (outTarget !== e.target) { + const overType = from.type === "mousemove" ? "mouseover" : "pointerover"; + const overEvent = this.clonePointerEvent(e, overType); + this.dispatchEvent(overEvent, "pointerover"); + if (isMouse) + this.dispatchEvent(overEvent, "mouseover"); + let overTargetAncestor = outTarget?.parent; + while (overTargetAncestor && overTargetAncestor !== this.rootTarget.parent) { + if (overTargetAncestor === e.target) + break; + overTargetAncestor = overTargetAncestor.parent; + } + const didPointerEnter = !overTargetAncestor || overTargetAncestor === this.rootTarget.parent; + if (didPointerEnter) { + const enterEvent = this.clonePointerEvent(e, "pointerenter"); + enterEvent.eventPhase = enterEvent.AT_TARGET; + while (enterEvent.target && enterEvent.target !== outTarget && enterEvent.target !== this.rootTarget.parent) { + enterEvent.currentTarget = enterEvent.target; + this.notifyTarget(enterEvent); + if (isMouse) + this.notifyTarget(enterEvent, "mouseenter"); + enterEvent.target = enterEvent.target.parent; + } + this.freeEvent(enterEvent); + } + this.freeEvent(overEvent); + } + const allMethods = []; + const allowGlobalPointerEvents = this.enableGlobalMoveEvents ?? true; + this.moveOnAll ? allMethods.push("pointermove") : this.dispatchEvent(e, "pointermove"); + allowGlobalPointerEvents && allMethods.push("globalpointermove"); + if (e.pointerType === "touch") { + this.moveOnAll ? allMethods.splice(1, 0, "touchmove") : this.dispatchEvent(e, "touchmove"); + allowGlobalPointerEvents && allMethods.push("globaltouchmove"); + } + if (isMouse) { + this.moveOnAll ? allMethods.splice(1, 0, "mousemove") : this.dispatchEvent(e, "mousemove"); + allowGlobalPointerEvents && allMethods.push("globalmousemove"); + this.cursor = e.target?.cursor; + } + if (allMethods.length > 0) { + this.all(e, allMethods); + } + this._allInteractiveElements.length = 0; + this._hitElements.length = 0; + trackingData.overTargets = e.composedPath(); + this.freeEvent(e); + } + mapPointerOver(from) { + if (!(from instanceof FederatedPointerEvent)) { + console.warn("EventBoundary cannot map a non-pointer event as a pointer event"); + return; + } + const trackingData = this.trackingData(from.pointerId); + const e = this.createPointerEvent(from); + const isMouse = e.pointerType === "mouse" || e.pointerType === "pen"; + this.dispatchEvent(e, "pointerover"); + if (isMouse) + this.dispatchEvent(e, "mouseover"); + if (e.pointerType === "mouse") + this.cursor = e.target?.cursor; + const enterEvent = this.clonePointerEvent(e, "pointerenter"); + enterEvent.eventPhase = enterEvent.AT_TARGET; + while (enterEvent.target && enterEvent.target !== this.rootTarget.parent) { + enterEvent.currentTarget = enterEvent.target; + this.notifyTarget(enterEvent); + if (isMouse) + this.notifyTarget(enterEvent, "mouseenter"); + enterEvent.target = enterEvent.target.parent; + } + trackingData.overTargets = e.composedPath(); + this.freeEvent(e); + this.freeEvent(enterEvent); + } + mapPointerOut(from) { + if (!(from instanceof FederatedPointerEvent)) { + console.warn("EventBoundary cannot map a non-pointer event as a pointer event"); + return; + } + const trackingData = this.trackingData(from.pointerId); + if (trackingData.overTargets) { + const isMouse = from.pointerType === "mouse" || from.pointerType === "pen"; + const outTarget = this.findMountedTarget(trackingData.overTargets); + const outEvent = this.createPointerEvent(from, "pointerout", outTarget); + this.dispatchEvent(outEvent); + if (isMouse) + this.dispatchEvent(outEvent, "mouseout"); + const leaveEvent = this.createPointerEvent(from, "pointerleave", outTarget); + leaveEvent.eventPhase = leaveEvent.AT_TARGET; + while (leaveEvent.target && leaveEvent.target !== this.rootTarget.parent) { + leaveEvent.currentTarget = leaveEvent.target; + this.notifyTarget(leaveEvent); + if (isMouse) + this.notifyTarget(leaveEvent, "mouseleave"); + leaveEvent.target = leaveEvent.target.parent; + } + trackingData.overTargets = null; + this.freeEvent(outEvent); + this.freeEvent(leaveEvent); + } + this.cursor = null; + } + mapPointerUp(from) { + if (!(from instanceof FederatedPointerEvent)) { + console.warn("EventBoundary cannot map a non-pointer event as a pointer event"); + return; + } + const now = performance.now(); + const e = this.createPointerEvent(from); + this.dispatchEvent(e, "pointerup"); + if (e.pointerType === "touch") { + this.dispatchEvent(e, "touchend"); + } else if (e.pointerType === "mouse" || e.pointerType === "pen") { + const isRightButton = e.button === 2; + this.dispatchEvent(e, isRightButton ? "rightup" : "mouseup"); + } + const trackingData = this.trackingData(from.pointerId); + const pressTarget = this.findMountedTarget(trackingData.pressTargetsByButton[from.button]); + let clickTarget = pressTarget; + if (pressTarget && !e.composedPath().includes(pressTarget)) { + let currentTarget = pressTarget; + while (currentTarget && !e.composedPath().includes(currentTarget)) { + e.currentTarget = currentTarget; + this.notifyTarget(e, "pointerupoutside"); + if (e.pointerType === "touch") { + this.notifyTarget(e, "touchendoutside"); + } else if (e.pointerType === "mouse" || e.pointerType === "pen") { + const isRightButton = e.button === 2; + this.notifyTarget(e, isRightButton ? "rightupoutside" : "mouseupoutside"); + } + currentTarget = currentTarget.parent; + } + delete trackingData.pressTargetsByButton[from.button]; + clickTarget = currentTarget; + } + if (clickTarget) { + const clickEvent = this.clonePointerEvent(e, "click"); + clickEvent.target = clickTarget; + clickEvent.path = null; + if (!trackingData.clicksByButton[from.button]) { + trackingData.clicksByButton[from.button] = { + clickCount: 0, + target: clickEvent.target, + timeStamp: now + }; + } + const clickHistory = trackingData.clicksByButton[from.button]; + if (clickHistory.target === clickEvent.target && now - clickHistory.timeStamp < 200) { + ++clickHistory.clickCount; + } else { + clickHistory.clickCount = 1; + } + clickHistory.target = clickEvent.target; + clickHistory.timeStamp = now; + clickEvent.detail = clickHistory.clickCount; + if (clickEvent.pointerType === "mouse") { + const isRightButton = clickEvent.button === 2; + this.dispatchEvent(clickEvent, isRightButton ? "rightclick" : "click"); + } else if (clickEvent.pointerType === "touch") { + this.dispatchEvent(clickEvent, "tap"); + } + this.dispatchEvent(clickEvent, "pointertap"); + this.freeEvent(clickEvent); + } + this.freeEvent(e); + } + mapPointerUpOutside(from) { + if (!(from instanceof FederatedPointerEvent)) { + console.warn("EventBoundary cannot map a non-pointer event as a pointer event"); + return; + } + const trackingData = this.trackingData(from.pointerId); + const pressTarget = this.findMountedTarget(trackingData.pressTargetsByButton[from.button]); + const e = this.createPointerEvent(from); + if (pressTarget) { + let currentTarget = pressTarget; + while (currentTarget) { + e.currentTarget = currentTarget; + this.notifyTarget(e, "pointerupoutside"); + if (e.pointerType === "touch") { + this.notifyTarget(e, "touchendoutside"); + } else if (e.pointerType === "mouse" || e.pointerType === "pen") { + this.notifyTarget(e, e.button === 2 ? "rightupoutside" : "mouseupoutside"); + } + currentTarget = currentTarget.parent; + } + delete trackingData.pressTargetsByButton[from.button]; + } + this.freeEvent(e); + } + mapWheel(from) { + if (!(from instanceof FederatedWheelEvent)) { + console.warn("EventBoundary cannot map a non-wheel event as a wheel event"); + return; + } + const wheelEvent = this.createWheelEvent(from); + this.dispatchEvent(wheelEvent); + this.freeEvent(wheelEvent); + } + findMountedTarget(propagationPath) { + if (!propagationPath) { + return null; + } + let currentTarget = propagationPath[0]; + for (let i = 1; i < propagationPath.length; i++) { + if (propagationPath[i].parent === currentTarget) { + currentTarget = propagationPath[i]; + } else { + break; + } + } + return currentTarget; + } + createPointerEvent(from, type, target) { + const event = this.allocateEvent(FederatedPointerEvent); + this.copyPointerData(from, event); + this.copyMouseData(from, event); + this.copyData(from, event); + event.nativeEvent = from.nativeEvent; + event.originalEvent = from; + event.target = target ?? this.hitTest(event.global.x, event.global.y) ?? this._hitElements[0]; + if (typeof type === "string") { + event.type = type; + } + return event; + } + createWheelEvent(from) { + const event = this.allocateEvent(FederatedWheelEvent); + this.copyWheelData(from, event); + this.copyMouseData(from, event); + this.copyData(from, event); + event.nativeEvent = from.nativeEvent; + event.originalEvent = from; + event.target = this.hitTest(event.global.x, event.global.y); + return event; + } + clonePointerEvent(from, type) { + const event = this.allocateEvent(FederatedPointerEvent); + event.nativeEvent = from.nativeEvent; + event.originalEvent = from.originalEvent; + this.copyPointerData(from, event); + this.copyMouseData(from, event); + this.copyData(from, event); + event.target = from.target; + event.path = from.composedPath().slice(); + event.type = type ?? event.type; + return event; + } + copyWheelData(from, to) { + to.deltaMode = from.deltaMode; + to.deltaX = from.deltaX; + to.deltaY = from.deltaY; + to.deltaZ = from.deltaZ; + } + copyPointerData(from, to) { + if (!(from instanceof FederatedPointerEvent && to instanceof FederatedPointerEvent)) + return; + to.pointerId = from.pointerId; + to.width = from.width; + to.height = from.height; + to.isPrimary = from.isPrimary; + to.pointerType = from.pointerType; + to.pressure = from.pressure; + to.tangentialPressure = from.tangentialPressure; + to.tiltX = from.tiltX; + to.tiltY = from.tiltY; + to.twist = from.twist; + } + copyMouseData(from, to) { + if (!(from instanceof FederatedMouseEvent && to instanceof FederatedMouseEvent)) + return; + to.altKey = from.altKey; + to.button = from.button; + to.buttons = from.buttons; + to.client.copyFrom(from.client); + to.ctrlKey = from.ctrlKey; + to.metaKey = from.metaKey; + to.movement.copyFrom(from.movement); + to.screen.copyFrom(from.screen); + to.shiftKey = from.shiftKey; + to.global.copyFrom(from.global); + } + copyData(from, to) { + to.isTrusted = from.isTrusted; + to.srcElement = from.srcElement; + to.timeStamp = performance.now(); + to.type = from.type; + to.detail = from.detail; + to.view = from.view; + to.which = from.which; + to.layer.copyFrom(from.layer); + to.page.copyFrom(from.page); + } + trackingData(id) { + if (!this.mappingState.trackingData[id]) { + this.mappingState.trackingData[id] = { + pressTargetsByButton: {}, + clicksByButton: {}, + overTarget: null + }; + } + return this.mappingState.trackingData[id]; + } + allocateEvent(constructor) { + if (!this.eventPool.has(constructor)) { + this.eventPool.set(constructor, []); + } + const event = this.eventPool.get(constructor).pop() || new constructor(this); + event.eventPhase = event.NONE; + event.currentTarget = null; + event.path = null; + event.target = null; + return event; + } + freeEvent(event) { + if (event.manager !== this) + throw new Error("It is illegal to free an event not managed by this EventBoundary!"); + const constructor = event.constructor; + if (!this.eventPool.has(constructor)) { + this.eventPool.set(constructor, []); + } + this.eventPool.get(constructor).push(event); + } + notifyListeners(e, type) { + const listeners = e.currentTarget._events[type]; + if (!listeners) + return; + if (!e.currentTarget.isInteractive()) + return; + if ("fn" in listeners) { + if (listeners.once) + e.currentTarget.removeListener(type, listeners.fn, void 0, true); + listeners.fn.call(listeners.context, e); + } else { + for (let i = 0, j = listeners.length; i < j && !e.propagationImmediatelyStopped; i++) { + if (listeners[i].once) + e.currentTarget.removeListener(type, listeners[i].fn, void 0, true); + listeners[i].fn.call(listeners[i].context, e); + } + } + } + } + + const MOUSE_POINTER_ID = 1; + const TOUCH_TO_POINTER = { + touchstart: "pointerdown", + touchend: "pointerup", + touchendoutside: "pointerupoutside", + touchmove: "pointermove", + touchcancel: "pointercancel" + }; + const _EventSystem = class { + constructor(renderer) { + this.supportsTouchEvents = "ontouchstart" in globalThis; + this.supportsPointerEvents = !!globalThis.PointerEvent; + this.domElement = null; + this.resolution = 1; + this.renderer = renderer; + this.rootBoundary = new EventBoundary(null); + EventsTicker.init(this); + this.autoPreventDefault = true; + this.eventsAdded = false; + this.rootPointerEvent = new FederatedPointerEvent(null); + this.rootWheelEvent = new FederatedWheelEvent(null); + this.cursorStyles = { + default: "inherit", + pointer: "pointer" + }; + this.features = new Proxy({ ..._EventSystem.defaultEventFeatures }, { + set: (target, key, value) => { + if (key === "globalMove") { + this.rootBoundary.enableGlobalMoveEvents = value; + } + target[key] = value; + return true; + } + }); + this.onPointerDown = this.onPointerDown.bind(this); + this.onPointerMove = this.onPointerMove.bind(this); + this.onPointerUp = this.onPointerUp.bind(this); + this.onPointerOverOut = this.onPointerOverOut.bind(this); + this.onWheel = this.onWheel.bind(this); + } + static get defaultEventMode() { + return this._defaultEventMode; + } + init(options) { + const { view, resolution } = this.renderer; + this.setTargetElement(view); + this.resolution = resolution; + _EventSystem._defaultEventMode = options.eventMode ?? "auto"; + Object.assign(this.features, options.eventFeatures ?? {}); + this.rootBoundary.enableGlobalMoveEvents = this.features.globalMove; + } + resolutionChange(resolution) { + this.resolution = resolution; + } + destroy() { + this.setTargetElement(null); + this.renderer = null; + } + setCursor(mode) { + mode = mode || "default"; + let applyStyles = true; + if (globalThis.OffscreenCanvas && this.domElement instanceof OffscreenCanvas) { + applyStyles = false; + } + if (this.currentCursor === mode) { + return; + } + this.currentCursor = mode; + const style = this.cursorStyles[mode]; + if (style) { + switch (typeof style) { + case "string": + if (applyStyles) { + this.domElement.style.cursor = style; + } + break; + case "function": + style(mode); + break; + case "object": + if (applyStyles) { + Object.assign(this.domElement.style, style); + } + break; + } + } else if (applyStyles && typeof mode === "string" && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) { + this.domElement.style.cursor = mode; + } + } + get pointer() { + return this.rootPointerEvent; + } + onPointerDown(nativeEvent) { + if (!this.features.click) + return; + this.rootBoundary.rootTarget = this.renderer.lastObjectRendered; + if (this.supportsTouchEvents && nativeEvent.pointerType === "touch") + return; + const events = this.normalizeToPointerData(nativeEvent); + if (this.autoPreventDefault && events[0].isNormalized) { + const cancelable = nativeEvent.cancelable || !("cancelable" in nativeEvent); + if (cancelable) { + nativeEvent.preventDefault(); + } + } + for (let i = 0, j = events.length; i < j; i++) { + const nativeEvent2 = events[i]; + const federatedEvent = this.bootstrapEvent(this.rootPointerEvent, nativeEvent2); + this.rootBoundary.mapEvent(federatedEvent); + } + this.setCursor(this.rootBoundary.cursor); + } + onPointerMove(nativeEvent) { + if (!this.features.move) + return; + this.rootBoundary.rootTarget = this.renderer.lastObjectRendered; + if (this.supportsTouchEvents && nativeEvent.pointerType === "touch") + return; + EventsTicker.pointerMoved(); + const normalizedEvents = this.normalizeToPointerData(nativeEvent); + for (let i = 0, j = normalizedEvents.length; i < j; i++) { + const event = this.bootstrapEvent(this.rootPointerEvent, normalizedEvents[i]); + this.rootBoundary.mapEvent(event); + } + this.setCursor(this.rootBoundary.cursor); + } + onPointerUp(nativeEvent) { + if (!this.features.click) + return; + this.rootBoundary.rootTarget = this.renderer.lastObjectRendered; + if (this.supportsTouchEvents && nativeEvent.pointerType === "touch") + return; + let target = nativeEvent.target; + if (nativeEvent.composedPath && nativeEvent.composedPath().length > 0) { + target = nativeEvent.composedPath()[0]; + } + const outside = target !== this.domElement ? "outside" : ""; + const normalizedEvents = this.normalizeToPointerData(nativeEvent); + for (let i = 0, j = normalizedEvents.length; i < j; i++) { + const event = this.bootstrapEvent(this.rootPointerEvent, normalizedEvents[i]); + event.type += outside; + this.rootBoundary.mapEvent(event); + } + this.setCursor(this.rootBoundary.cursor); + } + onPointerOverOut(nativeEvent) { + if (!this.features.click) + return; + this.rootBoundary.rootTarget = this.renderer.lastObjectRendered; + if (this.supportsTouchEvents && nativeEvent.pointerType === "touch") + return; + const normalizedEvents = this.normalizeToPointerData(nativeEvent); + for (let i = 0, j = normalizedEvents.length; i < j; i++) { + const event = this.bootstrapEvent(this.rootPointerEvent, normalizedEvents[i]); + this.rootBoundary.mapEvent(event); + } + this.setCursor(this.rootBoundary.cursor); + } + onWheel(nativeEvent) { + if (!this.features.wheel) + return; + const wheelEvent = this.normalizeWheelEvent(nativeEvent); + this.rootBoundary.rootTarget = this.renderer.lastObjectRendered; + this.rootBoundary.mapEvent(wheelEvent); + } + setTargetElement(element) { + this.removeEvents(); + this.domElement = element; + EventsTicker.domElement = element; + this.addEvents(); + } + addEvents() { + if (this.eventsAdded || !this.domElement) { + return; + } + EventsTicker.addTickerListener(); + const style = this.domElement.style; + if (style) { + if (globalThis.navigator.msPointerEnabled) { + style.msContentZooming = "none"; + style.msTouchAction = "none"; + } else if (this.supportsPointerEvents) { + style.touchAction = "none"; + } + } + if (this.supportsPointerEvents) { + globalThis.document.addEventListener("pointermove", this.onPointerMove, true); + this.domElement.addEventListener("pointerdown", this.onPointerDown, true); + this.domElement.addEventListener("pointerleave", this.onPointerOverOut, true); + this.domElement.addEventListener("pointerover", this.onPointerOverOut, true); + globalThis.addEventListener("pointerup", this.onPointerUp, true); + } else { + globalThis.document.addEventListener("mousemove", this.onPointerMove, true); + this.domElement.addEventListener("mousedown", this.onPointerDown, true); + this.domElement.addEventListener("mouseout", this.onPointerOverOut, true); + this.domElement.addEventListener("mouseover", this.onPointerOverOut, true); + globalThis.addEventListener("mouseup", this.onPointerUp, true); + } + if (this.supportsTouchEvents) { + this.domElement.addEventListener("touchstart", this.onPointerDown, true); + this.domElement.addEventListener("touchend", this.onPointerUp, true); + this.domElement.addEventListener("touchmove", this.onPointerMove, true); + } + this.domElement.addEventListener("wheel", this.onWheel, { + passive: true, + capture: true + }); + this.eventsAdded = true; + } + removeEvents() { + if (!this.eventsAdded || !this.domElement) { + return; + } + EventsTicker.removeTickerListener(); + const style = this.domElement.style; + if (globalThis.navigator.msPointerEnabled) { + style.msContentZooming = ""; + style.msTouchAction = ""; + } else if (this.supportsPointerEvents) { + style.touchAction = ""; + } + if (this.supportsPointerEvents) { + globalThis.document.removeEventListener("pointermove", this.onPointerMove, true); + this.domElement.removeEventListener("pointerdown", this.onPointerDown, true); + this.domElement.removeEventListener("pointerleave", this.onPointerOverOut, true); + this.domElement.removeEventListener("pointerover", this.onPointerOverOut, true); + globalThis.removeEventListener("pointerup", this.onPointerUp, true); + } else { + globalThis.document.removeEventListener("mousemove", this.onPointerMove, true); + this.domElement.removeEventListener("mousedown", this.onPointerDown, true); + this.domElement.removeEventListener("mouseout", this.onPointerOverOut, true); + this.domElement.removeEventListener("mouseover", this.onPointerOverOut, true); + globalThis.removeEventListener("mouseup", this.onPointerUp, true); + } + if (this.supportsTouchEvents) { + this.domElement.removeEventListener("touchstart", this.onPointerDown, true); + this.domElement.removeEventListener("touchend", this.onPointerUp, true); + this.domElement.removeEventListener("touchmove", this.onPointerMove, true); + } + this.domElement.removeEventListener("wheel", this.onWheel, true); + this.domElement = null; + this.eventsAdded = false; + } + mapPositionToPoint(point, x, y) { + let rect; + if (!this.domElement.parentElement) { + rect = { + x: 0, + y: 0, + width: this.domElement.width, + height: this.domElement.height, + left: 0, + top: 0 + }; + } else { + rect = this.domElement.getBoundingClientRect(); + } + const resolutionMultiplier = 1 / this.resolution; + point.x = (x - rect.left) * (this.domElement.width / rect.width) * resolutionMultiplier; + point.y = (y - rect.top) * (this.domElement.height / rect.height) * resolutionMultiplier; + } + normalizeToPointerData(event) { + const normalizedEvents = []; + if (this.supportsTouchEvents && event instanceof TouchEvent) { + for (let i = 0, li = event.changedTouches.length; i < li; i++) { + const touch = event.changedTouches[i]; + if (typeof touch.button === "undefined") + touch.button = 0; + if (typeof touch.buttons === "undefined") + touch.buttons = 1; + if (typeof touch.isPrimary === "undefined") { + touch.isPrimary = event.touches.length === 1 && event.type === "touchstart"; + } + if (typeof touch.width === "undefined") + touch.width = touch.radiusX || 1; + if (typeof touch.height === "undefined") + touch.height = touch.radiusY || 1; + if (typeof touch.tiltX === "undefined") + touch.tiltX = 0; + if (typeof touch.tiltY === "undefined") + touch.tiltY = 0; + if (typeof touch.pointerType === "undefined") + touch.pointerType = "touch"; + if (typeof touch.pointerId === "undefined") + touch.pointerId = touch.identifier || 0; + if (typeof touch.pressure === "undefined") + touch.pressure = touch.force || 0.5; + if (typeof touch.twist === "undefined") + touch.twist = 0; + if (typeof touch.tangentialPressure === "undefined") + touch.tangentialPressure = 0; + if (typeof touch.layerX === "undefined") + touch.layerX = touch.offsetX = touch.clientX; + if (typeof touch.layerY === "undefined") + touch.layerY = touch.offsetY = touch.clientY; + touch.isNormalized = true; + touch.type = event.type; + normalizedEvents.push(touch); + } + } else if (!globalThis.MouseEvent || event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof globalThis.PointerEvent))) { + const tempEvent = event; + if (typeof tempEvent.isPrimary === "undefined") + tempEvent.isPrimary = true; + if (typeof tempEvent.width === "undefined") + tempEvent.width = 1; + if (typeof tempEvent.height === "undefined") + tempEvent.height = 1; + if (typeof tempEvent.tiltX === "undefined") + tempEvent.tiltX = 0; + if (typeof tempEvent.tiltY === "undefined") + tempEvent.tiltY = 0; + if (typeof tempEvent.pointerType === "undefined") + tempEvent.pointerType = "mouse"; + if (typeof tempEvent.pointerId === "undefined") + tempEvent.pointerId = MOUSE_POINTER_ID; + if (typeof tempEvent.pressure === "undefined") + tempEvent.pressure = 0.5; + if (typeof tempEvent.twist === "undefined") + tempEvent.twist = 0; + if (typeof tempEvent.tangentialPressure === "undefined") + tempEvent.tangentialPressure = 0; + tempEvent.isNormalized = true; + normalizedEvents.push(tempEvent); + } else { + normalizedEvents.push(event); + } + return normalizedEvents; + } + normalizeWheelEvent(nativeEvent) { + const event = this.rootWheelEvent; + this.transferMouseData(event, nativeEvent); + event.deltaX = nativeEvent.deltaX; + event.deltaY = nativeEvent.deltaY; + event.deltaZ = nativeEvent.deltaZ; + event.deltaMode = nativeEvent.deltaMode; + this.mapPositionToPoint(event.screen, nativeEvent.clientX, nativeEvent.clientY); + event.global.copyFrom(event.screen); + event.offset.copyFrom(event.screen); + event.nativeEvent = nativeEvent; + event.type = nativeEvent.type; + return event; + } + bootstrapEvent(event, nativeEvent) { + event.originalEvent = null; + event.nativeEvent = nativeEvent; + event.pointerId = nativeEvent.pointerId; + event.width = nativeEvent.width; + event.height = nativeEvent.height; + event.isPrimary = nativeEvent.isPrimary; + event.pointerType = nativeEvent.pointerType; + event.pressure = nativeEvent.pressure; + event.tangentialPressure = nativeEvent.tangentialPressure; + event.tiltX = nativeEvent.tiltX; + event.tiltY = nativeEvent.tiltY; + event.twist = nativeEvent.twist; + this.transferMouseData(event, nativeEvent); + this.mapPositionToPoint(event.screen, nativeEvent.clientX, nativeEvent.clientY); + event.global.copyFrom(event.screen); + event.offset.copyFrom(event.screen); + event.isTrusted = nativeEvent.isTrusted; + if (event.type === "pointerleave") { + event.type = "pointerout"; + } + if (event.type.startsWith("mouse")) { + event.type = event.type.replace("mouse", "pointer"); + } + if (event.type.startsWith("touch")) { + event.type = TOUCH_TO_POINTER[event.type] || event.type; + } + return event; + } + transferMouseData(event, nativeEvent) { + event.isTrusted = nativeEvent.isTrusted; + event.srcElement = nativeEvent.srcElement; + event.timeStamp = performance.now(); + event.type = nativeEvent.type; + event.altKey = nativeEvent.altKey; + event.button = nativeEvent.button; + event.buttons = nativeEvent.buttons; + event.client.x = nativeEvent.clientX; + event.client.y = nativeEvent.clientY; + event.ctrlKey = nativeEvent.ctrlKey; + event.metaKey = nativeEvent.metaKey; + event.movement.x = nativeEvent.movementX; + event.movement.y = nativeEvent.movementY; + event.page.x = nativeEvent.pageX; + event.page.y = nativeEvent.pageY; + event.relatedTarget = null; + event.shiftKey = nativeEvent.shiftKey; + } + }; + let EventSystem = _EventSystem; + EventSystem.extension = { + name: "events", + type: [ + ExtensionType.RendererSystem, + ExtensionType.CanvasRendererSystem + ] + }; + EventSystem.defaultEventFeatures = { + move: true, + globalMove: true, + click: true, + wheel: true + }; + extensions$1.add(EventSystem); + + function convertEventModeToInteractiveMode(mode) { + return mode === "dynamic" || mode === "static"; + } + const FederatedDisplayObject = { + onclick: null, + onmousedown: null, + onmouseenter: null, + onmouseleave: null, + onmousemove: null, + onglobalmousemove: null, + onmouseout: null, + onmouseover: null, + onmouseup: null, + onmouseupoutside: null, + onpointercancel: null, + onpointerdown: null, + onpointerenter: null, + onpointerleave: null, + onpointermove: null, + onglobalpointermove: null, + onpointerout: null, + onpointerover: null, + onpointertap: null, + onpointerup: null, + onpointerupoutside: null, + onrightclick: null, + onrightdown: null, + onrightup: null, + onrightupoutside: null, + ontap: null, + ontouchcancel: null, + ontouchend: null, + ontouchendoutside: null, + ontouchmove: null, + onglobaltouchmove: null, + ontouchstart: null, + onwheel: null, + _internalInteractive: void 0, + get interactive() { + return this._internalInteractive ?? convertEventModeToInteractiveMode(EventSystem.defaultEventMode); + }, + set interactive(value) { + deprecation$1("7.2.0", `Setting interactive is deprecated, use eventMode = 'none'/'passive'/'auto'/'static'/'dynamic' instead.`); + this._internalInteractive = value; + this.eventMode = value ? "static" : "auto"; + }, + _internalEventMode: void 0, + get eventMode() { + return this._internalEventMode ?? EventSystem.defaultEventMode; + }, + set eventMode(value) { + this._internalInteractive = convertEventModeToInteractiveMode(value); + this._internalEventMode = value; + }, + isInteractive() { + return this.eventMode === "static" || this.eventMode === "dynamic"; + }, + interactiveChildren: true, + hitArea: null, + addEventListener(type, listener, options) { + const capture = typeof options === "boolean" && options || typeof options === "object" && options.capture; + const context = typeof listener === "function" ? void 0 : listener; + type = capture ? `${type}capture` : type; + listener = typeof listener === "function" ? listener : listener.handleEvent; + this.on(type, listener, context); + }, + removeEventListener(type, listener, options) { + const capture = typeof options === "boolean" && options || typeof options === "object" && options.capture; + const context = typeof listener === "function" ? void 0 : listener; + type = capture ? `${type}capture` : type; + listener = typeof listener === "function" ? listener : listener.handleEvent; + this.off(type, listener, context); + }, + dispatchEvent(e) { + if (!(e instanceof FederatedEvent)) { + throw new Error("DisplayObject cannot propagate events outside of the Federated Events API"); + } + e.defaultPrevented = false; + e.path = null; + e.target = this; + e.manager.dispatchEvent(e); + return !e.defaultPrevented; + } + }; + DisplayObject.mixin(FederatedDisplayObject); + + const accessibleTarget = { + accessible: false, + accessibleTitle: null, + accessibleHint: null, + tabIndex: 0, + _accessibleActive: false, + _accessibleDiv: null, + accessibleType: "button", + accessiblePointerEvents: "auto", + accessibleChildren: true, + renderId: -1 + }; + + DisplayObject.mixin(accessibleTarget); + const KEY_CODE_TAB = 9; + const DIV_TOUCH_SIZE = 100; + const DIV_TOUCH_POS_X = 0; + const DIV_TOUCH_POS_Y = 0; + const DIV_TOUCH_ZINDEX = 2; + const DIV_HOOK_SIZE = 1; + const DIV_HOOK_POS_X = -1e3; + const DIV_HOOK_POS_Y = -1e3; + const DIV_HOOK_ZINDEX = 2; + class AccessibilityManager { + constructor(renderer) { + this.debug = false; + this._isActive = false; + this._isMobileAccessibility = false; + this.pool = []; + this.renderId = 0; + this.children = []; + this.androidUpdateCount = 0; + this.androidUpdateFrequency = 500; + this._hookDiv = null; + if (isMobile.tablet || isMobile.phone) { + this.createTouchHook(); + } + const div = document.createElement("div"); + div.style.width = `${DIV_TOUCH_SIZE}px`; + div.style.height = `${DIV_TOUCH_SIZE}px`; + div.style.position = "absolute"; + div.style.top = `${DIV_TOUCH_POS_X}px`; + div.style.left = `${DIV_TOUCH_POS_Y}px`; + div.style.zIndex = DIV_TOUCH_ZINDEX.toString(); + this.div = div; + this.renderer = renderer; + this._onKeyDown = this._onKeyDown.bind(this); + this._onMouseMove = this._onMouseMove.bind(this); + globalThis.addEventListener("keydown", this._onKeyDown, false); + } + get isActive() { + return this._isActive; + } + get isMobileAccessibility() { + return this._isMobileAccessibility; + } + createTouchHook() { + const hookDiv = document.createElement("button"); + hookDiv.style.width = `${DIV_HOOK_SIZE}px`; + hookDiv.style.height = `${DIV_HOOK_SIZE}px`; + hookDiv.style.position = "absolute"; + hookDiv.style.top = `${DIV_HOOK_POS_X}px`; + hookDiv.style.left = `${DIV_HOOK_POS_Y}px`; + hookDiv.style.zIndex = DIV_HOOK_ZINDEX.toString(); + hookDiv.style.backgroundColor = "#FF0000"; + hookDiv.title = "select to enable accessibility for this content"; + hookDiv.addEventListener("focus", () => { + this._isMobileAccessibility = true; + this.activate(); + this.destroyTouchHook(); + }); + document.body.appendChild(hookDiv); + this._hookDiv = hookDiv; + } + destroyTouchHook() { + if (!this._hookDiv) { + return; + } + document.body.removeChild(this._hookDiv); + this._hookDiv = null; + } + activate() { + if (this._isActive) { + return; + } + this._isActive = true; + globalThis.document.addEventListener("mousemove", this._onMouseMove, true); + globalThis.removeEventListener("keydown", this._onKeyDown, false); + this.renderer.on("postrender", this.update, this); + this.renderer.view.parentNode?.appendChild(this.div); + } + deactivate() { + if (!this._isActive || this._isMobileAccessibility) { + return; + } + this._isActive = false; + globalThis.document.removeEventListener("mousemove", this._onMouseMove, true); + globalThis.addEventListener("keydown", this._onKeyDown, false); + this.renderer.off("postrender", this.update); + this.div.parentNode?.removeChild(this.div); + } + updateAccessibleObjects(displayObject) { + if (!displayObject.visible || !displayObject.accessibleChildren) { + return; + } + if (displayObject.accessible && displayObject.isInteractive()) { + if (!displayObject._accessibleActive) { + this.addChild(displayObject); + } + displayObject.renderId = this.renderId; + } + const children = displayObject.children; + if (children) { + for (let i = 0; i < children.length; i++) { + this.updateAccessibleObjects(children[i]); + } + } + } + update() { + const now = performance.now(); + if (isMobile.android.device && now < this.androidUpdateCount) { + return; + } + this.androidUpdateCount = now + this.androidUpdateFrequency; + if (!this.renderer.renderingToScreen) { + return; + } + if (this.renderer.lastObjectRendered) { + this.updateAccessibleObjects(this.renderer.lastObjectRendered); + } + const { x, y, width, height } = this.renderer.view.getBoundingClientRect(); + const { width: viewWidth, height: viewHeight, resolution } = this.renderer; + const sx = width / viewWidth * resolution; + const sy = height / viewHeight * resolution; + let div = this.div; + div.style.left = `${x}px`; + div.style.top = `${y}px`; + div.style.width = `${viewWidth}px`; + div.style.height = `${viewHeight}px`; + for (let i = 0; i < this.children.length; i++) { + const child = this.children[i]; + if (child.renderId !== this.renderId) { + child._accessibleActive = false; + removeItems(this.children, i, 1); + this.div.removeChild(child._accessibleDiv); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + i--; + } else { + div = child._accessibleDiv; + let hitArea = child.hitArea; + const wt = child.worldTransform; + if (child.hitArea) { + div.style.left = `${(wt.tx + hitArea.x * wt.a) * sx}px`; + div.style.top = `${(wt.ty + hitArea.y * wt.d) * sy}px`; + div.style.width = `${hitArea.width * wt.a * sx}px`; + div.style.height = `${hitArea.height * wt.d * sy}px`; + } else { + hitArea = child.getBounds(); + this.capHitArea(hitArea); + div.style.left = `${hitArea.x * sx}px`; + div.style.top = `${hitArea.y * sy}px`; + div.style.width = `${hitArea.width * sx}px`; + div.style.height = `${hitArea.height * sy}px`; + if (div.title !== child.accessibleTitle && child.accessibleTitle !== null) { + div.title = child.accessibleTitle; + } + if (div.getAttribute("aria-label") !== child.accessibleHint && child.accessibleHint !== null) { + div.setAttribute("aria-label", child.accessibleHint); + } + } + if (child.accessibleTitle !== div.title || child.tabIndex !== div.tabIndex) { + div.title = child.accessibleTitle; + div.tabIndex = child.tabIndex; + if (this.debug) + this.updateDebugHTML(div); + } + } + } + this.renderId++; + } + updateDebugHTML(div) { + div.innerHTML = `type: ${div.type}
title : ${div.title}
tabIndex: ${div.tabIndex}`; + } + capHitArea(hitArea) { + if (hitArea.x < 0) { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + if (hitArea.y < 0) { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + const { width: viewWidth, height: viewHeight } = this.renderer; + if (hitArea.x + hitArea.width > viewWidth) { + hitArea.width = viewWidth - hitArea.x; + } + if (hitArea.y + hitArea.height > viewHeight) { + hitArea.height = viewHeight - hitArea.y; + } + } + addChild(displayObject) { + let div = this.pool.pop(); + if (!div) { + div = document.createElement("button"); + div.style.width = `${DIV_TOUCH_SIZE}px`; + div.style.height = `${DIV_TOUCH_SIZE}px`; + div.style.backgroundColor = this.debug ? "rgba(255,255,255,0.5)" : "transparent"; + div.style.position = "absolute"; + div.style.zIndex = DIV_TOUCH_ZINDEX.toString(); + div.style.borderStyle = "none"; + if (navigator.userAgent.toLowerCase().includes("chrome")) { + div.setAttribute("aria-live", "off"); + } else { + div.setAttribute("aria-live", "polite"); + } + if (navigator.userAgent.match(/rv:.*Gecko\//)) { + div.setAttribute("aria-relevant", "additions"); + } else { + div.setAttribute("aria-relevant", "text"); + } + div.addEventListener("click", this._onClick.bind(this)); + div.addEventListener("focus", this._onFocus.bind(this)); + div.addEventListener("focusout", this._onFocusOut.bind(this)); + } + div.style.pointerEvents = displayObject.accessiblePointerEvents; + div.type = displayObject.accessibleType; + if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null) { + div.title = displayObject.accessibleTitle; + } else if (!displayObject.accessibleHint || displayObject.accessibleHint === null) { + div.title = `displayObject ${displayObject.tabIndex}`; + } + if (displayObject.accessibleHint && displayObject.accessibleHint !== null) { + div.setAttribute("aria-label", displayObject.accessibleHint); + } + if (this.debug) + this.updateDebugHTML(div); + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + this.children.push(displayObject); + this.div.appendChild(displayObject._accessibleDiv); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; + } + _dispatchEvent(e, type) { + const { displayObject: target } = e.target; + const boundry = this.renderer.events.rootBoundary; + const event = Object.assign(new FederatedEvent(boundry), { target }); + boundry.rootTarget = this.renderer.lastObjectRendered; + type.forEach((type2) => boundry.dispatchEvent(event, type2)); + } + _onClick(e) { + this._dispatchEvent(e, ["click", "pointertap", "tap"]); + } + _onFocus(e) { + if (!e.target.getAttribute("aria-live")) { + e.target.setAttribute("aria-live", "assertive"); + } + this._dispatchEvent(e, ["mouseover"]); + } + _onFocusOut(e) { + if (!e.target.getAttribute("aria-live")) { + e.target.setAttribute("aria-live", "polite"); + } + this._dispatchEvent(e, ["mouseout"]); + } + _onKeyDown(e) { + if (e.keyCode !== KEY_CODE_TAB) { + return; + } + this.activate(); + } + _onMouseMove(e) { + if (e.movementX === 0 && e.movementY === 0) { + return; + } + this.deactivate(); + } + destroy() { + this.destroyTouchHook(); + this.div = null; + globalThis.document.removeEventListener("mousemove", this._onMouseMove, true); + globalThis.removeEventListener("keydown", this._onKeyDown); + this.pool = null; + this.children = null; + this.renderer = null; + } + } + AccessibilityManager.extension = { + name: "accessibility", + type: [ + ExtensionType.RendererPlugin, + ExtensionType.CanvasRendererPlugin + ] + }; + extensions$1.add(AccessibilityManager); + + const _Application = class { + constructor(options) { + this.stage = new Container(); + options = Object.assign({ + forceCanvas: false + }, options); + this.renderer = autoDetectRenderer(options); + _Application._plugins.forEach((plugin) => { + plugin.init.call(this, options); + }); + } + render() { + this.renderer.render(this.stage); + } + get view() { + return this.renderer.view; + } + get screen() { + return this.renderer.screen; + } + destroy(removeView, stageOptions) { + const plugins = _Application._plugins.slice(0); + plugins.reverse(); + plugins.forEach((plugin) => { + plugin.destroy.call(this); + }); + this.stage.destroy(stageOptions); + this.stage = null; + this.renderer.destroy(removeView); + this.renderer = null; + } + }; + let Application = _Application; + Application._plugins = []; + extensions$1.handleByList(ExtensionType.Application, Application._plugins); + + class ResizePlugin { + static init(options) { + Object.defineProperty(this, "resizeTo", { + set(dom) { + globalThis.removeEventListener("resize", this.queueResize); + this._resizeTo = dom; + if (dom) { + globalThis.addEventListener("resize", this.queueResize); + this.resize(); + } + }, + get() { + return this._resizeTo; + } + }); + this.queueResize = () => { + if (!this._resizeTo) { + return; + } + this.cancelResize(); + this._resizeId = requestAnimationFrame(() => this.resize()); + }; + this.cancelResize = () => { + if (this._resizeId) { + cancelAnimationFrame(this._resizeId); + this._resizeId = null; + } + }; + this.resize = () => { + if (!this._resizeTo) { + return; + } + this.cancelResize(); + let width; + let height; + if (this._resizeTo === globalThis.window) { + width = globalThis.innerWidth; + height = globalThis.innerHeight; + } else { + const { clientWidth, clientHeight } = this._resizeTo; + width = clientWidth; + height = clientHeight; + } + this.renderer.resize(width, height); + this.render(); + }; + this._resizeId = null; + this._resizeTo = null; + this.resizeTo = options.resizeTo || null; + } + static destroy() { + globalThis.removeEventListener("resize", this.queueResize); + this.cancelResize(); + this.cancelResize = null; + this.queueResize = null; + this.resizeTo = null; + this.resize = null; + } + } + ResizePlugin.extension = ExtensionType.Application; + extensions$1.add(ResizePlugin); + + const assetKeyMap = { + loader: ExtensionType.LoadParser, + resolver: ExtensionType.ResolveParser, + cache: ExtensionType.CacheParser, + detection: ExtensionType.DetectionParser + }; + extensions$1.handle(ExtensionType.Asset, (extension) => { + const ref = extension.ref; + Object.entries(assetKeyMap).filter(([key]) => !!ref[key]).forEach(([key, type]) => extensions$1.add(Object.assign(ref[key], { extension: ref[key].extension ?? type }))); + }, (extension) => { + const ref = extension.ref; + Object.keys(assetKeyMap).filter((key) => !!ref[key]).forEach((key) => extensions$1.remove(ref[key])); + }); + + class BackgroundLoader { + constructor(loader, verbose = false) { + this._loader = loader; + this._assetList = []; + this._isLoading = false; + this._maxConcurrent = 1; + this.verbose = verbose; + } + add(assetUrls) { + assetUrls.forEach((a) => { + this._assetList.push(a); + }); + if (this.verbose) + console.log("[BackgroundLoader] assets: ", this._assetList); + if (this._isActive && !this._isLoading) { + this._next(); + } + } + async _next() { + if (this._assetList.length && this._isActive) { + this._isLoading = true; + const toLoad = []; + const toLoadAmount = Math.min(this._assetList.length, this._maxConcurrent); + for (let i = 0; i < toLoadAmount; i++) { + toLoad.push(this._assetList.pop()); + } + await this._loader.load(toLoad); + this._isLoading = false; + this._next(); + } + } + get active() { + return this._isActive; + } + set active(value) { + if (this._isActive === value) + return; + this._isActive = value; + if (value && !this._isLoading) { + this._next(); + } + } + } + + function checkDataUrl(url, mimes) { + if (Array.isArray(mimes)) { + for (const mime of mimes) { + if (url.startsWith(`data:${mime}`)) + return true; + } + return false; + } + return url.startsWith(`data:${mimes}`); + } + + function checkExtension(url, extension) { + const tempURL = url.split("?")[0]; + const ext = path.extname(tempURL).toLowerCase(); + if (Array.isArray(extension)) { + return extension.includes(ext); + } + return ext === extension; + } + + const convertToList = (input, transform) => { + if (!Array.isArray(input)) { + input = [input]; + } + if (!transform) { + return input; + } + return input.map((item) => { + if (typeof item === "string") { + return transform(item); + } + return item; + }); + }; + + const copySearchParams = (targetUrl, sourceUrl) => { + const searchParams = sourceUrl.split("?")[1]; + if (searchParams) { + targetUrl += `?${searchParams}`; + } + return targetUrl; + }; + + function processX(base, ids, depth, result, tags) { + const id = ids[depth]; + for (let i = 0; i < id.length; i++) { + const value = id[i]; + if (depth < ids.length - 1) { + processX(base.replace(result[depth], value), ids, depth + 1, result, tags); + } else { + tags.push(base.replace(result[depth], value)); + } + } + } + function createStringVariations(string) { + const regex = /\{(.*?)\}/g; + const result = string.match(regex); + const tags = []; + if (result) { + const ids = []; + result.forEach((vars) => { + const split = vars.substring(1, vars.length - 1).split(","); + ids.push(split); + }); + processX(string, ids, 0, result, tags); + } else { + tags.push(string); + } + return tags; + } + + const isSingleItem = (item) => !Array.isArray(item); + + class CacheClass { + constructor() { + this._parsers = []; + this._cache = /* @__PURE__ */ new Map(); + this._cacheMap = /* @__PURE__ */ new Map(); + } + reset() { + this._cacheMap.clear(); + this._cache.clear(); + } + has(key) { + return this._cache.has(key); + } + get(key) { + const result = this._cache.get(key); + if (!result) { + console.warn(`[Assets] Asset id ${key} was not found in the Cache`); + } + return result; + } + set(key, value) { + const keys = convertToList(key); + let cacheableAssets; + for (let i = 0; i < this.parsers.length; i++) { + const parser = this.parsers[i]; + if (parser.test(value)) { + cacheableAssets = parser.getCacheableAssets(keys, value); + break; + } + } + if (!cacheableAssets) { + cacheableAssets = {}; + keys.forEach((key2) => { + cacheableAssets[key2] = value; + }); + } + const cacheKeys = Object.keys(cacheableAssets); + const cachedAssets = { + cacheKeys, + keys + }; + keys.forEach((key2) => { + this._cacheMap.set(key2, cachedAssets); + }); + cacheKeys.forEach((key2) => { + if (this._cache.has(key2) && this._cache.get(key2) !== value) { + console.warn("[Cache] already has key:", key2); + } + this._cache.set(key2, cacheableAssets[key2]); + }); + if (value instanceof Texture) { + const texture = value; + keys.forEach((key2) => { + if (texture.baseTexture !== Texture.EMPTY.baseTexture) { + BaseTexture.addToCache(texture.baseTexture, key2); + } + Texture.addToCache(texture, key2); + }); + } + } + remove(key) { + this._cacheMap.get(key); + if (!this._cacheMap.has(key)) { + console.warn(`[Assets] Asset id ${key} was not found in the Cache`); + return; + } + const cacheMap = this._cacheMap.get(key); + const cacheKeys = cacheMap.cacheKeys; + cacheKeys.forEach((key2) => { + this._cache.delete(key2); + }); + cacheMap.keys.forEach((key2) => { + this._cacheMap.delete(key2); + }); + } + get parsers() { + return this._parsers; + } + } + const Cache = new CacheClass(); + + class Loader { + constructor() { + this._parsers = []; + this._parsersValidated = false; + this.parsers = new Proxy(this._parsers, { + set: (target, key, value) => { + this._parsersValidated = false; + target[key] = value; + return true; + } + }); + this.promiseCache = {}; + } + reset() { + this._parsersValidated = false; + this.promiseCache = {}; + } + _getLoadPromiseAndParser(url, data) { + const result = { + promise: null, + parser: null + }; + result.promise = (async () => { + let asset = null; + let parser = null; + if (data.loadParser) { + parser = this._parserHash[data.loadParser]; + if (!parser) { + console.warn(`[Assets] specified load parser "${data.loadParser}" not found while loading ${url}`); + } + } + if (!parser) { + for (let i = 0; i < this.parsers.length; i++) { + const parserX = this.parsers[i]; + if (parserX.load && parserX.test?.(url, data, this)) { + parser = parserX; + break; + } + } + if (!parser) { + console.warn(`[Assets] ${url} could not be loaded as we don't know how to parse it, ensure the correct parser has been added`); + return null; + } + } + asset = await parser.load(url, data, this); + result.parser = parser; + for (let i = 0; i < this.parsers.length; i++) { + const parser2 = this.parsers[i]; + if (parser2.parse) { + if (parser2.parse && await parser2.testParse?.(asset, data, this)) { + asset = await parser2.parse(asset, data, this) || asset; + result.parser = parser2; + } + } + } + return asset; + })(); + return result; + } + async load(assetsToLoadIn, onProgress) { + if (!this._parsersValidated) { + this._validateParsers(); + } + let count = 0; + const assets = {}; + const singleAsset = isSingleItem(assetsToLoadIn); + const assetsToLoad = convertToList(assetsToLoadIn, (item) => ({ + src: item + })); + const total = assetsToLoad.length; + const promises = assetsToLoad.map(async (asset) => { + const url = path.toAbsolute(asset.src); + if (!assets[asset.src]) { + try { + if (!this.promiseCache[url]) { + this.promiseCache[url] = this._getLoadPromiseAndParser(url, asset); + } + assets[asset.src] = await this.promiseCache[url].promise; + if (onProgress) + onProgress(++count / total); + } catch (e) { + delete this.promiseCache[url]; + delete assets[asset.src]; + throw new Error(`[Loader.load] Failed to load ${url}. +${e}`); + } + } + }); + await Promise.all(promises); + return singleAsset ? assets[assetsToLoad[0].src] : assets; + } + async unload(assetsToUnloadIn) { + const assetsToUnload = convertToList(assetsToUnloadIn, (item) => ({ + src: item + })); + const promises = assetsToUnload.map(async (asset) => { + const url = path.toAbsolute(asset.src); + const loadPromise = this.promiseCache[url]; + if (loadPromise) { + const loadedAsset = await loadPromise.promise; + loadPromise.parser?.unload?.(loadedAsset, asset, this); + delete this.promiseCache[url]; + } + }); + await Promise.all(promises); + } + _validateParsers() { + this._parsersValidated = true; + this._parserHash = this._parsers.filter((parser) => parser.name).reduce((hash, parser) => { + if (hash[parser.name]) { + console.warn(`[Assets] loadParser name conflict "${parser.name}"`); + } + return { ...hash, [parser.name]: parser }; + }, {}); + } + } + + var LoaderParserPriority = /* @__PURE__ */ ((LoaderParserPriority2) => { + LoaderParserPriority2[LoaderParserPriority2["Low"] = 0] = "Low"; + LoaderParserPriority2[LoaderParserPriority2["Normal"] = 1] = "Normal"; + LoaderParserPriority2[LoaderParserPriority2["High"] = 2] = "High"; + return LoaderParserPriority2; + })(LoaderParserPriority || {}); + + const validJSONExtension = ".json"; + const validJSONMIME = "application/json"; + const loadJson = { + extension: { + type: ExtensionType.LoadParser, + priority: LoaderParserPriority.Low + }, + name: "loadJson", + test(url) { + return checkDataUrl(url, validJSONMIME) || checkExtension(url, validJSONExtension); + }, + async load(url) { + const response = await settings.ADAPTER.fetch(url); + const json = await response.json(); + return json; + } + }; + extensions$1.add(loadJson); + + const validTXTExtension = ".txt"; + const validTXTMIME = "text/plain"; + const loadTxt = { + name: "loadTxt", + extension: { + type: ExtensionType.LoadParser, + priority: LoaderParserPriority.Low + }, + test(url) { + return checkDataUrl(url, validTXTMIME) || checkExtension(url, validTXTExtension); + }, + async load(url) { + const response = await settings.ADAPTER.fetch(url); + const txt = await response.text(); + return txt; + } + }; + extensions$1.add(loadTxt); + + const validWeights = [ + "normal", + "bold", + "100", + "200", + "300", + "400", + "500", + "600", + "700", + "800", + "900" + ]; + const validFontExtensions = [".ttf", ".otf", ".woff", ".woff2"]; + const validFontMIMEs = [ + "font/ttf", + "font/otf", + "font/woff", + "font/woff2" + ]; + const CSS_IDENT_TOKEN_REGEX = /^(--|-?[A-Z_])[0-9A-Z_-]*$/i; + function getFontFamilyName(url) { + const ext = path.extname(url); + const name = path.basename(url, ext); + const nameWithSpaces = name.replace(/(-|_)/g, " "); + const nameTokens = nameWithSpaces.toLowerCase().split(" ").map((word) => word.charAt(0).toUpperCase() + word.slice(1)); + let valid = nameTokens.length > 0; + for (const token of nameTokens) { + if (!token.match(CSS_IDENT_TOKEN_REGEX)) { + valid = false; + break; + } + } + let fontFamilyName = nameTokens.join(" "); + if (!valid) { + fontFamilyName = `"${fontFamilyName.replace(/[\\"]/g, "\\$&")}"`; + } + return fontFamilyName; + } + const loadWebFont = { + extension: { + type: ExtensionType.LoadParser, + priority: LoaderParserPriority.Low + }, + name: "loadWebFont", + test(url) { + return checkDataUrl(url, validFontMIMEs) || checkExtension(url, validFontExtensions); + }, + async load(url, options) { + const fonts = settings.ADAPTER.getFontFaceSet(); + if (fonts) { + const fontFaces = []; + const name = options.data?.family ?? getFontFamilyName(url); + const weights = options.data?.weights?.filter((weight) => validWeights.includes(weight)) ?? ["normal"]; + const data = options.data ?? {}; + for (let i = 0; i < weights.length; i++) { + const weight = weights[i]; + const font = new FontFace(name, `url(${encodeURI(url)})`, { + ...data, + weight + }); + await font.load(); + fonts.add(font); + fontFaces.push(font); + } + return fontFaces.length === 1 ? fontFaces[0] : fontFaces; + } + console.warn("[loadWebFont] FontFace API is not supported. Skipping loading font"); + return null; + }, + unload(font) { + (Array.isArray(font) ? font : [font]).forEach((t) => settings.ADAPTER.getFontFaceSet().delete(t)); + } + }; + extensions$1.add(loadWebFont); + + let UUID = 0; + let MAX_WORKERS; + const WHITE_PNG = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII="; + const checkImageBitmapCode = { + id: "checkImageBitmap", + code: ` + async function checkImageBitmap() + { + try + { + if (typeof createImageBitmap !== 'function') return false; + + const response = await fetch('${WHITE_PNG}'); + const imageBlob = await response.blob(); + const imageBitmap = await createImageBitmap(imageBlob); + + return imageBitmap.width === 1 && imageBitmap.height === 1; + } + catch (e) + { + return false; + } + } + checkImageBitmap().then((result) => { self.postMessage(result); }); + ` + }; + const workerCode = { + id: "loadImageBitmap", + code: ` + async function loadImageBitmap(url) + { + const response = await fetch(url); + + if (!response.ok) + { + throw new Error(\`[WorkerManager.loadImageBitmap] Failed to fetch \${url}: \` + + \`\${response.status} \${response.statusText}\`); + } + + const imageBlob = await response.blob(); + const imageBitmap = await createImageBitmap(imageBlob); + + return imageBitmap; + } + self.onmessage = async (event) => + { + try + { + const imageBitmap = await loadImageBitmap(event.data.data[0]); + + self.postMessage({ + data: imageBitmap, + uuid: event.data.uuid, + id: event.data.id, + }, [imageBitmap]); + } + catch(e) + { + self.postMessage({ + error: e, + uuid: event.data.uuid, + id: event.data.id, + }); + } + };` + }; + let workerURL; + class WorkerManagerClass { + constructor() { + this._initialized = false; + this._createdWorkers = 0; + this.workerPool = []; + this.queue = []; + this.resolveHash = {}; + } + isImageBitmapSupported() { + if (this._isImageBitmapSupported !== void 0) + return this._isImageBitmapSupported; + this._isImageBitmapSupported = new Promise((resolve) => { + const workerURL2 = URL.createObjectURL(new Blob([checkImageBitmapCode.code], { type: "application/javascript" })); + const worker = new Worker(workerURL2); + worker.addEventListener("message", (event) => { + worker.terminate(); + URL.revokeObjectURL(workerURL2); + resolve(event.data); + }); + }); + return this._isImageBitmapSupported; + } + loadImageBitmap(src) { + return this._run("loadImageBitmap", [src]); + } + async _initWorkers() { + if (this._initialized) + return; + this._initialized = true; + } + getWorker() { + if (MAX_WORKERS === void 0) { + MAX_WORKERS = navigator.hardwareConcurrency || 4; + } + let worker = this.workerPool.pop(); + if (!worker && this._createdWorkers < MAX_WORKERS) { + if (!workerURL) { + workerURL = URL.createObjectURL(new Blob([workerCode.code], { type: "application/javascript" })); + } + this._createdWorkers++; + worker = new Worker(workerURL); + worker.addEventListener("message", (event) => { + this.complete(event.data); + this.returnWorker(event.target); + this.next(); + }); + } + return worker; + } + returnWorker(worker) { + this.workerPool.push(worker); + } + complete(data) { + if (data.error !== void 0) { + this.resolveHash[data.uuid].reject(data.error); + } else { + this.resolveHash[data.uuid].resolve(data.data); + } + this.resolveHash[data.uuid] = null; + } + async _run(id, args) { + await this._initWorkers(); + const promise = new Promise((resolve, reject) => { + this.queue.push({ id, arguments: args, resolve, reject }); + }); + this.next(); + return promise; + } + next() { + if (!this.queue.length) + return; + const worker = this.getWorker(); + if (!worker) { + return; + } + const toDo = this.queue.pop(); + const id = toDo.id; + this.resolveHash[UUID] = { resolve: toDo.resolve, reject: toDo.reject }; + worker.postMessage({ + data: toDo.arguments, + uuid: UUID++, + id + }); + } + } + const WorkerManager = new WorkerManagerClass(); + + function createTexture(base, loader, url) { + const texture = new Texture(base); + texture.baseTexture.on("dispose", () => { + delete loader.promiseCache[url]; + }); + return texture; + } + + const validImageExtensions = [".jpeg", ".jpg", ".png", ".webp", ".avif"]; + const validImageMIMEs = [ + "image/jpeg", + "image/png", + "image/webp", + "image/avif" + ]; + async function loadImageBitmap(url) { + const response = await settings.ADAPTER.fetch(url); + if (!response.ok) { + throw new Error(`[loadImageBitmap] Failed to fetch ${url}: ${response.status} ${response.statusText}`); + } + const imageBlob = await response.blob(); + const imageBitmap = await createImageBitmap(imageBlob); + return imageBitmap; + } + const loadTextures = { + name: "loadTextures", + extension: { + type: ExtensionType.LoadParser, + priority: LoaderParserPriority.High + }, + config: { + preferWorkers: true, + preferCreateImageBitmap: true, + crossOrigin: "anonymous" + }, + test(url) { + return checkDataUrl(url, validImageMIMEs) || checkExtension(url, validImageExtensions); + }, + async load(url, asset, loader) { + let src = null; + if (globalThis.createImageBitmap && this.config.preferCreateImageBitmap) { + if (this.config.preferWorkers && await WorkerManager.isImageBitmapSupported()) { + src = await WorkerManager.loadImageBitmap(url); + } else { + src = await loadImageBitmap(url); + } + } else { + src = await new Promise((resolve) => { + src = new Image(); + src.crossOrigin = this.config.crossOrigin; + src.src = url; + if (src.complete) { + resolve(src); + } else { + src.onload = () => { + resolve(src); + }; + } + }); + } + const base = new BaseTexture(src, { + resolution: getResolutionOfUrl(url), + ...asset.data + }); + base.resource.src = url; + return createTexture(base, loader, url); + }, + unload(texture) { + texture.destroy(true); + } + }; + extensions$1.add(loadTextures); + + const validSVGExtension = ".svg"; + const validSVGMIME = "image/svg+xml"; + const loadSVG = { + extension: { + type: ExtensionType.LoadParser, + priority: LoaderParserPriority.High + }, + name: "loadSVG", + test(url) { + return checkDataUrl(url, validSVGMIME) || checkExtension(url, validSVGExtension); + }, + async testParse(data) { + return SVGResource.test(data); + }, + async parse(asset, data, loader) { + const src = new SVGResource(asset, data?.data?.resourceOptions); + await src.load(); + const base = new BaseTexture(src, { + resolution: getResolutionOfUrl(asset), + ...data?.data + }); + base.resource.src = asset; + const texture = createTexture(base, loader, asset); + return texture; + }, + async load(url, _options) { + const response = await settings.ADAPTER.fetch(url); + return response.text(); + }, + unload: loadTextures.unload + }; + extensions$1.add(loadSVG); + + class Resolver { + constructor() { + this._defaultBundleIdentifierOptions = { + connector: "-", + createBundleAssetId: (bundleId, assetId) => `${bundleId}${this._bundleIdConnector}${assetId}`, + extractAssetIdFromBundle: (bundleId, assetBundleId) => assetBundleId.replace(`${bundleId}${this._bundleIdConnector}`, "") + }; + this._bundleIdConnector = this._defaultBundleIdentifierOptions.connector; + this._createBundleAssetId = this._defaultBundleIdentifierOptions.createBundleAssetId; + this._extractAssetIdFromBundle = this._defaultBundleIdentifierOptions.extractAssetIdFromBundle; + this._assetMap = {}; + this._preferredOrder = []; + this._parsers = []; + this._resolverHash = {}; + this._bundles = {}; + } + setBundleIdentifier(bundleIdentifier) { + this._bundleIdConnector = bundleIdentifier.connector ?? this._bundleIdConnector; + this._createBundleAssetId = bundleIdentifier.createBundleAssetId ?? this._createBundleAssetId; + this._extractAssetIdFromBundle = bundleIdentifier.extractAssetIdFromBundle ?? this._extractAssetIdFromBundle; + if (this._extractAssetIdFromBundle("foo", this._createBundleAssetId("foo", "bar")) !== "bar") { + throw new Error("[Resolver] GenerateBundleAssetId are not working correctly"); + } + } + prefer(...preferOrders) { + preferOrders.forEach((prefer) => { + this._preferredOrder.push(prefer); + if (!prefer.priority) { + prefer.priority = Object.keys(prefer.params); + } + }); + this._resolverHash = {}; + } + set basePath(basePath) { + this._basePath = basePath; + } + get basePath() { + return this._basePath; + } + set rootPath(rootPath) { + this._rootPath = rootPath; + } + get rootPath() { + return this._rootPath; + } + get parsers() { + return this._parsers; + } + reset() { + this.setBundleIdentifier(this._defaultBundleIdentifierOptions); + this._assetMap = {}; + this._preferredOrder = []; + this._resolverHash = {}; + this._rootPath = null; + this._basePath = null; + this._manifest = null; + this._bundles = {}; + this._defaultSearchParams = null; + } + setDefaultSearchParams(searchParams) { + if (typeof searchParams === "string") { + this._defaultSearchParams = searchParams; + } else { + const queryValues = searchParams; + this._defaultSearchParams = Object.keys(queryValues).map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(queryValues[key])}`).join("&"); + } + } + addManifest(manifest) { + if (this._manifest) { + console.warn("[Resolver] Manifest already exists, this will be overwritten"); + } + this._manifest = manifest; + manifest.bundles.forEach((bundle) => { + this.addBundle(bundle.name, bundle.assets); + }); + } + addBundle(bundleId, assets) { + const assetNames = []; + if (Array.isArray(assets)) { + assets.forEach((asset) => { + if (typeof asset.name === "string") { + const bundleAssetId = this._createBundleAssetId(bundleId, asset.name); + assetNames.push(bundleAssetId); + this.add([asset.name, bundleAssetId], asset.srcs, asset.data); + } else { + const bundleIds = asset.name.map((name) => this._createBundleAssetId(bundleId, name)); + bundleIds.forEach((bundleId2) => { + assetNames.push(bundleId2); + }); + this.add([...asset.name, ...bundleIds], asset.srcs); + } + }); + } else { + Object.keys(assets).forEach((key) => { + assetNames.push(this._createBundleAssetId(bundleId, key)); + this.add([key, this._createBundleAssetId(bundleId, key)], assets[key]); + }); + } + this._bundles[bundleId] = assetNames; + } + add(keysIn, assetsIn, data) { + const keys = convertToList(keysIn); + keys.forEach((key) => { + if (this.hasKey(key)) { + console.warn(`[Resolver] already has key: ${key} overwriting`); + } + }); + if (!Array.isArray(assetsIn)) { + if (typeof assetsIn === "string") { + assetsIn = createStringVariations(assetsIn); + } else { + assetsIn = [assetsIn]; + } + } + const assetMap = assetsIn.map((asset) => { + let formattedAsset = asset; + if (typeof asset === "string") { + let parsed = false; + for (let i = 0; i < this._parsers.length; i++) { + const parser = this._parsers[i]; + if (parser.test(asset)) { + formattedAsset = parser.parse(asset); + parsed = true; + break; + } + } + if (!parsed) { + formattedAsset = { + src: asset + }; + } + } + if (!formattedAsset.format) { + formattedAsset.format = formattedAsset.src.split(".").pop(); + } + if (!formattedAsset.alias) { + formattedAsset.alias = keys; + } + if (this._basePath || this._rootPath) { + formattedAsset.src = path.toAbsolute(formattedAsset.src, this._basePath, this._rootPath); + } + formattedAsset.src = this._appendDefaultSearchParams(formattedAsset.src); + formattedAsset.data = formattedAsset.data ?? data; + return formattedAsset; + }); + keys.forEach((key) => { + this._assetMap[key] = assetMap; + }); + } + resolveBundle(bundleIds) { + const singleAsset = isSingleItem(bundleIds); + bundleIds = convertToList(bundleIds); + const out = {}; + bundleIds.forEach((bundleId) => { + const assetNames = this._bundles[bundleId]; + if (assetNames) { + const results = this.resolve(assetNames); + const assets = {}; + for (const key in results) { + const asset = results[key]; + assets[this._extractAssetIdFromBundle(bundleId, key)] = asset; + } + out[bundleId] = assets; + } + }); + return singleAsset ? out[bundleIds[0]] : out; + } + resolveUrl(key) { + const result = this.resolve(key); + if (typeof key !== "string") { + const out = {}; + for (const i in result) { + out[i] = result[i].src; + } + return out; + } + return result.src; + } + resolve(keys) { + const singleAsset = isSingleItem(keys); + keys = convertToList(keys); + const result = {}; + keys.forEach((key) => { + if (!this._resolverHash[key]) { + if (this._assetMap[key]) { + let assets = this._assetMap[key]; + const preferredOrder = this._getPreferredOrder(assets); + const bestAsset = assets[0]; + preferredOrder?.priority.forEach((priorityKey) => { + preferredOrder.params[priorityKey].forEach((value) => { + const filteredAssets = assets.filter((asset) => { + if (asset[priorityKey]) { + return asset[priorityKey] === value; + } + return false; + }); + if (filteredAssets.length) { + assets = filteredAssets; + } + }); + }); + this._resolverHash[key] = assets[0] ?? bestAsset; + } else { + let src = key; + if (this._basePath || this._rootPath) { + src = path.toAbsolute(src, this._basePath, this._rootPath); + } + src = this._appendDefaultSearchParams(src); + this._resolverHash[key] = { + src + }; + } + } + result[key] = this._resolverHash[key]; + }); + return singleAsset ? result[keys[0]] : result; + } + hasKey(key) { + return !!this._assetMap[key]; + } + hasBundle(key) { + return !!this._bundles[key]; + } + _getPreferredOrder(assets) { + for (let i = 0; i < assets.length; i++) { + const asset = assets[0]; + const preferred = this._preferredOrder.find((preference) => preference.params.format.includes(asset.format)); + if (preferred) { + return preferred; + } + } + return this._preferredOrder[0]; + } + _appendDefaultSearchParams(url) { + if (!this._defaultSearchParams) + return url; + const paramConnector = /\?/.test(url) ? "&" : "?"; + return `${url}${paramConnector}${this._defaultSearchParams}`; + } + } + + class AssetsClass { + constructor() { + this._detections = []; + this._initialized = false; + this.resolver = new Resolver(); + this.loader = new Loader(); + this.cache = Cache; + this._backgroundLoader = new BackgroundLoader(this.loader); + this._backgroundLoader.active = true; + this.reset(); + } + async init(options = {}) { + if (this._initialized) { + console.warn("[Assets]AssetManager already initialized, did you load before calling this Asset.init()?"); + return; + } + this._initialized = true; + if (options.defaultSearchParams) { + this.resolver.setDefaultSearchParams(options.defaultSearchParams); + } + if (options.basePath) { + this.resolver.basePath = options.basePath; + } + if (options.bundleIdentifier) { + this.resolver.setBundleIdentifier(options.bundleIdentifier); + } + if (options.manifest) { + let manifest = options.manifest; + if (typeof manifest === "string") { + manifest = await this.load(manifest); + } + this.resolver.addManifest(manifest); + } + const resolutionPref = options.texturePreference?.resolution ?? 1; + const resolution = typeof resolutionPref === "number" ? [resolutionPref] : resolutionPref; + let formats = []; + if (options.texturePreference?.format) { + const formatPref = options.texturePreference?.format; + formats = typeof formatPref === "string" ? [formatPref] : formatPref; + for (const detection of this._detections) { + if (!await detection.test()) { + formats = await detection.remove(formats); + } + } + } else { + for (const detection of this._detections) { + if (await detection.test()) { + formats = await detection.add(formats); + } + } + } + this.resolver.prefer({ + params: { + format: formats, + resolution + } + }); + if (options.preferences) { + this.setPreferences(options.preferences); + } + } + add(keysIn, assetsIn, data) { + this.resolver.add(keysIn, assetsIn, data); + } + async load(urls, onProgress) { + if (!this._initialized) { + await this.init(); + } + const singleAsset = isSingleItem(urls); + const urlArray = convertToList(urls).map((url) => { + if (typeof url !== "string") { + this.resolver.add(url.src, url); + return url.src; + } + if (!this.resolver.hasKey(url)) { + this.resolver.add(url, url); + } + return url; + }); + const resolveResults = this.resolver.resolve(urlArray); + const out = await this._mapLoadToResolve(resolveResults, onProgress); + return singleAsset ? out[urlArray[0]] : out; + } + addBundle(bundleId, assets) { + this.resolver.addBundle(bundleId, assets); + } + async loadBundle(bundleIds, onProgress) { + if (!this._initialized) { + await this.init(); + } + let singleAsset = false; + if (typeof bundleIds === "string") { + singleAsset = true; + bundleIds = [bundleIds]; + } + const resolveResults = this.resolver.resolveBundle(bundleIds); + const out = {}; + const keys = Object.keys(resolveResults); + let count = 0; + let total = 0; + const _onProgress = () => { + onProgress?.(++count / total); + }; + const promises = keys.map((bundleId) => { + const resolveResult = resolveResults[bundleId]; + total += Object.keys(resolveResult).length; + return this._mapLoadToResolve(resolveResult, _onProgress).then((resolveResult2) => { + out[bundleId] = resolveResult2; + }); + }); + await Promise.all(promises); + return singleAsset ? out[bundleIds[0]] : out; + } + async backgroundLoad(urls) { + if (!this._initialized) { + await this.init(); + } + if (typeof urls === "string") { + urls = [urls]; + } + const resolveResults = this.resolver.resolve(urls); + this._backgroundLoader.add(Object.values(resolveResults)); + } + async backgroundLoadBundle(bundleIds) { + if (!this._initialized) { + await this.init(); + } + if (typeof bundleIds === "string") { + bundleIds = [bundleIds]; + } + const resolveResults = this.resolver.resolveBundle(bundleIds); + Object.values(resolveResults).forEach((resolveResult) => { + this._backgroundLoader.add(Object.values(resolveResult)); + }); + } + reset() { + this.resolver.reset(); + this.loader.reset(); + this.cache.reset(); + this._initialized = false; + } + get(keys) { + if (typeof keys === "string") { + return Cache.get(keys); + } + const assets = {}; + for (let i = 0; i < keys.length; i++) { + assets[i] = Cache.get(keys[i]); + } + return assets; + } + async _mapLoadToResolve(resolveResults, onProgress) { + const resolveArray = Object.values(resolveResults); + const resolveKeys = Object.keys(resolveResults); + this._backgroundLoader.active = false; + const loadedAssets = await this.loader.load(resolveArray, onProgress); + this._backgroundLoader.active = true; + const out = {}; + resolveArray.forEach((resolveResult, i) => { + const asset = loadedAssets[resolveResult.src]; + const keys = [resolveResult.src]; + if (resolveResult.alias) { + keys.push(...resolveResult.alias); + } + out[resolveKeys[i]] = asset; + Cache.set(keys, asset); + }); + return out; + } + async unload(urls) { + if (!this._initialized) { + await this.init(); + } + const urlArray = convertToList(urls).map((url) => typeof url !== "string" ? url.src : url); + const resolveResults = this.resolver.resolve(urlArray); + await this._unloadFromResolved(resolveResults); + } + async unloadBundle(bundleIds) { + if (!this._initialized) { + await this.init(); + } + bundleIds = convertToList(bundleIds); + const resolveResults = this.resolver.resolveBundle(bundleIds); + const promises = Object.keys(resolveResults).map((bundleId) => this._unloadFromResolved(resolveResults[bundleId])); + await Promise.all(promises); + } + async _unloadFromResolved(resolveResult) { + const resolveArray = Object.values(resolveResult); + resolveArray.forEach((resolveResult2) => { + Cache.remove(resolveResult2.src); + }); + await this.loader.unload(resolveArray); + } + get detections() { + return this._detections; + } + get preferWorkers() { + return loadTextures.config.preferWorkers; + } + set preferWorkers(value) { + deprecation$1("7.2.0", "Assets.prefersWorkers is deprecated, use Assets.setPreferences({ preferWorkers: true }) instead."); + this.setPreferences({ preferWorkers: value }); + } + setPreferences(preferences) { + this.loader.parsers.forEach((parser) => { + if (!parser.config) + return; + Object.keys(parser.config).filter((key) => key in preferences).forEach((key) => { + parser.config[key] = preferences[key]; + }); + }); + } + } + const Assets = new AssetsClass(); + extensions$1.handleByList(ExtensionType.LoadParser, Assets.loader.parsers).handleByList(ExtensionType.ResolveParser, Assets.resolver.parsers).handleByList(ExtensionType.CacheParser, Assets.cache.parsers).handleByList(ExtensionType.DetectionParser, Assets.detections); + + const cacheTextureArray = { + extension: ExtensionType.CacheParser, + test: (asset) => Array.isArray(asset) && asset.every((t) => t instanceof Texture), + getCacheableAssets: (keys, asset) => { + const out = {}; + keys.forEach((key) => { + asset.forEach((item, i) => { + out[key + (i === 0 ? "" : i + 1)] = item; + }); + }); + return out; + } + }; + extensions$1.add(cacheTextureArray); + + const detectAvif = { + extension: { + type: ExtensionType.DetectionParser, + priority: 1 + }, + test: async () => { + if (!globalThis.createImageBitmap) + return false; + const avifData = "data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A="; + const blob = await settings.ADAPTER.fetch(avifData).then((r) => r.blob()); + return createImageBitmap(blob).then(() => true, () => false); + }, + add: async (formats) => [...formats, "avif"], + remove: async (formats) => formats.filter((f) => f !== "avif") + }; + extensions$1.add(detectAvif); + + const detectWebp = { + extension: { + type: ExtensionType.DetectionParser, + priority: 0 + }, + test: async () => { + if (!globalThis.createImageBitmap) + return false; + const webpData = "data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA="; + const blob = await settings.ADAPTER.fetch(webpData).then((r) => r.blob()); + return createImageBitmap(blob).then(() => true, () => false); + }, + add: async (formats) => [...formats, "webp"], + remove: async (formats) => formats.filter((f) => f !== "webp") + }; + extensions$1.add(detectWebp); + + const imageFormats = ["png", "jpg", "jpeg"]; + const detectDefaults = { + extension: { + type: ExtensionType.DetectionParser, + priority: -1 + }, + test: () => Promise.resolve(true), + add: async (formats) => [...formats, ...imageFormats], + remove: async (formats) => formats.filter((f) => !imageFormats.includes(f)) + }; + extensions$1.add(detectDefaults); + + const resolveTextureUrl = { + extension: ExtensionType.ResolveParser, + test: loadTextures.test, + parse: (value) => ({ + resolution: parseFloat(settings.RETINA_PREFIX.exec(value)?.[1] ?? "1"), + format: value.split(".").pop(), + src: value + }) + }; + extensions$1.add(resolveTextureUrl); + + var INTERNAL_FORMATS = /* @__PURE__ */ ((INTERNAL_FORMATS2) => { + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_RGB_S3TC_DXT1_EXT"] = 33776] = "COMPRESSED_RGB_S3TC_DXT1_EXT"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_RGBA_S3TC_DXT1_EXT"] = 33777] = "COMPRESSED_RGBA_S3TC_DXT1_EXT"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_RGBA_S3TC_DXT3_EXT"] = 33778] = "COMPRESSED_RGBA_S3TC_DXT3_EXT"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_RGBA_S3TC_DXT5_EXT"] = 33779] = "COMPRESSED_RGBA_S3TC_DXT5_EXT"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"] = 35917] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"] = 35918] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"] = 35919] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_SRGB_S3TC_DXT1_EXT"] = 35916] = "COMPRESSED_SRGB_S3TC_DXT1_EXT"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_R11_EAC"] = 37488] = "COMPRESSED_R11_EAC"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_SIGNED_R11_EAC"] = 37489] = "COMPRESSED_SIGNED_R11_EAC"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_RG11_EAC"] = 37490] = "COMPRESSED_RG11_EAC"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_SIGNED_RG11_EAC"] = 37491] = "COMPRESSED_SIGNED_RG11_EAC"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_RGB8_ETC2"] = 37492] = "COMPRESSED_RGB8_ETC2"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_RGBA8_ETC2_EAC"] = 37496] = "COMPRESSED_RGBA8_ETC2_EAC"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_SRGB8_ETC2"] = 37493] = "COMPRESSED_SRGB8_ETC2"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"] = 37497] = "COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37494] = "COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37495] = "COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_RGB_PVRTC_4BPPV1_IMG"] = 35840] = "COMPRESSED_RGB_PVRTC_4BPPV1_IMG"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"] = 35842] = "COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_RGB_PVRTC_2BPPV1_IMG"] = 35841] = "COMPRESSED_RGB_PVRTC_2BPPV1_IMG"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"] = 35843] = "COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_RGB_ETC1_WEBGL"] = 36196] = "COMPRESSED_RGB_ETC1_WEBGL"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_RGB_ATC_WEBGL"] = 35986] = "COMPRESSED_RGB_ATC_WEBGL"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL"] = 35986] = "COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL"] = 34798] = "COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL"; + INTERNAL_FORMATS2[INTERNAL_FORMATS2["COMPRESSED_RGBA_ASTC_4x4_KHR"] = 37808] = "COMPRESSED_RGBA_ASTC_4x4_KHR"; + return INTERNAL_FORMATS2; + })(INTERNAL_FORMATS || {}); + const INTERNAL_FORMAT_TO_BYTES_PER_PIXEL = { + [33776 /* COMPRESSED_RGB_S3TC_DXT1_EXT */]: 0.5, + [33777 /* COMPRESSED_RGBA_S3TC_DXT1_EXT */]: 0.5, + [33778 /* COMPRESSED_RGBA_S3TC_DXT3_EXT */]: 1, + [33779 /* COMPRESSED_RGBA_S3TC_DXT5_EXT */]: 1, + [35916 /* COMPRESSED_SRGB_S3TC_DXT1_EXT */]: 0.5, + [35917 /* COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT */]: 0.5, + [35918 /* COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT */]: 1, + [35919 /* COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT */]: 1, + [37488 /* COMPRESSED_R11_EAC */]: 0.5, + [37489 /* COMPRESSED_SIGNED_R11_EAC */]: 0.5, + [37490 /* COMPRESSED_RG11_EAC */]: 1, + [37491 /* COMPRESSED_SIGNED_RG11_EAC */]: 1, + [37492 /* COMPRESSED_RGB8_ETC2 */]: 0.5, + [37496 /* COMPRESSED_RGBA8_ETC2_EAC */]: 1, + [37493 /* COMPRESSED_SRGB8_ETC2 */]: 0.5, + [37497 /* COMPRESSED_SRGB8_ALPHA8_ETC2_EAC */]: 1, + [37494 /* COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 */]: 0.5, + [37495 /* COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 */]: 0.5, + [35840 /* COMPRESSED_RGB_PVRTC_4BPPV1_IMG */]: 0.5, + [35842 /* COMPRESSED_RGBA_PVRTC_4BPPV1_IMG */]: 0.5, + [35841 /* COMPRESSED_RGB_PVRTC_2BPPV1_IMG */]: 0.25, + [35843 /* COMPRESSED_RGBA_PVRTC_2BPPV1_IMG */]: 0.25, + [36196 /* COMPRESSED_RGB_ETC1_WEBGL */]: 0.5, + [35986 /* COMPRESSED_RGB_ATC_WEBGL */]: 0.5, + [35986 /* COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL */]: 1, + [34798 /* COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL */]: 1, + [37808 /* COMPRESSED_RGBA_ASTC_4x4_KHR */]: 1 + }; + + let storedGl; + let extensions; + function getCompressedTextureExtensions() { + extensions = { + s3tc: storedGl.getExtension("WEBGL_compressed_texture_s3tc"), + s3tc_sRGB: storedGl.getExtension("WEBGL_compressed_texture_s3tc_srgb"), + etc: storedGl.getExtension("WEBGL_compressed_texture_etc"), + etc1: storedGl.getExtension("WEBGL_compressed_texture_etc1"), + pvrtc: storedGl.getExtension("WEBGL_compressed_texture_pvrtc") || storedGl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"), + atc: storedGl.getExtension("WEBGL_compressed_texture_atc"), + astc: storedGl.getExtension("WEBGL_compressed_texture_astc") + }; + } + const detectCompressedTextures = { + extension: { + type: ExtensionType.DetectionParser, + priority: 2 + }, + test: async () => { + const canvas = settings.ADAPTER.createCanvas(); + const gl = canvas.getContext("webgl"); + if (!gl) { + console.warn("WebGL not available for compressed textures."); + return false; + } + storedGl = gl; + return true; + }, + add: async (formats) => { + if (!extensions) + getCompressedTextureExtensions(); + const textureFormats = []; + for (const extensionName in extensions) { + const extension = extensions[extensionName]; + if (!extension) { + continue; + } + textureFormats.push(extensionName); + } + return [...textureFormats, ...formats]; + }, + remove: async (formats) => { + if (!extensions) + getCompressedTextureExtensions(); + return formats.filter((f) => !(f in extensions)); + } + }; + extensions$1.add(detectCompressedTextures); + + class BlobResource extends BufferResource { + constructor(source, options = { width: 1, height: 1, autoLoad: true }) { + let origin; + let data; + if (typeof source === "string") { + origin = source; + data = new Uint8Array(); + } else { + origin = null; + data = source; + } + super(data, options); + this.origin = origin; + this.buffer = data ? new ViewableBuffer(data) : null; + this._load = null; + this.loaded = false; + if (this.origin !== null && options.autoLoad !== false) { + this.load(); + } + if (this.origin === null && this.buffer) { + this._load = Promise.resolve(this); + this.loaded = true; + this.onBlobLoaded(this.buffer.rawBinaryData); + } + } + onBlobLoaded(_data) { + } + load() { + if (this._load) { + return this._load; + } + this._load = fetch(this.origin).then((response) => response.blob()).then((blob) => blob.arrayBuffer()).then((arrayBuffer) => { + this.data = new Uint32Array(arrayBuffer); + this.buffer = new ViewableBuffer(arrayBuffer); + this.loaded = true; + this.onBlobLoaded(arrayBuffer); + this.update(); + return this; + }); + return this._load; + } + } + + class CompressedTextureResource extends BlobResource { + constructor(source, options) { + super(source, options); + this.format = options.format; + this.levels = options.levels || 1; + this._width = options.width; + this._height = options.height; + this._extension = CompressedTextureResource._formatToExtension(this.format); + if (options.levelBuffers || this.buffer) { + this._levelBuffers = options.levelBuffers || CompressedTextureResource._createLevelBuffers(source instanceof Uint8Array ? source : this.buffer.uint8View, this.format, this.levels, 4, 4, this.width, this.height); + } + } + upload(renderer, _texture, _glTexture) { + const gl = renderer.gl; + const extension = renderer.context.extensions[this._extension]; + if (!extension) { + throw new Error(`${this._extension} textures are not supported on the current machine`); + } + if (!this._levelBuffers) { + return false; + } + for (let i = 0, j = this.levels; i < j; i++) { + const { levelID, levelWidth, levelHeight, levelBuffer } = this._levelBuffers[i]; + gl.compressedTexImage2D(gl.TEXTURE_2D, levelID, this.format, levelWidth, levelHeight, 0, levelBuffer); + } + return true; + } + onBlobLoaded() { + this._levelBuffers = CompressedTextureResource._createLevelBuffers(this.buffer.uint8View, this.format, this.levels, 4, 4, this.width, this.height); + } + static _formatToExtension(format) { + if (format >= 33776 && format <= 33779) { + return "s3tc"; + } else if (format >= 37488 && format <= 37497) { + return "etc"; + } else if (format >= 35840 && format <= 35843) { + return "pvrtc"; + } else if (format >= 36196) { + return "etc1"; + } else if (format >= 35986 && format <= 34798) { + return "atc"; + } + throw new Error("Invalid (compressed) texture format given!"); + } + static _createLevelBuffers(buffer, format, levels, blockWidth, blockHeight, imageWidth, imageHeight) { + const buffers = new Array(levels); + let offset = buffer.byteOffset; + let levelWidth = imageWidth; + let levelHeight = imageHeight; + let alignedLevelWidth = levelWidth + blockWidth - 1 & ~(blockWidth - 1); + let alignedLevelHeight = levelHeight + blockHeight - 1 & ~(blockHeight - 1); + let levelSize = alignedLevelWidth * alignedLevelHeight * INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[format]; + for (let i = 0; i < levels; i++) { + buffers[i] = { + levelID: i, + levelWidth: levels > 1 ? levelWidth : alignedLevelWidth, + levelHeight: levels > 1 ? levelHeight : alignedLevelHeight, + levelBuffer: new Uint8Array(buffer.buffer, offset, levelSize) + }; + offset += levelSize; + levelWidth = levelWidth >> 1 || 1; + levelHeight = levelHeight >> 1 || 1; + alignedLevelWidth = levelWidth + blockWidth - 1 & ~(blockWidth - 1); + alignedLevelHeight = levelHeight + blockHeight - 1 & ~(blockHeight - 1); + levelSize = alignedLevelWidth * alignedLevelHeight * INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[format]; + } + return buffers; + } + } + + const DDS_MAGIC_SIZE = 4; + const DDS_HEADER_SIZE = 124; + const DDS_HEADER_PF_SIZE = 32; + const DDS_HEADER_DX10_SIZE = 20; + const DDS_MAGIC = 542327876; + const DDS_FIELDS = { + SIZE: 1, + FLAGS: 2, + HEIGHT: 3, + WIDTH: 4, + MIPMAP_COUNT: 7, + PIXEL_FORMAT: 19 + }; + const DDS_PF_FIELDS = { + SIZE: 0, + FLAGS: 1, + FOURCC: 2, + RGB_BITCOUNT: 3, + R_BIT_MASK: 4, + G_BIT_MASK: 5, + B_BIT_MASK: 6, + A_BIT_MASK: 7 + }; + const DDS_DX10_FIELDS = { + DXGI_FORMAT: 0, + RESOURCE_DIMENSION: 1, + MISC_FLAG: 2, + ARRAY_SIZE: 3, + MISC_FLAGS2: 4 + }; + var DXGI_FORMAT = /* @__PURE__ */ ((DXGI_FORMAT2) => { + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_UNKNOWN"] = 0] = "DXGI_FORMAT_UNKNOWN"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R32G32B32A32_TYPELESS"] = 1] = "DXGI_FORMAT_R32G32B32A32_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R32G32B32A32_FLOAT"] = 2] = "DXGI_FORMAT_R32G32B32A32_FLOAT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R32G32B32A32_UINT"] = 3] = "DXGI_FORMAT_R32G32B32A32_UINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R32G32B32A32_SINT"] = 4] = "DXGI_FORMAT_R32G32B32A32_SINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R32G32B32_TYPELESS"] = 5] = "DXGI_FORMAT_R32G32B32_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R32G32B32_FLOAT"] = 6] = "DXGI_FORMAT_R32G32B32_FLOAT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R32G32B32_UINT"] = 7] = "DXGI_FORMAT_R32G32B32_UINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R32G32B32_SINT"] = 8] = "DXGI_FORMAT_R32G32B32_SINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R16G16B16A16_TYPELESS"] = 9] = "DXGI_FORMAT_R16G16B16A16_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R16G16B16A16_FLOAT"] = 10] = "DXGI_FORMAT_R16G16B16A16_FLOAT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R16G16B16A16_UNORM"] = 11] = "DXGI_FORMAT_R16G16B16A16_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R16G16B16A16_UINT"] = 12] = "DXGI_FORMAT_R16G16B16A16_UINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R16G16B16A16_SNORM"] = 13] = "DXGI_FORMAT_R16G16B16A16_SNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R16G16B16A16_SINT"] = 14] = "DXGI_FORMAT_R16G16B16A16_SINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R32G32_TYPELESS"] = 15] = "DXGI_FORMAT_R32G32_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R32G32_FLOAT"] = 16] = "DXGI_FORMAT_R32G32_FLOAT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R32G32_UINT"] = 17] = "DXGI_FORMAT_R32G32_UINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R32G32_SINT"] = 18] = "DXGI_FORMAT_R32G32_SINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R32G8X24_TYPELESS"] = 19] = "DXGI_FORMAT_R32G8X24_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_D32_FLOAT_S8X24_UINT"] = 20] = "DXGI_FORMAT_D32_FLOAT_S8X24_UINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS"] = 21] = "DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_X32_TYPELESS_G8X24_UINT"] = 22] = "DXGI_FORMAT_X32_TYPELESS_G8X24_UINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R10G10B10A2_TYPELESS"] = 23] = "DXGI_FORMAT_R10G10B10A2_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R10G10B10A2_UNORM"] = 24] = "DXGI_FORMAT_R10G10B10A2_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R10G10B10A2_UINT"] = 25] = "DXGI_FORMAT_R10G10B10A2_UINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R11G11B10_FLOAT"] = 26] = "DXGI_FORMAT_R11G11B10_FLOAT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R8G8B8A8_TYPELESS"] = 27] = "DXGI_FORMAT_R8G8B8A8_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R8G8B8A8_UNORM"] = 28] = "DXGI_FORMAT_R8G8B8A8_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R8G8B8A8_UNORM_SRGB"] = 29] = "DXGI_FORMAT_R8G8B8A8_UNORM_SRGB"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R8G8B8A8_UINT"] = 30] = "DXGI_FORMAT_R8G8B8A8_UINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R8G8B8A8_SNORM"] = 31] = "DXGI_FORMAT_R8G8B8A8_SNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R8G8B8A8_SINT"] = 32] = "DXGI_FORMAT_R8G8B8A8_SINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R16G16_TYPELESS"] = 33] = "DXGI_FORMAT_R16G16_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R16G16_FLOAT"] = 34] = "DXGI_FORMAT_R16G16_FLOAT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R16G16_UNORM"] = 35] = "DXGI_FORMAT_R16G16_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R16G16_UINT"] = 36] = "DXGI_FORMAT_R16G16_UINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R16G16_SNORM"] = 37] = "DXGI_FORMAT_R16G16_SNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R16G16_SINT"] = 38] = "DXGI_FORMAT_R16G16_SINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R32_TYPELESS"] = 39] = "DXGI_FORMAT_R32_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_D32_FLOAT"] = 40] = "DXGI_FORMAT_D32_FLOAT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R32_FLOAT"] = 41] = "DXGI_FORMAT_R32_FLOAT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R32_UINT"] = 42] = "DXGI_FORMAT_R32_UINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R32_SINT"] = 43] = "DXGI_FORMAT_R32_SINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R24G8_TYPELESS"] = 44] = "DXGI_FORMAT_R24G8_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_D24_UNORM_S8_UINT"] = 45] = "DXGI_FORMAT_D24_UNORM_S8_UINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R24_UNORM_X8_TYPELESS"] = 46] = "DXGI_FORMAT_R24_UNORM_X8_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_X24_TYPELESS_G8_UINT"] = 47] = "DXGI_FORMAT_X24_TYPELESS_G8_UINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R8G8_TYPELESS"] = 48] = "DXGI_FORMAT_R8G8_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R8G8_UNORM"] = 49] = "DXGI_FORMAT_R8G8_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R8G8_UINT"] = 50] = "DXGI_FORMAT_R8G8_UINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R8G8_SNORM"] = 51] = "DXGI_FORMAT_R8G8_SNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R8G8_SINT"] = 52] = "DXGI_FORMAT_R8G8_SINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R16_TYPELESS"] = 53] = "DXGI_FORMAT_R16_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R16_FLOAT"] = 54] = "DXGI_FORMAT_R16_FLOAT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_D16_UNORM"] = 55] = "DXGI_FORMAT_D16_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R16_UNORM"] = 56] = "DXGI_FORMAT_R16_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R16_UINT"] = 57] = "DXGI_FORMAT_R16_UINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R16_SNORM"] = 58] = "DXGI_FORMAT_R16_SNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R16_SINT"] = 59] = "DXGI_FORMAT_R16_SINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R8_TYPELESS"] = 60] = "DXGI_FORMAT_R8_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R8_UNORM"] = 61] = "DXGI_FORMAT_R8_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R8_UINT"] = 62] = "DXGI_FORMAT_R8_UINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R8_SNORM"] = 63] = "DXGI_FORMAT_R8_SNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R8_SINT"] = 64] = "DXGI_FORMAT_R8_SINT"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_A8_UNORM"] = 65] = "DXGI_FORMAT_A8_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R1_UNORM"] = 66] = "DXGI_FORMAT_R1_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R9G9B9E5_SHAREDEXP"] = 67] = "DXGI_FORMAT_R9G9B9E5_SHAREDEXP"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R8G8_B8G8_UNORM"] = 68] = "DXGI_FORMAT_R8G8_B8G8_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_G8R8_G8B8_UNORM"] = 69] = "DXGI_FORMAT_G8R8_G8B8_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC1_TYPELESS"] = 70] = "DXGI_FORMAT_BC1_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC1_UNORM"] = 71] = "DXGI_FORMAT_BC1_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC1_UNORM_SRGB"] = 72] = "DXGI_FORMAT_BC1_UNORM_SRGB"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC2_TYPELESS"] = 73] = "DXGI_FORMAT_BC2_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC2_UNORM"] = 74] = "DXGI_FORMAT_BC2_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC2_UNORM_SRGB"] = 75] = "DXGI_FORMAT_BC2_UNORM_SRGB"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC3_TYPELESS"] = 76] = "DXGI_FORMAT_BC3_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC3_UNORM"] = 77] = "DXGI_FORMAT_BC3_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC3_UNORM_SRGB"] = 78] = "DXGI_FORMAT_BC3_UNORM_SRGB"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC4_TYPELESS"] = 79] = "DXGI_FORMAT_BC4_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC4_UNORM"] = 80] = "DXGI_FORMAT_BC4_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC4_SNORM"] = 81] = "DXGI_FORMAT_BC4_SNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC5_TYPELESS"] = 82] = "DXGI_FORMAT_BC5_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC5_UNORM"] = 83] = "DXGI_FORMAT_BC5_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC5_SNORM"] = 84] = "DXGI_FORMAT_BC5_SNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_B5G6R5_UNORM"] = 85] = "DXGI_FORMAT_B5G6R5_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_B5G5R5A1_UNORM"] = 86] = "DXGI_FORMAT_B5G5R5A1_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_B8G8R8A8_UNORM"] = 87] = "DXGI_FORMAT_B8G8R8A8_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_B8G8R8X8_UNORM"] = 88] = "DXGI_FORMAT_B8G8R8X8_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM"] = 89] = "DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_B8G8R8A8_TYPELESS"] = 90] = "DXGI_FORMAT_B8G8R8A8_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_B8G8R8A8_UNORM_SRGB"] = 91] = "DXGI_FORMAT_B8G8R8A8_UNORM_SRGB"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_B8G8R8X8_TYPELESS"] = 92] = "DXGI_FORMAT_B8G8R8X8_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_B8G8R8X8_UNORM_SRGB"] = 93] = "DXGI_FORMAT_B8G8R8X8_UNORM_SRGB"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC6H_TYPELESS"] = 94] = "DXGI_FORMAT_BC6H_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC6H_UF16"] = 95] = "DXGI_FORMAT_BC6H_UF16"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC6H_SF16"] = 96] = "DXGI_FORMAT_BC6H_SF16"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC7_TYPELESS"] = 97] = "DXGI_FORMAT_BC7_TYPELESS"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC7_UNORM"] = 98] = "DXGI_FORMAT_BC7_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_BC7_UNORM_SRGB"] = 99] = "DXGI_FORMAT_BC7_UNORM_SRGB"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_AYUV"] = 100] = "DXGI_FORMAT_AYUV"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_Y410"] = 101] = "DXGI_FORMAT_Y410"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_Y416"] = 102] = "DXGI_FORMAT_Y416"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_NV12"] = 103] = "DXGI_FORMAT_NV12"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_P010"] = 104] = "DXGI_FORMAT_P010"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_P016"] = 105] = "DXGI_FORMAT_P016"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_420_OPAQUE"] = 106] = "DXGI_FORMAT_420_OPAQUE"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_YUY2"] = 107] = "DXGI_FORMAT_YUY2"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_Y210"] = 108] = "DXGI_FORMAT_Y210"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_Y216"] = 109] = "DXGI_FORMAT_Y216"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_NV11"] = 110] = "DXGI_FORMAT_NV11"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_AI44"] = 111] = "DXGI_FORMAT_AI44"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_IA44"] = 112] = "DXGI_FORMAT_IA44"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_P8"] = 113] = "DXGI_FORMAT_P8"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_A8P8"] = 114] = "DXGI_FORMAT_A8P8"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_B4G4R4A4_UNORM"] = 115] = "DXGI_FORMAT_B4G4R4A4_UNORM"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_P208"] = 116] = "DXGI_FORMAT_P208"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_V208"] = 117] = "DXGI_FORMAT_V208"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_V408"] = 118] = "DXGI_FORMAT_V408"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE"] = 119] = "DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE"] = 120] = "DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE"; + DXGI_FORMAT2[DXGI_FORMAT2["DXGI_FORMAT_FORCE_UINT"] = 121] = "DXGI_FORMAT_FORCE_UINT"; + return DXGI_FORMAT2; + })(DXGI_FORMAT || {}); + var D3D10_RESOURCE_DIMENSION = /* @__PURE__ */ ((D3D10_RESOURCE_DIMENSION2) => { + D3D10_RESOURCE_DIMENSION2[D3D10_RESOURCE_DIMENSION2["DDS_DIMENSION_TEXTURE1D"] = 2] = "DDS_DIMENSION_TEXTURE1D"; + D3D10_RESOURCE_DIMENSION2[D3D10_RESOURCE_DIMENSION2["DDS_DIMENSION_TEXTURE2D"] = 3] = "DDS_DIMENSION_TEXTURE2D"; + D3D10_RESOURCE_DIMENSION2[D3D10_RESOURCE_DIMENSION2["DDS_DIMENSION_TEXTURE3D"] = 6] = "DDS_DIMENSION_TEXTURE3D"; + return D3D10_RESOURCE_DIMENSION2; + })(D3D10_RESOURCE_DIMENSION || {}); + const PF_FLAGS = 1; + const DDPF_ALPHA = 2; + const DDPF_FOURCC = 4; + const DDPF_RGB = 64; + const DDPF_YUV = 512; + const DDPF_LUMINANCE = 131072; + const FOURCC_DXT1 = 827611204; + const FOURCC_DXT3 = 861165636; + const FOURCC_DXT5 = 894720068; + const FOURCC_DX10 = 808540228; + const DDS_RESOURCE_MISC_TEXTURECUBE = 4; + const FOURCC_TO_FORMAT = { + [FOURCC_DXT1]: INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT, + [FOURCC_DXT3]: INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT, + [FOURCC_DXT5]: INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT + }; + const DXGI_TO_FORMAT = { + [70 /* DXGI_FORMAT_BC1_TYPELESS */]: INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT, + [71 /* DXGI_FORMAT_BC1_UNORM */]: INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT, + [73 /* DXGI_FORMAT_BC2_TYPELESS */]: INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT, + [74 /* DXGI_FORMAT_BC2_UNORM */]: INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT, + [76 /* DXGI_FORMAT_BC3_TYPELESS */]: INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT, + [77 /* DXGI_FORMAT_BC3_UNORM */]: INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT, + [72 /* DXGI_FORMAT_BC1_UNORM_SRGB */]: INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, + [75 /* DXGI_FORMAT_BC2_UNORM_SRGB */]: INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, + [78 /* DXGI_FORMAT_BC3_UNORM_SRGB */]: INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT + }; + function parseDDS(arrayBuffer) { + const data = new Uint32Array(arrayBuffer); + const magicWord = data[0]; + if (magicWord !== DDS_MAGIC) { + throw new Error("Invalid DDS file magic word"); + } + const header = new Uint32Array(arrayBuffer, 0, DDS_HEADER_SIZE / Uint32Array.BYTES_PER_ELEMENT); + const height = header[DDS_FIELDS.HEIGHT]; + const width = header[DDS_FIELDS.WIDTH]; + const mipmapCount = header[DDS_FIELDS.MIPMAP_COUNT]; + const pixelFormat = new Uint32Array(arrayBuffer, DDS_FIELDS.PIXEL_FORMAT * Uint32Array.BYTES_PER_ELEMENT, DDS_HEADER_PF_SIZE / Uint32Array.BYTES_PER_ELEMENT); + const formatFlags = pixelFormat[PF_FLAGS]; + if (formatFlags & DDPF_FOURCC) { + const fourCC = pixelFormat[DDS_PF_FIELDS.FOURCC]; + if (fourCC !== FOURCC_DX10) { + const internalFormat2 = FOURCC_TO_FORMAT[fourCC]; + const dataOffset2 = DDS_MAGIC_SIZE + DDS_HEADER_SIZE; + const texData = new Uint8Array(arrayBuffer, dataOffset2); + const resource = new CompressedTextureResource(texData, { + format: internalFormat2, + width, + height, + levels: mipmapCount + }); + return [resource]; + } + const dx10Offset = DDS_MAGIC_SIZE + DDS_HEADER_SIZE; + const dx10Header = new Uint32Array(data.buffer, dx10Offset, DDS_HEADER_DX10_SIZE / Uint32Array.BYTES_PER_ELEMENT); + const dxgiFormat = dx10Header[DDS_DX10_FIELDS.DXGI_FORMAT]; + const resourceDimension = dx10Header[DDS_DX10_FIELDS.RESOURCE_DIMENSION]; + const miscFlag = dx10Header[DDS_DX10_FIELDS.MISC_FLAG]; + const arraySize = dx10Header[DDS_DX10_FIELDS.ARRAY_SIZE]; + const internalFormat = DXGI_TO_FORMAT[dxgiFormat]; + if (internalFormat === void 0) { + throw new Error(`DDSParser cannot parse texture data with DXGI format ${dxgiFormat}`); + } + if (miscFlag === DDS_RESOURCE_MISC_TEXTURECUBE) { + throw new Error("DDSParser does not support cubemap textures"); + } + if (resourceDimension === 6 /* DDS_DIMENSION_TEXTURE3D */) { + throw new Error("DDSParser does not supported 3D texture data"); + } + const imageBuffers = new Array(); + const dataOffset = DDS_MAGIC_SIZE + DDS_HEADER_SIZE + DDS_HEADER_DX10_SIZE; + if (arraySize === 1) { + imageBuffers.push(new Uint8Array(arrayBuffer, dataOffset)); + } else { + const pixelSize = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[internalFormat]; + let imageSize = 0; + let levelWidth = width; + let levelHeight = height; + for (let i = 0; i < mipmapCount; i++) { + const alignedLevelWidth = Math.max(1, levelWidth + 3 & ~3); + const alignedLevelHeight = Math.max(1, levelHeight + 3 & ~3); + const levelSize = alignedLevelWidth * alignedLevelHeight * pixelSize; + imageSize += levelSize; + levelWidth = levelWidth >>> 1; + levelHeight = levelHeight >>> 1; + } + let imageOffset = dataOffset; + for (let i = 0; i < arraySize; i++) { + imageBuffers.push(new Uint8Array(arrayBuffer, imageOffset, imageSize)); + imageOffset += imageSize; + } + } + return imageBuffers.map((buffer) => new CompressedTextureResource(buffer, { + format: internalFormat, + width, + height, + levels: mipmapCount + })); + } + if (formatFlags & DDPF_RGB) { + throw new Error("DDSParser does not support uncompressed texture data."); + } + if (formatFlags & DDPF_YUV) { + throw new Error("DDSParser does not supported YUV uncompressed texture data."); + } + if (formatFlags & DDPF_LUMINANCE) { + throw new Error("DDSParser does not support single-channel (lumninance) texture data!"); + } + if (formatFlags & DDPF_ALPHA) { + throw new Error("DDSParser does not support single-channel (alpha) texture data!"); + } + throw new Error("DDSParser failed to load a texture file due to an unknown reason!"); + } + + const FILE_IDENTIFIER = [171, 75, 84, 88, 32, 49, 49, 187, 13, 10, 26, 10]; + const ENDIANNESS = 67305985; + const KTX_FIELDS = { + FILE_IDENTIFIER: 0, + ENDIANNESS: 12, + GL_TYPE: 16, + GL_TYPE_SIZE: 20, + GL_FORMAT: 24, + GL_INTERNAL_FORMAT: 28, + GL_BASE_INTERNAL_FORMAT: 32, + PIXEL_WIDTH: 36, + PIXEL_HEIGHT: 40, + PIXEL_DEPTH: 44, + NUMBER_OF_ARRAY_ELEMENTS: 48, + NUMBER_OF_FACES: 52, + NUMBER_OF_MIPMAP_LEVELS: 56, + BYTES_OF_KEY_VALUE_DATA: 60 + }; + const FILE_HEADER_SIZE = 64; + const TYPES_TO_BYTES_PER_COMPONENT = { + [TYPES.UNSIGNED_BYTE]: 1, + [TYPES.UNSIGNED_SHORT]: 2, + [TYPES.INT]: 4, + [TYPES.UNSIGNED_INT]: 4, + [TYPES.FLOAT]: 4, + [TYPES.HALF_FLOAT]: 8 + }; + const FORMATS_TO_COMPONENTS = { + [FORMATS.RGBA]: 4, + [FORMATS.RGB]: 3, + [FORMATS.RG]: 2, + [FORMATS.RED]: 1, + [FORMATS.LUMINANCE]: 1, + [FORMATS.LUMINANCE_ALPHA]: 2, + [FORMATS.ALPHA]: 1 + }; + const TYPES_TO_BYTES_PER_PIXEL = { + [TYPES.UNSIGNED_SHORT_4_4_4_4]: 2, + [TYPES.UNSIGNED_SHORT_5_5_5_1]: 2, + [TYPES.UNSIGNED_SHORT_5_6_5]: 2 + }; + function parseKTX(url, arrayBuffer, loadKeyValueData = false) { + const dataView = new DataView(arrayBuffer); + if (!validate(url, dataView)) { + return null; + } + const littleEndian = dataView.getUint32(KTX_FIELDS.ENDIANNESS, true) === ENDIANNESS; + const glType = dataView.getUint32(KTX_FIELDS.GL_TYPE, littleEndian); + const glFormat = dataView.getUint32(KTX_FIELDS.GL_FORMAT, littleEndian); + const glInternalFormat = dataView.getUint32(KTX_FIELDS.GL_INTERNAL_FORMAT, littleEndian); + const pixelWidth = dataView.getUint32(KTX_FIELDS.PIXEL_WIDTH, littleEndian); + const pixelHeight = dataView.getUint32(KTX_FIELDS.PIXEL_HEIGHT, littleEndian) || 1; + const pixelDepth = dataView.getUint32(KTX_FIELDS.PIXEL_DEPTH, littleEndian) || 1; + const numberOfArrayElements = dataView.getUint32(KTX_FIELDS.NUMBER_OF_ARRAY_ELEMENTS, littleEndian) || 1; + const numberOfFaces = dataView.getUint32(KTX_FIELDS.NUMBER_OF_FACES, littleEndian); + const numberOfMipmapLevels = dataView.getUint32(KTX_FIELDS.NUMBER_OF_MIPMAP_LEVELS, littleEndian); + const bytesOfKeyValueData = dataView.getUint32(KTX_FIELDS.BYTES_OF_KEY_VALUE_DATA, littleEndian); + if (pixelHeight === 0 || pixelDepth !== 1) { + throw new Error("Only 2D textures are supported"); + } + if (numberOfFaces !== 1) { + throw new Error("CubeTextures are not supported by KTXLoader yet!"); + } + if (numberOfArrayElements !== 1) { + throw new Error("WebGL does not support array textures"); + } + const blockWidth = 4; + const blockHeight = 4; + const alignedWidth = pixelWidth + 3 & ~3; + const alignedHeight = pixelHeight + 3 & ~3; + const imageBuffers = new Array(numberOfArrayElements); + let imagePixels = pixelWidth * pixelHeight; + if (glType === 0) { + imagePixels = alignedWidth * alignedHeight; + } + let imagePixelByteSize; + if (glType !== 0) { + if (TYPES_TO_BYTES_PER_COMPONENT[glType]) { + imagePixelByteSize = TYPES_TO_BYTES_PER_COMPONENT[glType] * FORMATS_TO_COMPONENTS[glFormat]; + } else { + imagePixelByteSize = TYPES_TO_BYTES_PER_PIXEL[glType]; + } + } else { + imagePixelByteSize = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[glInternalFormat]; + } + if (imagePixelByteSize === void 0) { + throw new Error("Unable to resolve the pixel format stored in the *.ktx file!"); + } + const kvData = loadKeyValueData ? parseKvData(dataView, bytesOfKeyValueData, littleEndian) : null; + const imageByteSize = imagePixels * imagePixelByteSize; + let mipByteSize = imageByteSize; + let mipWidth = pixelWidth; + let mipHeight = pixelHeight; + let alignedMipWidth = alignedWidth; + let alignedMipHeight = alignedHeight; + let imageOffset = FILE_HEADER_SIZE + bytesOfKeyValueData; + for (let mipmapLevel = 0; mipmapLevel < numberOfMipmapLevels; mipmapLevel++) { + const imageSize = dataView.getUint32(imageOffset, littleEndian); + let elementOffset = imageOffset + 4; + for (let arrayElement = 0; arrayElement < numberOfArrayElements; arrayElement++) { + let mips = imageBuffers[arrayElement]; + if (!mips) { + mips = imageBuffers[arrayElement] = new Array(numberOfMipmapLevels); + } + mips[mipmapLevel] = { + levelID: mipmapLevel, + levelWidth: numberOfMipmapLevels > 1 || glType !== 0 ? mipWidth : alignedMipWidth, + levelHeight: numberOfMipmapLevels > 1 || glType !== 0 ? mipHeight : alignedMipHeight, + levelBuffer: new Uint8Array(arrayBuffer, elementOffset, mipByteSize) + }; + elementOffset += mipByteSize; + } + imageOffset += imageSize + 4; + imageOffset = imageOffset % 4 !== 0 ? imageOffset + 4 - imageOffset % 4 : imageOffset; + mipWidth = mipWidth >> 1 || 1; + mipHeight = mipHeight >> 1 || 1; + alignedMipWidth = mipWidth + blockWidth - 1 & ~(blockWidth - 1); + alignedMipHeight = mipHeight + blockHeight - 1 & ~(blockHeight - 1); + mipByteSize = alignedMipWidth * alignedMipHeight * imagePixelByteSize; + } + if (glType !== 0) { + return { + uncompressed: imageBuffers.map((levelBuffers) => { + let buffer = levelBuffers[0].levelBuffer; + let convertToInt = false; + if (glType === TYPES.FLOAT) { + buffer = new Float32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4); + } else if (glType === TYPES.UNSIGNED_INT) { + convertToInt = true; + buffer = new Uint32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4); + } else if (glType === TYPES.INT) { + convertToInt = true; + buffer = new Int32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4); + } + return { + resource: new BufferResource(buffer, { + width: levelBuffers[0].levelWidth, + height: levelBuffers[0].levelHeight + }), + type: glType, + format: convertToInt ? convertFormatToInteger(glFormat) : glFormat + }; + }), + kvData + }; + } + return { + compressed: imageBuffers.map((levelBuffers) => new CompressedTextureResource(null, { + format: glInternalFormat, + width: pixelWidth, + height: pixelHeight, + levels: numberOfMipmapLevels, + levelBuffers + })), + kvData + }; + } + function validate(url, dataView) { + for (let i = 0; i < FILE_IDENTIFIER.length; i++) { + if (dataView.getUint8(i) !== FILE_IDENTIFIER[i]) { + console.error(`${url} is not a valid *.ktx file!`); + return false; + } + } + return true; + } + function convertFormatToInteger(format) { + switch (format) { + case FORMATS.RGBA: + return FORMATS.RGBA_INTEGER; + case FORMATS.RGB: + return FORMATS.RGB_INTEGER; + case FORMATS.RG: + return FORMATS.RG_INTEGER; + case FORMATS.RED: + return FORMATS.RED_INTEGER; + default: + return format; + } + } + function parseKvData(dataView, bytesOfKeyValueData, littleEndian) { + const kvData = /* @__PURE__ */ new Map(); + let bytesIntoKeyValueData = 0; + while (bytesIntoKeyValueData < bytesOfKeyValueData) { + const keyAndValueByteSize = dataView.getUint32(FILE_HEADER_SIZE + bytesIntoKeyValueData, littleEndian); + const keyAndValueByteOffset = FILE_HEADER_SIZE + bytesIntoKeyValueData + 4; + const valuePadding = 3 - (keyAndValueByteSize + 3) % 4; + if (keyAndValueByteSize === 0 || keyAndValueByteSize > bytesOfKeyValueData - bytesIntoKeyValueData) { + console.error("KTXLoader: keyAndValueByteSize out of bounds"); + break; + } + let keyNulByte = 0; + for (; keyNulByte < keyAndValueByteSize; keyNulByte++) { + if (dataView.getUint8(keyAndValueByteOffset + keyNulByte) === 0) { + break; + } + } + if (keyNulByte === -1) { + console.error("KTXLoader: Failed to find null byte terminating kvData key"); + break; + } + const key = new TextDecoder().decode(new Uint8Array(dataView.buffer, keyAndValueByteOffset, keyNulByte)); + const value = new DataView(dataView.buffer, keyAndValueByteOffset + keyNulByte + 1, keyAndValueByteSize - keyNulByte - 1); + kvData.set(key, value); + bytesIntoKeyValueData += 4 + keyAndValueByteSize + valuePadding; + } + return kvData; + } + + const loadDDS = { + extension: { + type: ExtensionType.LoadParser, + priority: LoaderParserPriority.High + }, + name: "loadDDS", + test(url) { + return checkExtension(url, ".dds"); + }, + async load(url, asset, loader) { + const response = await settings.ADAPTER.fetch(url); + const arrayBuffer = await response.arrayBuffer(); + const resources = parseDDS(arrayBuffer); + const textures = resources.map((resource) => { + const base = new BaseTexture(resource, { + mipmap: MIPMAP_MODES.OFF, + alphaMode: ALPHA_MODES.NO_PREMULTIPLIED_ALPHA, + resolution: getResolutionOfUrl(url), + ...asset.data + }); + return createTexture(base, loader, url); + }); + return textures.length === 1 ? textures[0] : textures; + }, + unload(texture) { + if (Array.isArray(texture)) { + texture.forEach((t) => t.destroy(true)); + } else { + texture.destroy(true); + } + } + }; + extensions$1.add(loadDDS); + + const loadKTX = { + extension: { + type: ExtensionType.LoadParser, + priority: LoaderParserPriority.High + }, + name: "loadKTX", + test(url) { + return checkExtension(url, ".ktx"); + }, + async load(url, asset, loader) { + const response = await settings.ADAPTER.fetch(url); + const arrayBuffer = await response.arrayBuffer(); + const { compressed, uncompressed, kvData } = parseKTX(url, arrayBuffer); + const resources = compressed ?? uncompressed; + const options = { + mipmap: MIPMAP_MODES.OFF, + alphaMode: ALPHA_MODES.NO_PREMULTIPLIED_ALPHA, + resolution: getResolutionOfUrl(url), + ...asset.data + }; + const textures = resources.map((resource) => { + if (resources === uncompressed) { + Object.assign(options, { + type: resource.type, + format: resource.format + }); + } + const base = new BaseTexture(resource, options); + base.ktxKeyValueData = kvData; + return createTexture(base, loader, url); + }); + return textures.length === 1 ? textures[0] : textures; + }, + unload(texture) { + if (Array.isArray(texture)) { + texture.forEach((t) => t.destroy(true)); + } else { + texture.destroy(true); + } + } + }; + extensions$1.add(loadKTX); + + const resolveCompressedTextureUrl = { + extension: ExtensionType.ResolveParser, + test: (value) => { + const temp = value.split("?")[0]; + const extension = temp.split(".").pop(); + return ["basis", "ktx", "dds"].includes(extension); + }, + parse: (value) => { + const temp = value.split("?")[0]; + const extension = temp.split(".").pop(); + if (extension === "ktx") { + const extensions2 = [ + ".s3tc.ktx", + ".s3tc_sRGB.ktx", + ".etc.ktx", + ".etc1.ktx", + ".pvrt.ktx", + ".atc.ktx", + ".astc.ktx" + ]; + if (extensions2.some((ext) => value.endsWith(ext))) { + return { + resolution: parseFloat(settings.RETINA_PREFIX.exec(value)?.[1] ?? "1"), + format: extensions2.find((ext) => value.endsWith(ext)), + src: value + }; + } + } + return { + resolution: parseFloat(settings.RETINA_PREFIX.exec(value)?.[1] ?? "1"), + format: value.split(".").pop(), + src: value + }; + } + }; + extensions$1.add(resolveCompressedTextureUrl); + + const TEMP_RECT$1 = new Rectangle(); + const BYTES_PER_PIXEL = 4; + const _Extract = class { + constructor(renderer) { + this.renderer = renderer; + } + async image(target, format, quality) { + const image = new Image(); + image.src = await this.base64(target, format, quality); + return image; + } + async base64(target, format, quality) { + const canvas = this.canvas(target); + if (canvas.toBlob !== void 0) { + return new Promise((resolve, reject) => { + canvas.toBlob((blob) => { + if (!blob) { + reject(new Error("ICanvas.toBlob failed!")); + return; + } + const reader = new FileReader(); + reader.onload = () => resolve(reader.result); + reader.onerror = reject; + reader.readAsDataURL(blob); + }, format, quality); + }); + } + if (canvas.toDataURL !== void 0) { + return canvas.toDataURL(format, quality); + } + if (canvas.convertToBlob !== void 0) { + const blob = await canvas.convertToBlob({ type: format, quality }); + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(reader.result); + reader.onerror = reject; + reader.readAsDataURL(blob); + }); + } + throw new Error("Extract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented"); + } + canvas(target, frame) { + const { pixels, width, height, flipY } = this._rawPixels(target, frame); + if (flipY) { + _Extract._flipY(pixels, width, height); + } + _Extract._unpremultiplyAlpha(pixels); + const canvasBuffer = new CanvasRenderTarget(width, height, 1); + const imageData = new ImageData(new Uint8ClampedArray(pixels.buffer), width, height); + canvasBuffer.context.putImageData(imageData, 0, 0); + return canvasBuffer.canvas; + } + pixels(target, frame) { + const { pixels, width, height, flipY } = this._rawPixels(target, frame); + if (flipY) { + _Extract._flipY(pixels, width, height); + } + _Extract._unpremultiplyAlpha(pixels); + return pixels; + } + _rawPixels(target, frame) { + const renderer = this.renderer; + if (!renderer) { + throw new Error("The Extract has already been destroyed"); + } + let resolution; + let flipY = false; + let renderTexture; + let generated = false; + if (target) { + if (target instanceof RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target, { + resolution: renderer.resolution, + multisample: renderer.multisample + }); + generated = true; + } + } + if (renderTexture) { + resolution = renderTexture.baseTexture.resolution; + frame = frame ?? renderTexture.frame; + flipY = false; + if (!generated) { + renderer.renderTexture.bind(renderTexture); + const fbo = renderTexture.framebuffer.glFramebuffers[renderer.CONTEXT_UID]; + if (fbo.blitFramebuffer) { + renderer.framebuffer.bind(fbo.blitFramebuffer); + } + } + } else { + resolution = renderer.resolution; + if (!frame) { + frame = TEMP_RECT$1; + frame.width = renderer.width / resolution; + frame.height = renderer.height / resolution; + } + flipY = true; + renderer.renderTexture.bind(); + } + const width = Math.round(frame.width * resolution); + const height = Math.round(frame.height * resolution); + const pixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + const gl = renderer.gl; + gl.readPixels(Math.round(frame.x * resolution), Math.round(frame.y * resolution), width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels); + if (generated) { + renderTexture?.destroy(true); + } + return { pixels, width, height, flipY }; + } + destroy() { + this.renderer = null; + } + static _flipY(pixels, width, height) { + const w = width << 2; + const h = height >> 1; + const temp = new Uint8Array(w); + for (let y = 0; y < h; y++) { + const t = y * w; + const b = (height - y - 1) * w; + temp.set(pixels.subarray(t, t + w)); + pixels.copyWithin(t, b, b + w); + pixels.set(temp, b); + } + } + static _unpremultiplyAlpha(pixels) { + if (pixels instanceof Uint8ClampedArray) { + pixels = new Uint8Array(pixels.buffer); + } + const n = pixels.length; + for (let i = 0; i < n; i += 4) { + const alpha = pixels[i + 3]; + if (alpha !== 0) { + const a = 255.001 / alpha; + pixels[i] = pixels[i] * a + 0.5; + pixels[i + 1] = pixels[i + 1] * a + 0.5; + pixels[i + 2] = pixels[i + 2] * a + 0.5; + } + } + } + }; + let Extract = _Extract; + Extract.extension = { + name: "extract", + type: ExtensionType.RendererSystem + }; + extensions$1.add(Extract); + + const buildCircle = { + build(graphicsData) { + const points = graphicsData.points; + let x; + let y; + let dx; + let dy; + let rx; + let ry; + if (graphicsData.type === SHAPES.CIRC) { + const circle = graphicsData.shape; + x = circle.x; + y = circle.y; + rx = ry = circle.radius; + dx = dy = 0; + } else if (graphicsData.type === SHAPES.ELIP) { + const ellipse = graphicsData.shape; + x = ellipse.x; + y = ellipse.y; + rx = ellipse.width; + ry = ellipse.height; + dx = dy = 0; + } else { + const roundedRect = graphicsData.shape; + const halfWidth = roundedRect.width / 2; + const halfHeight = roundedRect.height / 2; + x = roundedRect.x + halfWidth; + y = roundedRect.y + halfHeight; + rx = ry = Math.max(0, Math.min(roundedRect.radius, Math.min(halfWidth, halfHeight))); + dx = halfWidth - rx; + dy = halfHeight - ry; + } + if (!(rx >= 0 && ry >= 0 && dx >= 0 && dy >= 0)) { + points.length = 0; + return; + } + const n = Math.ceil(2.3 * Math.sqrt(rx + ry)); + const m = n * 8 + (dx ? 4 : 0) + (dy ? 4 : 0); + points.length = m; + if (m === 0) { + return; + } + if (n === 0) { + points.length = 8; + points[0] = points[6] = x + dx; + points[1] = points[3] = y + dy; + points[2] = points[4] = x - dx; + points[5] = points[7] = y - dy; + return; + } + let j1 = 0; + let j2 = n * 4 + (dx ? 2 : 0) + 2; + let j3 = j2; + let j4 = m; + { + const x0 = dx + rx; + const y0 = dy; + const x1 = x + x0; + const x2 = x - x0; + const y1 = y + y0; + points[j1++] = x1; + points[j1++] = y1; + points[--j2] = y1; + points[--j2] = x2; + if (dy) { + const y2 = y - y0; + points[j3++] = x2; + points[j3++] = y2; + points[--j4] = y2; + points[--j4] = x1; + } + } + for (let i = 1; i < n; i++) { + const a = Math.PI / 2 * (i / n); + const x0 = dx + Math.cos(a) * rx; + const y0 = dy + Math.sin(a) * ry; + const x1 = x + x0; + const x2 = x - x0; + const y1 = y + y0; + const y2 = y - y0; + points[j1++] = x1; + points[j1++] = y1; + points[--j2] = y1; + points[--j2] = x2; + points[j3++] = x2; + points[j3++] = y2; + points[--j4] = y2; + points[--j4] = x1; + } + { + const x0 = dx; + const y0 = dy + ry; + const x1 = x + x0; + const x2 = x - x0; + const y1 = y + y0; + const y2 = y - y0; + points[j1++] = x1; + points[j1++] = y1; + points[--j4] = y2; + points[--j4] = x1; + if (dx) { + points[j1++] = x2; + points[j1++] = y1; + points[--j4] = y2; + points[--j4] = x2; + } + } + }, + triangulate(graphicsData, graphicsGeometry) { + const points = graphicsData.points; + const verts = graphicsGeometry.points; + const indices = graphicsGeometry.indices; + if (points.length === 0) { + return; + } + let vertPos = verts.length / 2; + const center = vertPos; + let x; + let y; + if (graphicsData.type !== SHAPES.RREC) { + const circle = graphicsData.shape; + x = circle.x; + y = circle.y; + } else { + const roundedRect = graphicsData.shape; + x = roundedRect.x + roundedRect.width / 2; + y = roundedRect.y + roundedRect.height / 2; + } + const matrix = graphicsData.matrix; + verts.push(graphicsData.matrix ? matrix.a * x + matrix.c * y + matrix.tx : x, graphicsData.matrix ? matrix.b * x + matrix.d * y + matrix.ty : y); + vertPos++; + verts.push(points[0], points[1]); + for (let i = 2; i < points.length; i += 2) { + verts.push(points[i], points[i + 1]); + indices.push(vertPos++, center, vertPos); + } + indices.push(center + 1, center, vertPos); + } + }; + + function fixOrientation(points, hole = false) { + const m = points.length; + if (m < 6) { + return; + } + let area = 0; + for (let i = 0, x1 = points[m - 2], y1 = points[m - 1]; i < m; i += 2) { + const x2 = points[i]; + const y2 = points[i + 1]; + area += (x2 - x1) * (y2 + y1); + x1 = x2; + y1 = y2; + } + if (!hole && area > 0 || hole && area <= 0) { + const n = m / 2; + for (let i = n + n % 2; i < m; i += 2) { + const i1 = m - i - 2; + const i2 = m - i - 1; + const i3 = i; + const i4 = i + 1; + [points[i1], points[i3]] = [points[i3], points[i1]]; + [points[i2], points[i4]] = [points[i4], points[i2]]; + } + } + } + const buildPoly = { + build(graphicsData) { + graphicsData.points = graphicsData.shape.points.slice(); + }, + triangulate(graphicsData, graphicsGeometry) { + let points = graphicsData.points; + const holes = graphicsData.holes; + const verts = graphicsGeometry.points; + const indices = graphicsGeometry.indices; + if (points.length >= 6) { + fixOrientation(points, false); + const holeArray = []; + for (let i = 0; i < holes.length; i++) { + const hole = holes[i]; + fixOrientation(hole.points, true); + holeArray.push(points.length / 2); + points = points.concat(hole.points); + } + const triangles = earcut_1(points, holeArray, 2); + if (!triangles) { + return; + } + const vertPos = verts.length / 2; + for (let i = 0; i < triangles.length; i += 3) { + indices.push(triangles[i] + vertPos); + indices.push(triangles[i + 1] + vertPos); + indices.push(triangles[i + 2] + vertPos); + } + for (let i = 0; i < points.length; i++) { + verts.push(points[i]); + } + } + } + }; + + const buildRectangle = { + build(graphicsData) { + const rectData = graphicsData.shape; + const x = rectData.x; + const y = rectData.y; + const width = rectData.width; + const height = rectData.height; + const points = graphicsData.points; + points.length = 0; + if (!(width >= 0 && height >= 0)) { + return; + } + points.push(x, y, x + width, y, x + width, y + height, x, y + height); + }, + triangulate(graphicsData, graphicsGeometry) { + const points = graphicsData.points; + const verts = graphicsGeometry.points; + if (points.length === 0) { + return; + } + const vertPos = verts.length / 2; + verts.push(points[0], points[1], points[2], points[3], points[6], points[7], points[4], points[5]); + graphicsGeometry.indices.push(vertPos, vertPos + 1, vertPos + 2, vertPos + 1, vertPos + 2, vertPos + 3); + } + }; + + const buildRoundedRectangle = { + build(graphicsData) { + buildCircle.build(graphicsData); + }, + triangulate(graphicsData, graphicsGeometry) { + buildCircle.triangulate(graphicsData, graphicsGeometry); + } + }; + + var LINE_JOIN = /* @__PURE__ */ ((LINE_JOIN2) => { + LINE_JOIN2["MITER"] = "miter"; + LINE_JOIN2["BEVEL"] = "bevel"; + LINE_JOIN2["ROUND"] = "round"; + return LINE_JOIN2; + })(LINE_JOIN || {}); + var LINE_CAP = /* @__PURE__ */ ((LINE_CAP2) => { + LINE_CAP2["BUTT"] = "butt"; + LINE_CAP2["ROUND"] = "round"; + LINE_CAP2["SQUARE"] = "square"; + return LINE_CAP2; + })(LINE_CAP || {}); + const curves = { + adaptive: true, + maxLength: 10, + minSegments: 8, + maxSegments: 2048, + epsilon: 1e-4, + _segmentsCount(length, defaultSegments = 20) { + if (!this.adaptive || !length || isNaN(length)) { + return defaultSegments; + } + let result = Math.ceil(length / this.maxLength); + if (result < this.minSegments) { + result = this.minSegments; + } else if (result > this.maxSegments) { + result = this.maxSegments; + } + return result; + } + }; + const GRAPHICS_CURVES = curves; + + class ArcUtils { + static curveTo(x1, y1, x2, y2, radius, points) { + const fromX = points[points.length - 2]; + const fromY = points[points.length - 1]; + const a1 = fromY - y1; + const b1 = fromX - x1; + const a2 = y2 - y1; + const b2 = x2 - x1; + const mm = Math.abs(a1 * b2 - b1 * a2); + if (mm < 1e-8 || radius === 0) { + if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { + points.push(x1, y1); + } + return null; + } + const dd = a1 * a1 + b1 * b1; + const cc = a2 * a2 + b2 * b2; + const tt = a1 * a2 + b1 * b2; + const k1 = radius * Math.sqrt(dd) / mm; + const k2 = radius * Math.sqrt(cc) / mm; + const j1 = k1 * tt / dd; + const j2 = k2 * tt / cc; + const cx = k1 * b2 + k2 * b1; + const cy = k1 * a2 + k2 * a1; + const px = b1 * (k2 + j1); + const py = a1 * (k2 + j1); + const qx = b2 * (k1 + j2); + const qy = a2 * (k1 + j2); + const startAngle = Math.atan2(py - cy, px - cx); + const endAngle = Math.atan2(qy - cy, qx - cx); + return { + cx: cx + x1, + cy: cy + y1, + radius, + startAngle, + endAngle, + anticlockwise: b1 * a2 > b2 * a1 + }; + } + static arc(_startX, _startY, cx, cy, radius, startAngle, endAngle, _anticlockwise, points) { + const sweep = endAngle - startAngle; + const n = curves._segmentsCount(Math.abs(sweep) * radius, Math.ceil(Math.abs(sweep) / PI_2) * 40); + const theta = sweep / (n * 2); + const theta2 = theta * 2; + const cTheta = Math.cos(theta); + const sTheta = Math.sin(theta); + const segMinus = n - 1; + const remainder = segMinus % 1 / segMinus; + for (let i = 0; i <= segMinus; ++i) { + const real = i + remainder * i; + const angle = theta + startAngle + theta2 * real; + const c = Math.cos(angle); + const s = -Math.sin(angle); + points.push((cTheta * c + sTheta * s) * radius + cx, (cTheta * -s + sTheta * c) * radius + cy); + } + } + } + + class BatchPart { + constructor() { + this.reset(); + } + begin(style, startIndex, attribStart) { + this.reset(); + this.style = style; + this.start = startIndex; + this.attribStart = attribStart; + } + end(endIndex, endAttrib) { + this.attribSize = endAttrib - this.attribStart; + this.size = endIndex - this.start; + } + reset() { + this.style = null; + this.size = 0; + this.start = 0; + this.attribStart = 0; + this.attribSize = 0; + } + } + + class BezierUtils { + static curveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { + const n = 10; + let result = 0; + let t = 0; + let t2 = 0; + let t3 = 0; + let nt = 0; + let nt2 = 0; + let nt3 = 0; + let x = 0; + let y = 0; + let dx = 0; + let dy = 0; + let prevX = fromX; + let prevY = fromY; + for (let i = 1; i <= n; ++i) { + t = i / n; + t2 = t * t; + t3 = t2 * t; + nt = 1 - t; + nt2 = nt * nt; + nt3 = nt2 * nt; + x = nt3 * fromX + 3 * nt2 * t * cpX + 3 * nt * t2 * cpX2 + t3 * toX; + y = nt3 * fromY + 3 * nt2 * t * cpY + 3 * nt * t2 * cpY2 + t3 * toY; + dx = prevX - x; + dy = prevY - y; + prevX = x; + prevY = y; + result += Math.sqrt(dx * dx + dy * dy); + } + return result; + } + static curveTo(cpX, cpY, cpX2, cpY2, toX, toY, points) { + const fromX = points[points.length - 2]; + const fromY = points[points.length - 1]; + points.length -= 2; + const n = curves._segmentsCount(BezierUtils.curveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY)); + let dt = 0; + let dt2 = 0; + let dt3 = 0; + let t2 = 0; + let t3 = 0; + points.push(fromX, fromY); + for (let i = 1, j = 0; i <= n; ++i) { + j = i / n; + dt = 1 - j; + dt2 = dt * dt; + dt3 = dt2 * dt; + t2 = j * j; + t3 = t2 * j; + points.push(dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + } + } + + function square(x, y, nx, ny, innerWeight, outerWeight, clockwise, verts) { + const ix = x - nx * innerWeight; + const iy = y - ny * innerWeight; + const ox = x + nx * outerWeight; + const oy = y + ny * outerWeight; + let exx; + let eyy; + if (clockwise) { + exx = ny; + eyy = -nx; + } else { + exx = -ny; + eyy = nx; + } + const eix = ix + exx; + const eiy = iy + eyy; + const eox = ox + exx; + const eoy = oy + eyy; + verts.push(eix, eiy, eox, eoy); + return 2; + } + function round(cx, cy, sx, sy, ex, ey, verts, clockwise) { + const cx2p0x = sx - cx; + const cy2p0y = sy - cy; + let angle0 = Math.atan2(cx2p0x, cy2p0y); + let angle1 = Math.atan2(ex - cx, ey - cy); + if (clockwise && angle0 < angle1) { + angle0 += Math.PI * 2; + } else if (!clockwise && angle0 > angle1) { + angle1 += Math.PI * 2; + } + let startAngle = angle0; + const angleDiff = angle1 - angle0; + const absAngleDiff = Math.abs(angleDiff); + const radius = Math.sqrt(cx2p0x * cx2p0x + cy2p0y * cy2p0y); + const segCount = (15 * absAngleDiff * Math.sqrt(radius) / Math.PI >> 0) + 1; + const angleInc = angleDiff / segCount; + startAngle += angleInc; + if (clockwise) { + verts.push(cx, cy, sx, sy); + for (let i = 1, angle = startAngle; i < segCount; i++, angle += angleInc) { + verts.push(cx, cy, cx + Math.sin(angle) * radius, cy + Math.cos(angle) * radius); + } + verts.push(cx, cy, ex, ey); + } else { + verts.push(sx, sy, cx, cy); + for (let i = 1, angle = startAngle; i < segCount; i++, angle += angleInc) { + verts.push(cx + Math.sin(angle) * radius, cy + Math.cos(angle) * radius, cx, cy); + } + verts.push(ex, ey, cx, cy); + } + return segCount * 2; + } + function buildNonNativeLine(graphicsData, graphicsGeometry) { + const shape = graphicsData.shape; + let points = graphicsData.points || shape.points.slice(); + const eps = graphicsGeometry.closePointEps; + if (points.length === 0) { + return; + } + const style = graphicsData.lineStyle; + const firstPoint = new Point(points[0], points[1]); + const lastPoint = new Point(points[points.length - 2], points[points.length - 1]); + const closedShape = shape.type !== SHAPES.POLY || shape.closeStroke; + const closedPath = Math.abs(firstPoint.x - lastPoint.x) < eps && Math.abs(firstPoint.y - lastPoint.y) < eps; + if (closedShape) { + points = points.slice(); + if (closedPath) { + points.pop(); + points.pop(); + lastPoint.set(points[points.length - 2], points[points.length - 1]); + } + const midPointX = (firstPoint.x + lastPoint.x) * 0.5; + const midPointY = (lastPoint.y + firstPoint.y) * 0.5; + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + const verts = graphicsGeometry.points; + const length = points.length / 2; + let indexCount = points.length; + const indexStart = verts.length / 2; + const width = style.width / 2; + const widthSquared = width * width; + const miterLimitSquared = style.miterLimit * style.miterLimit; + let x0 = points[0]; + let y0 = points[1]; + let x1 = points[2]; + let y1 = points[3]; + let x2 = 0; + let y2 = 0; + let perpx = -(y0 - y1); + let perpy = x0 - x1; + let perp1x = 0; + let perp1y = 0; + let dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + const ratio = style.alignment; + const innerWeight = (1 - ratio) * 2; + const outerWeight = ratio * 2; + if (!closedShape) { + if (style.cap === LINE_CAP.ROUND) { + indexCount += round(x0 - perpx * (innerWeight - outerWeight) * 0.5, y0 - perpy * (innerWeight - outerWeight) * 0.5, x0 - perpx * innerWeight, y0 - perpy * innerWeight, x0 + perpx * outerWeight, y0 + perpy * outerWeight, verts, true) + 2; + } else if (style.cap === LINE_CAP.SQUARE) { + indexCount += square(x0, y0, perpx, perpy, innerWeight, outerWeight, true, verts); + } + } + verts.push(x0 - perpx * innerWeight, y0 - perpy * innerWeight, x0 + perpx * outerWeight, y0 + perpy * outerWeight); + for (let i = 1; i < length - 1; ++i) { + x0 = points[(i - 1) * 2]; + y0 = points[(i - 1) * 2 + 1]; + x1 = points[i * 2]; + y1 = points[i * 2 + 1]; + x2 = points[(i + 1) * 2]; + y2 = points[(i + 1) * 2 + 1]; + perpx = -(y0 - y1); + perpy = x0 - x1; + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + perp1x = -(y1 - y2); + perp1y = x1 - x2; + dist = Math.sqrt(perp1x * perp1x + perp1y * perp1y); + perp1x /= dist; + perp1y /= dist; + perp1x *= width; + perp1y *= width; + const dx0 = x1 - x0; + const dy0 = y0 - y1; + const dx1 = x1 - x2; + const dy1 = y2 - y1; + const dot = dx0 * dx1 + dy0 * dy1; + const cross = dy0 * dx1 - dy1 * dx0; + const clockwise = cross < 0; + if (Math.abs(cross) < 1e-3 * Math.abs(dot)) { + verts.push(x1 - perpx * innerWeight, y1 - perpy * innerWeight, x1 + perpx * outerWeight, y1 + perpy * outerWeight); + if (dot >= 0) { + if (style.join === LINE_JOIN.ROUND) { + indexCount += round(x1, y1, x1 - perpx * innerWeight, y1 - perpy * innerWeight, x1 - perp1x * innerWeight, y1 - perp1y * innerWeight, verts, false) + 4; + } else { + indexCount += 2; + } + verts.push(x1 - perp1x * outerWeight, y1 - perp1y * outerWeight, x1 + perp1x * innerWeight, y1 + perp1y * innerWeight); + } + continue; + } + const c1 = (-perpx + x0) * (-perpy + y1) - (-perpx + x1) * (-perpy + y0); + const c2 = (-perp1x + x2) * (-perp1y + y1) - (-perp1x + x1) * (-perp1y + y2); + const px = (dx0 * c2 - dx1 * c1) / cross; + const py = (dy1 * c1 - dy0 * c2) / cross; + const pdist = (px - x1) * (px - x1) + (py - y1) * (py - y1); + const imx = x1 + (px - x1) * innerWeight; + const imy = y1 + (py - y1) * innerWeight; + const omx = x1 - (px - x1) * outerWeight; + const omy = y1 - (py - y1) * outerWeight; + const smallerInsideSegmentSq = Math.min(dx0 * dx0 + dy0 * dy0, dx1 * dx1 + dy1 * dy1); + const insideWeight = clockwise ? innerWeight : outerWeight; + const smallerInsideDiagonalSq = smallerInsideSegmentSq + insideWeight * insideWeight * widthSquared; + const insideMiterOk = pdist <= smallerInsideDiagonalSq; + let join = style.join; + if (join === LINE_JOIN.MITER && pdist / widthSquared > miterLimitSquared) { + join = LINE_JOIN.BEVEL; + } + if (insideMiterOk) { + switch (join) { + case LINE_JOIN.MITER: { + verts.push(imx, imy, omx, omy); + break; + } + case LINE_JOIN.BEVEL: { + if (clockwise) { + verts.push(imx, imy, x1 + perpx * outerWeight, y1 + perpy * outerWeight, imx, imy, x1 + perp1x * outerWeight, y1 + perp1y * outerWeight); + } else { + verts.push(x1 - perpx * innerWeight, y1 - perpy * innerWeight, omx, omy, x1 - perp1x * innerWeight, y1 - perp1y * innerWeight, omx, omy); + } + indexCount += 2; + break; + } + case LINE_JOIN.ROUND: { + if (clockwise) { + verts.push(imx, imy, x1 + perpx * outerWeight, y1 + perpy * outerWeight); + indexCount += round(x1, y1, x1 + perpx * outerWeight, y1 + perpy * outerWeight, x1 + perp1x * outerWeight, y1 + perp1y * outerWeight, verts, true) + 4; + verts.push(imx, imy, x1 + perp1x * outerWeight, y1 + perp1y * outerWeight); + } else { + verts.push(x1 - perpx * innerWeight, y1 - perpy * innerWeight, omx, omy); + indexCount += round(x1, y1, x1 - perpx * innerWeight, y1 - perpy * innerWeight, x1 - perp1x * innerWeight, y1 - perp1y * innerWeight, verts, false) + 4; + verts.push(x1 - perp1x * innerWeight, y1 - perp1y * innerWeight, omx, omy); + } + break; + } + } + } else { + verts.push(x1 - perpx * innerWeight, y1 - perpy * innerWeight, x1 + perpx * outerWeight, y1 + perpy * outerWeight); + switch (join) { + case LINE_JOIN.MITER: { + if (clockwise) { + verts.push(omx, omy, omx, omy); + } else { + verts.push(imx, imy, imx, imy); + } + indexCount += 2; + break; + } + case LINE_JOIN.ROUND: { + if (clockwise) { + indexCount += round(x1, y1, x1 + perpx * outerWeight, y1 + perpy * outerWeight, x1 + perp1x * outerWeight, y1 + perp1y * outerWeight, verts, true) + 2; + } else { + indexCount += round(x1, y1, x1 - perpx * innerWeight, y1 - perpy * innerWeight, x1 - perp1x * innerWeight, y1 - perp1y * innerWeight, verts, false) + 2; + } + break; + } + } + verts.push(x1 - perp1x * innerWeight, y1 - perp1y * innerWeight, x1 + perp1x * outerWeight, y1 + perp1y * outerWeight); + indexCount += 2; + } + } + x0 = points[(length - 2) * 2]; + y0 = points[(length - 2) * 2 + 1]; + x1 = points[(length - 1) * 2]; + y1 = points[(length - 1) * 2 + 1]; + perpx = -(y0 - y1); + perpy = x0 - x1; + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + verts.push(x1 - perpx * innerWeight, y1 - perpy * innerWeight, x1 + perpx * outerWeight, y1 + perpy * outerWeight); + if (!closedShape) { + if (style.cap === LINE_CAP.ROUND) { + indexCount += round(x1 - perpx * (innerWeight - outerWeight) * 0.5, y1 - perpy * (innerWeight - outerWeight) * 0.5, x1 - perpx * innerWeight, y1 - perpy * innerWeight, x1 + perpx * outerWeight, y1 + perpy * outerWeight, verts, false) + 2; + } else if (style.cap === LINE_CAP.SQUARE) { + indexCount += square(x1, y1, perpx, perpy, innerWeight, outerWeight, false, verts); + } + } + const indices = graphicsGeometry.indices; + const eps2 = curves.epsilon * curves.epsilon; + for (let i = indexStart; i < indexCount + indexStart - 2; ++i) { + x0 = verts[i * 2]; + y0 = verts[i * 2 + 1]; + x1 = verts[(i + 1) * 2]; + y1 = verts[(i + 1) * 2 + 1]; + x2 = verts[(i + 2) * 2]; + y2 = verts[(i + 2) * 2 + 1]; + if (Math.abs(x0 * (y1 - y2) + x1 * (y2 - y0) + x2 * (y0 - y1)) < eps2) { + continue; + } + indices.push(i, i + 1, i + 2); + } + } + function buildNativeLine(graphicsData, graphicsGeometry) { + let i = 0; + const shape = graphicsData.shape; + const points = graphicsData.points || shape.points; + const closedShape = shape.type !== SHAPES.POLY || shape.closeStroke; + if (points.length === 0) + return; + const verts = graphicsGeometry.points; + const indices = graphicsGeometry.indices; + const length = points.length / 2; + const startIndex = verts.length / 2; + let currentIndex = startIndex; + verts.push(points[0], points[1]); + for (i = 1; i < length; i++) { + verts.push(points[i * 2], points[i * 2 + 1]); + indices.push(currentIndex, currentIndex + 1); + currentIndex++; + } + if (closedShape) { + indices.push(currentIndex, startIndex); + } + } + function buildLine(graphicsData, graphicsGeometry) { + if (graphicsData.lineStyle.native) { + buildNativeLine(graphicsData, graphicsGeometry); + } else { + buildNonNativeLine(graphicsData, graphicsGeometry); + } + } + + class QuadraticUtils { + static curveLength(fromX, fromY, cpX, cpY, toX, toY) { + const ax = fromX - 2 * cpX + toX; + const ay = fromY - 2 * cpY + toY; + const bx = 2 * cpX - 2 * fromX; + const by = 2 * cpY - 2 * fromY; + const a = 4 * (ax * ax + ay * ay); + const b = 4 * (ax * bx + ay * by); + const c = bx * bx + by * by; + const s = 2 * Math.sqrt(a + b + c); + const a2 = Math.sqrt(a); + const a32 = 2 * a * a2; + const c2 = 2 * Math.sqrt(c); + const ba = b / a2; + return (a32 * s + a2 * b * (s - c2) + (4 * c * a - b * b) * Math.log((2 * a2 + ba + s) / (ba + c2))) / (4 * a32); + } + static curveTo(cpX, cpY, toX, toY, points) { + const fromX = points[points.length - 2]; + const fromY = points[points.length - 1]; + const n = curves._segmentsCount(QuadraticUtils.curveLength(fromX, fromY, cpX, cpY, toX, toY)); + let xa = 0; + let ya = 0; + for (let i = 1; i <= n; ++i) { + const j = i / n; + xa = fromX + (cpX - fromX) * j; + ya = fromY + (cpY - fromY) * j; + points.push(xa + (cpX + (toX - cpX) * j - xa) * j, ya + (cpY + (toY - cpY) * j - ya) * j); + } + } + } + + const FILL_COMMANDS = { + [SHAPES.POLY]: buildPoly, + [SHAPES.CIRC]: buildCircle, + [SHAPES.ELIP]: buildCircle, + [SHAPES.RECT]: buildRectangle, + [SHAPES.RREC]: buildRoundedRectangle + }; + const BATCH_POOL = []; + const DRAW_CALL_POOL = []; + + class GraphicsData { + constructor(shape, fillStyle = null, lineStyle = null, matrix = null) { + this.points = []; + this.holes = []; + this.shape = shape; + this.lineStyle = lineStyle; + this.fillStyle = fillStyle; + this.matrix = matrix; + this.type = shape.type; + } + clone() { + return new GraphicsData(this.shape, this.fillStyle, this.lineStyle, this.matrix); + } + destroy() { + this.shape = null; + this.holes.length = 0; + this.holes = null; + this.points.length = 0; + this.points = null; + this.lineStyle = null; + this.fillStyle = null; + } + } + + const tmpPoint = new Point(); + const _GraphicsGeometry = class extends BatchGeometry { + constructor() { + super(); + this.closePointEps = 1e-4; + this.boundsPadding = 0; + this.uvsFloat32 = null; + this.indicesUint16 = null; + this.batchable = false; + this.points = []; + this.colors = []; + this.uvs = []; + this.indices = []; + this.textureIds = []; + this.graphicsData = []; + this.drawCalls = []; + this.batchDirty = -1; + this.batches = []; + this.dirty = 0; + this.cacheDirty = -1; + this.clearDirty = 0; + this.shapeIndex = 0; + this._bounds = new Bounds(); + this.boundsDirty = -1; + } + get bounds() { + this.updateBatches(); + if (this.boundsDirty !== this.dirty) { + this.boundsDirty = this.dirty; + this.calculateBounds(); + } + return this._bounds; + } + invalidate() { + this.boundsDirty = -1; + this.dirty++; + this.batchDirty++; + this.shapeIndex = 0; + this.points.length = 0; + this.colors.length = 0; + this.uvs.length = 0; + this.indices.length = 0; + this.textureIds.length = 0; + for (let i = 0; i < this.drawCalls.length; i++) { + this.drawCalls[i].texArray.clear(); + DRAW_CALL_POOL.push(this.drawCalls[i]); + } + this.drawCalls.length = 0; + for (let i = 0; i < this.batches.length; i++) { + const batchPart = this.batches[i]; + batchPart.reset(); + BATCH_POOL.push(batchPart); + } + this.batches.length = 0; + } + clear() { + if (this.graphicsData.length > 0) { + this.invalidate(); + this.clearDirty++; + this.graphicsData.length = 0; + } + return this; + } + drawShape(shape, fillStyle = null, lineStyle = null, matrix = null) { + const data = new GraphicsData(shape, fillStyle, lineStyle, matrix); + this.graphicsData.push(data); + this.dirty++; + return this; + } + drawHole(shape, matrix = null) { + if (!this.graphicsData.length) { + return null; + } + const data = new GraphicsData(shape, null, null, matrix); + const lastShape = this.graphicsData[this.graphicsData.length - 1]; + data.lineStyle = lastShape.lineStyle; + lastShape.holes.push(data); + this.dirty++; + return this; + } + destroy() { + super.destroy(); + for (let i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); + } + this.points.length = 0; + this.points = null; + this.colors.length = 0; + this.colors = null; + this.uvs.length = 0; + this.uvs = null; + this.indices.length = 0; + this.indices = null; + this.indexBuffer.destroy(); + this.indexBuffer = null; + this.graphicsData.length = 0; + this.graphicsData = null; + this.drawCalls.length = 0; + this.drawCalls = null; + this.batches.length = 0; + this.batches = null; + this._bounds = null; + } + containsPoint(point) { + const graphicsData = this.graphicsData; + for (let i = 0; i < graphicsData.length; ++i) { + const data = graphicsData[i]; + if (!data.fillStyle.visible) { + continue; + } + if (data.shape) { + if (data.matrix) { + data.matrix.applyInverse(point, tmpPoint); + } else { + tmpPoint.copyFrom(point); + } + if (data.shape.contains(tmpPoint.x, tmpPoint.y)) { + let hitHole = false; + if (data.holes) { + for (let i2 = 0; i2 < data.holes.length; i2++) { + const hole = data.holes[i2]; + if (hole.shape.contains(tmpPoint.x, tmpPoint.y)) { + hitHole = true; + break; + } + } + } + if (!hitHole) { + return true; + } + } + } + } + return false; + } + updateBatches() { + if (!this.graphicsData.length) { + this.batchable = true; + return; + } + if (!this.validateBatching()) { + return; + } + this.cacheDirty = this.dirty; + const uvs = this.uvs; + const graphicsData = this.graphicsData; + let batchPart = null; + let currentStyle = null; + if (this.batches.length > 0) { + batchPart = this.batches[this.batches.length - 1]; + currentStyle = batchPart.style; + } + for (let i = this.shapeIndex; i < graphicsData.length; i++) { + this.shapeIndex++; + const data = graphicsData[i]; + const fillStyle = data.fillStyle; + const lineStyle = data.lineStyle; + const command = FILL_COMMANDS[data.type]; + command.build(data); + if (data.matrix) { + this.transformPoints(data.points, data.matrix); + } + if (fillStyle.visible || lineStyle.visible) { + this.processHoles(data.holes); + } + for (let j = 0; j < 2; j++) { + const style = j === 0 ? fillStyle : lineStyle; + if (!style.visible) + continue; + const nextTexture = style.texture.baseTexture; + const index2 = this.indices.length; + const attribIndex = this.points.length / 2; + nextTexture.wrapMode = WRAP_MODES.REPEAT; + if (j === 0) { + this.processFill(data); + } else { + this.processLine(data); + } + const size = this.points.length / 2 - attribIndex; + if (size === 0) + continue; + if (batchPart && !this._compareStyles(currentStyle, style)) { + batchPart.end(index2, attribIndex); + batchPart = null; + } + if (!batchPart) { + batchPart = BATCH_POOL.pop() || new BatchPart(); + batchPart.begin(style, index2, attribIndex); + this.batches.push(batchPart); + currentStyle = style; + } + this.addUvs(this.points, uvs, style.texture, attribIndex, size, style.matrix); + } + } + const index = this.indices.length; + const attrib = this.points.length / 2; + if (batchPart) { + batchPart.end(index, attrib); + } + if (this.batches.length === 0) { + this.batchable = true; + return; + } + const need32 = attrib > 65535; + if (this.indicesUint16 && this.indices.length === this.indicesUint16.length && need32 === this.indicesUint16.BYTES_PER_ELEMENT > 2) { + this.indicesUint16.set(this.indices); + } else { + this.indicesUint16 = need32 ? new Uint32Array(this.indices) : new Uint16Array(this.indices); + } + this.batchable = this.isBatchable(); + if (this.batchable) { + this.packBatches(); + } else { + this.buildDrawCalls(); + } + } + _compareStyles(styleA, styleB) { + if (!styleA || !styleB) { + return false; + } + if (styleA.texture.baseTexture !== styleB.texture.baseTexture) { + return false; + } + if (styleA.color + styleA.alpha !== styleB.color + styleB.alpha) { + return false; + } + if (!!styleA.native !== !!styleB.native) { + return false; + } + return true; + } + validateBatching() { + if (this.dirty === this.cacheDirty || !this.graphicsData.length) { + return false; + } + for (let i = 0, l = this.graphicsData.length; i < l; i++) { + const data = this.graphicsData[i]; + const fill = data.fillStyle; + const line = data.lineStyle; + if (fill && !fill.texture.baseTexture.valid) + return false; + if (line && !line.texture.baseTexture.valid) + return false; + } + return true; + } + packBatches() { + this.batchDirty++; + this.uvsFloat32 = new Float32Array(this.uvs); + const batches = this.batches; + for (let i = 0, l = batches.length; i < l; i++) { + const batch = batches[i]; + for (let j = 0; j < batch.size; j++) { + const index = batch.start + j; + this.indicesUint16[index] = this.indicesUint16[index] - batch.attribStart; + } + } + } + isBatchable() { + if (this.points.length > 65535 * 2) { + return false; + } + const batches = this.batches; + for (let i = 0; i < batches.length; i++) { + if (batches[i].style.native) { + return false; + } + } + return this.points.length < _GraphicsGeometry.BATCHABLE_SIZE * 2; + } + buildDrawCalls() { + let TICK = ++BaseTexture._globalBatch; + for (let i = 0; i < this.drawCalls.length; i++) { + this.drawCalls[i].texArray.clear(); + DRAW_CALL_POOL.push(this.drawCalls[i]); + } + this.drawCalls.length = 0; + const colors = this.colors; + const textureIds = this.textureIds; + let currentGroup = DRAW_CALL_POOL.pop(); + if (!currentGroup) { + currentGroup = new BatchDrawCall(); + currentGroup.texArray = new BatchTextureArray(); + } + currentGroup.texArray.count = 0; + currentGroup.start = 0; + currentGroup.size = 0; + currentGroup.type = DRAW_MODES.TRIANGLES; + let textureCount = 0; + let currentTexture = null; + let textureId = 0; + let native = false; + let drawMode = DRAW_MODES.TRIANGLES; + let index = 0; + this.drawCalls.push(currentGroup); + for (let i = 0; i < this.batches.length; i++) { + const data = this.batches[i]; + const maxTextures = 8; + const style = data.style; + const nextTexture = style.texture.baseTexture; + if (native !== !!style.native) { + native = !!style.native; + drawMode = native ? DRAW_MODES.LINES : DRAW_MODES.TRIANGLES; + currentTexture = null; + textureCount = maxTextures; + TICK++; + } + if (currentTexture !== nextTexture) { + currentTexture = nextTexture; + if (nextTexture._batchEnabled !== TICK) { + if (textureCount === maxTextures) { + TICK++; + textureCount = 0; + if (currentGroup.size > 0) { + currentGroup = DRAW_CALL_POOL.pop(); + if (!currentGroup) { + currentGroup = new BatchDrawCall(); + currentGroup.texArray = new BatchTextureArray(); + } + this.drawCalls.push(currentGroup); + } + currentGroup.start = index; + currentGroup.size = 0; + currentGroup.texArray.count = 0; + currentGroup.type = drawMode; + } + nextTexture.touched = 1; + nextTexture._batchEnabled = TICK; + nextTexture._batchLocation = textureCount; + nextTexture.wrapMode = WRAP_MODES.REPEAT; + currentGroup.texArray.elements[currentGroup.texArray.count++] = nextTexture; + textureCount++; + } + } + currentGroup.size += data.size; + index += data.size; + textureId = nextTexture._batchLocation; + this.addColors(colors, style.color, style.alpha, data.attribSize, data.attribStart); + this.addTextureIds(textureIds, textureId, data.attribSize, data.attribStart); + } + BaseTexture._globalBatch = TICK; + this.packAttributes(); + } + packAttributes() { + const verts = this.points; + const uvs = this.uvs; + const colors = this.colors; + const textureIds = this.textureIds; + const glPoints = new ArrayBuffer(verts.length * 3 * 4); + const f32 = new Float32Array(glPoints); + const u32 = new Uint32Array(glPoints); + let p = 0; + for (let i = 0; i < verts.length / 2; i++) { + f32[p++] = verts[i * 2]; + f32[p++] = verts[i * 2 + 1]; + f32[p++] = uvs[i * 2]; + f32[p++] = uvs[i * 2 + 1]; + u32[p++] = colors[i]; + f32[p++] = textureIds[i]; + } + this._buffer.update(glPoints); + this._indexBuffer.update(this.indicesUint16); + } + processFill(data) { + if (data.holes.length) { + buildPoly.triangulate(data, this); + } else { + const command = FILL_COMMANDS[data.type]; + command.triangulate(data, this); + } + } + processLine(data) { + buildLine(data, this); + for (let i = 0; i < data.holes.length; i++) { + buildLine(data.holes[i], this); + } + } + processHoles(holes) { + for (let i = 0; i < holes.length; i++) { + const hole = holes[i]; + const command = FILL_COMMANDS[hole.type]; + command.build(hole); + if (hole.matrix) { + this.transformPoints(hole.points, hole.matrix); + } + } + } + calculateBounds() { + const bounds = this._bounds; + bounds.clear(); + bounds.addVertexData(this.points, 0, this.points.length); + bounds.pad(this.boundsPadding, this.boundsPadding); + } + transformPoints(points, matrix) { + for (let i = 0; i < points.length / 2; i++) { + const x = points[i * 2]; + const y = points[i * 2 + 1]; + points[i * 2] = matrix.a * x + matrix.c * y + matrix.tx; + points[i * 2 + 1] = matrix.b * x + matrix.d * y + matrix.ty; + } + } + addColors(colors, color, alpha, size, offset = 0) { + const bgr = Color.shared.setValue(color).toLittleEndianNumber(); + const result = Color.shared.setValue(bgr).toPremultiplied(alpha); + colors.length = Math.max(colors.length, offset + size); + for (let i = 0; i < size; i++) { + colors[offset + i] = result; + } + } + addTextureIds(textureIds, id, size, offset = 0) { + textureIds.length = Math.max(textureIds.length, offset + size); + for (let i = 0; i < size; i++) { + textureIds[offset + i] = id; + } + } + addUvs(verts, uvs, texture, start, size, matrix = null) { + let index = 0; + const uvsStart = uvs.length; + const frame = texture.frame; + while (index < size) { + let x = verts[(start + index) * 2]; + let y = verts[(start + index) * 2 + 1]; + if (matrix) { + const nx = matrix.a * x + matrix.c * y + matrix.tx; + y = matrix.b * x + matrix.d * y + matrix.ty; + x = nx; + } + index++; + uvs.push(x / frame.width, y / frame.height); + } + const baseTexture = texture.baseTexture; + if (frame.width < baseTexture.width || frame.height < baseTexture.height) { + this.adjustUvs(uvs, texture, uvsStart, size); + } + } + adjustUvs(uvs, texture, start, size) { + const baseTexture = texture.baseTexture; + const eps = 1e-6; + const finish = start + size * 2; + const frame = texture.frame; + const scaleX = frame.width / baseTexture.width; + const scaleY = frame.height / baseTexture.height; + let offsetX = frame.x / frame.width; + let offsetY = frame.y / frame.height; + let minX = Math.floor(uvs[start] + eps); + let minY = Math.floor(uvs[start + 1] + eps); + for (let i = start + 2; i < finish; i += 2) { + minX = Math.min(minX, Math.floor(uvs[i] + eps)); + minY = Math.min(minY, Math.floor(uvs[i + 1] + eps)); + } + offsetX -= minX; + offsetY -= minY; + for (let i = start; i < finish; i += 2) { + uvs[i] = (uvs[i] + offsetX) * scaleX; + uvs[i + 1] = (uvs[i + 1] + offsetY) * scaleY; + } + } + }; + let GraphicsGeometry = _GraphicsGeometry; + GraphicsGeometry.BATCHABLE_SIZE = 100; + + class FillStyle { + constructor() { + this.color = 16777215; + this.alpha = 1; + this.texture = Texture.WHITE; + this.matrix = null; + this.visible = false; + this.reset(); + } + clone() { + const obj = new FillStyle(); + obj.color = this.color; + obj.alpha = this.alpha; + obj.texture = this.texture; + obj.matrix = this.matrix; + obj.visible = this.visible; + return obj; + } + reset() { + this.color = 16777215; + this.alpha = 1; + this.texture = Texture.WHITE; + this.matrix = null; + this.visible = false; + } + destroy() { + this.texture = null; + this.matrix = null; + } + } + + class LineStyle extends FillStyle { + constructor() { + super(...arguments); + this.width = 0; + this.alignment = 0.5; + this.native = false; + this.cap = LINE_CAP.BUTT; + this.join = LINE_JOIN.MITER; + this.miterLimit = 10; + } + clone() { + const obj = new LineStyle(); + obj.color = this.color; + obj.alpha = this.alpha; + obj.texture = this.texture; + obj.matrix = this.matrix; + obj.visible = this.visible; + obj.width = this.width; + obj.alignment = this.alignment; + obj.native = this.native; + obj.cap = this.cap; + obj.join = this.join; + obj.miterLimit = this.miterLimit; + return obj; + } + reset() { + super.reset(); + this.color = 0; + this.alignment = 0.5; + this.width = 0; + this.native = false; + } + } + + const DEFAULT_SHADERS = {}; + const _Graphics = class extends Container { + constructor(geometry = null) { + super(); + this.shader = null; + this.pluginName = "batch"; + this.currentPath = null; + this.batches = []; + this.batchTint = -1; + this.batchDirty = -1; + this.vertexData = null; + this._fillStyle = new FillStyle(); + this._lineStyle = new LineStyle(); + this._matrix = null; + this._holeMode = false; + this.state = State.for2d(); + this._geometry = geometry || new GraphicsGeometry(); + this._geometry.refCount++; + this._transformID = -1; + this._tintColor = new Color(16777215); + this.blendMode = BLEND_MODES.NORMAL; + } + get geometry() { + return this._geometry; + } + clone() { + this.finishPoly(); + return new _Graphics(this._geometry); + } + set blendMode(value) { + this.state.blendMode = value; + } + get blendMode() { + return this.state.blendMode; + } + get tint() { + return this._tintColor.value; + } + set tint(value) { + this._tintColor.setValue(value); + } + get fill() { + return this._fillStyle; + } + get line() { + return this._lineStyle; + } + lineStyle(options = null, color = 0, alpha, alignment = 0.5, native = false) { + if (typeof options === "number") { + options = { width: options, color, alpha, alignment, native }; + } + return this.lineTextureStyle(options); + } + lineTextureStyle(options) { + const defaultLineStyleOptions = { + width: 0, + texture: Texture.WHITE, + color: options?.texture ? 16777215 : 0, + matrix: null, + alignment: 0.5, + native: false, + cap: LINE_CAP.BUTT, + join: LINE_JOIN.MITER, + miterLimit: 10 + }; + options = Object.assign(defaultLineStyleOptions, options); + this.normalizeColor(options); + if (this.currentPath) { + this.startPoly(); + } + const visible = options.width > 0 && options.alpha > 0; + if (!visible) { + this._lineStyle.reset(); + } else { + if (options.matrix) { + options.matrix = options.matrix.clone(); + options.matrix.invert(); + } + Object.assign(this._lineStyle, { visible }, options); + } + return this; + } + startPoly() { + if (this.currentPath) { + const points = this.currentPath.points; + const len = this.currentPath.points.length; + if (len > 2) { + this.drawShape(this.currentPath); + this.currentPath = new Polygon(); + this.currentPath.closeStroke = false; + this.currentPath.points.push(points[len - 2], points[len - 1]); + } + } else { + this.currentPath = new Polygon(); + this.currentPath.closeStroke = false; + } + } + finishPoly() { + if (this.currentPath) { + if (this.currentPath.points.length > 2) { + this.drawShape(this.currentPath); + this.currentPath = null; + } else { + this.currentPath.points.length = 0; + } + } + } + moveTo(x, y) { + this.startPoly(); + this.currentPath.points[0] = x; + this.currentPath.points[1] = y; + return this; + } + lineTo(x, y) { + if (!this.currentPath) { + this.moveTo(0, 0); + } + const points = this.currentPath.points; + const fromX = points[points.length - 2]; + const fromY = points[points.length - 1]; + if (fromX !== x || fromY !== y) { + points.push(x, y); + } + return this; + } + _initCurve(x = 0, y = 0) { + if (this.currentPath) { + if (this.currentPath.points.length === 0) { + this.currentPath.points = [x, y]; + } + } else { + this.moveTo(x, y); + } + } + quadraticCurveTo(cpX, cpY, toX, toY) { + this._initCurve(); + const points = this.currentPath.points; + if (points.length === 0) { + this.moveTo(0, 0); + } + QuadraticUtils.curveTo(cpX, cpY, toX, toY, points); + return this; + } + bezierCurveTo(cpX, cpY, cpX2, cpY2, toX, toY) { + this._initCurve(); + BezierUtils.curveTo(cpX, cpY, cpX2, cpY2, toX, toY, this.currentPath.points); + return this; + } + arcTo(x1, y1, x2, y2, radius) { + this._initCurve(x1, y1); + const points = this.currentPath.points; + const result = ArcUtils.curveTo(x1, y1, x2, y2, radius, points); + if (result) { + const { cx, cy, radius: radius2, startAngle, endAngle, anticlockwise } = result; + this.arc(cx, cy, radius2, startAngle, endAngle, anticlockwise); + } + return this; + } + arc(cx, cy, radius, startAngle, endAngle, anticlockwise = false) { + if (startAngle === endAngle) { + return this; + } + if (!anticlockwise && endAngle <= startAngle) { + endAngle += PI_2; + } else if (anticlockwise && startAngle <= endAngle) { + startAngle += PI_2; + } + const sweep = endAngle - startAngle; + if (sweep === 0) { + return this; + } + const startX = cx + Math.cos(startAngle) * radius; + const startY = cy + Math.sin(startAngle) * radius; + const eps = this._geometry.closePointEps; + let points = this.currentPath ? this.currentPath.points : null; + if (points) { + const xDiff = Math.abs(points[points.length - 2] - startX); + const yDiff = Math.abs(points[points.length - 1] - startY); + if (xDiff < eps && yDiff < eps) { + } else { + points.push(startX, startY); + } + } else { + this.moveTo(startX, startY); + points = this.currentPath.points; + } + ArcUtils.arc(startX, startY, cx, cy, radius, startAngle, endAngle, anticlockwise, points); + return this; + } + beginFill(color = 0, alpha) { + return this.beginTextureFill({ texture: Texture.WHITE, color, alpha }); + } + normalizeColor(options) { + const temp = Color.shared.setValue(options.color ?? 0); + options.color = temp.toNumber(); + options.alpha ?? (options.alpha = temp.alpha); + } + beginTextureFill(options) { + const defaultOptions = { + texture: Texture.WHITE, + color: 16777215, + matrix: null + }; + options = Object.assign(defaultOptions, options); + this.normalizeColor(options); + if (this.currentPath) { + this.startPoly(); + } + const visible = options.alpha > 0; + if (!visible) { + this._fillStyle.reset(); + } else { + if (options.matrix) { + options.matrix = options.matrix.clone(); + options.matrix.invert(); + } + Object.assign(this._fillStyle, { visible }, options); + } + return this; + } + endFill() { + this.finishPoly(); + this._fillStyle.reset(); + return this; + } + drawRect(x, y, width, height) { + return this.drawShape(new Rectangle(x, y, width, height)); + } + drawRoundedRect(x, y, width, height, radius) { + return this.drawShape(new RoundedRectangle(x, y, width, height, radius)); + } + drawCircle(x, y, radius) { + return this.drawShape(new Circle(x, y, radius)); + } + drawEllipse(x, y, width, height) { + return this.drawShape(new Ellipse(x, y, width, height)); + } + drawPolygon(...path) { + let points; + let closeStroke = true; + const poly = path[0]; + if (poly.points) { + closeStroke = poly.closeStroke; + points = poly.points; + } else if (Array.isArray(path[0])) { + points = path[0]; + } else { + points = path; + } + const shape = new Polygon(points); + shape.closeStroke = closeStroke; + this.drawShape(shape); + return this; + } + drawShape(shape) { + if (!this._holeMode) { + this._geometry.drawShape(shape, this._fillStyle.clone(), this._lineStyle.clone(), this._matrix); + } else { + this._geometry.drawHole(shape, this._matrix); + } + return this; + } + clear() { + this._geometry.clear(); + this._lineStyle.reset(); + this._fillStyle.reset(); + this._boundsID++; + this._matrix = null; + this._holeMode = false; + this.currentPath = null; + return this; + } + isFastRect() { + const data = this._geometry.graphicsData; + return data.length === 1 && data[0].shape.type === SHAPES.RECT && !data[0].matrix && !data[0].holes.length && !(data[0].lineStyle.visible && data[0].lineStyle.width); + } + _render(renderer) { + this.finishPoly(); + const geometry = this._geometry; + geometry.updateBatches(); + if (geometry.batchable) { + if (this.batchDirty !== geometry.batchDirty) { + this._populateBatches(); + } + this._renderBatched(renderer); + } else { + renderer.batch.flush(); + this._renderDirect(renderer); + } + } + _populateBatches() { + const geometry = this._geometry; + const blendMode = this.blendMode; + const len = geometry.batches.length; + this.batchTint = -1; + this._transformID = -1; + this.batchDirty = geometry.batchDirty; + this.batches.length = len; + this.vertexData = new Float32Array(geometry.points); + for (let i = 0; i < len; i++) { + const gI = geometry.batches[i]; + const color = gI.style.color; + const vertexData = new Float32Array(this.vertexData.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2); + const uvs = new Float32Array(geometry.uvsFloat32.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2); + const indices = new Uint16Array(geometry.indicesUint16.buffer, gI.start * 2, gI.size); + const batch = { + vertexData, + blendMode, + indices, + uvs, + _batchRGB: Color.shared.setValue(color).toRgbArray(), + _tintRGB: color, + _texture: gI.style.texture, + alpha: gI.style.alpha, + worldAlpha: 1 + }; + this.batches[i] = batch; + } + } + _renderBatched(renderer) { + if (!this.batches.length) { + return; + } + renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); + this.calculateVertices(); + this.calculateTints(); + for (let i = 0, l = this.batches.length; i < l; i++) { + const batch = this.batches[i]; + batch.worldAlpha = this.worldAlpha * batch.alpha; + renderer.plugins[this.pluginName].render(batch); + } + } + _renderDirect(renderer) { + const shader = this._resolveDirectShader(renderer); + const geometry = this._geometry; + const worldAlpha = this.worldAlpha; + const uniforms = shader.uniforms; + const drawCalls = geometry.drawCalls; + uniforms.translationMatrix = this.transform.worldTransform; + Color.shared.setValue(this._tintColor).premultiply(worldAlpha).toArray(uniforms.tint); + renderer.shader.bind(shader); + renderer.geometry.bind(geometry, shader); + renderer.state.set(this.state); + for (let i = 0, l = drawCalls.length; i < l; i++) { + this._renderDrawCallDirect(renderer, geometry.drawCalls[i]); + } + } + _renderDrawCallDirect(renderer, drawCall) { + const { texArray, type, size, start } = drawCall; + const groupTextureCount = texArray.count; + for (let j = 0; j < groupTextureCount; j++) { + renderer.texture.bind(texArray.elements[j], j); + } + renderer.geometry.draw(type, size, start); + } + _resolveDirectShader(renderer) { + let shader = this.shader; + const pluginName = this.pluginName; + if (!shader) { + if (!DEFAULT_SHADERS[pluginName]) { + const { maxTextures } = renderer.plugins[pluginName]; + const sampleValues = new Int32Array(maxTextures); + for (let i = 0; i < maxTextures; i++) { + sampleValues[i] = i; + } + const uniforms = { + tint: new Float32Array([1, 1, 1, 1]), + translationMatrix: new Matrix(), + default: UniformGroup.from({ uSamplers: sampleValues }, true) + }; + const program = renderer.plugins[pluginName]._shader.program; + DEFAULT_SHADERS[pluginName] = new Shader(program, uniforms); + } + shader = DEFAULT_SHADERS[pluginName]; + } + return shader; + } + _calculateBounds() { + this.finishPoly(); + const geometry = this._geometry; + if (!geometry.graphicsData.length) { + return; + } + const { minX, minY, maxX, maxY } = geometry.bounds; + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + } + containsPoint(point) { + this.worldTransform.applyInverse(point, _Graphics._TEMP_POINT); + return this._geometry.containsPoint(_Graphics._TEMP_POINT); + } + calculateTints() { + if (this.batchTint !== this.tint) { + this.batchTint = this._tintColor.toNumber(); + for (let i = 0; i < this.batches.length; i++) { + const batch = this.batches[i]; + batch._tintRGB = Color.shared.setValue(this._tintColor).multiply(batch._batchRGB).toLittleEndianNumber(); + } + } + } + calculateVertices() { + const wtID = this.transform._worldID; + if (this._transformID === wtID) { + return; + } + this._transformID = wtID; + const wt = this.transform.worldTransform; + const a = wt.a; + const b = wt.b; + const c = wt.c; + const d = wt.d; + const tx = wt.tx; + const ty = wt.ty; + const data = this._geometry.points; + const vertexData = this.vertexData; + let count = 0; + for (let i = 0; i < data.length; i += 2) { + const x = data[i]; + const y = data[i + 1]; + vertexData[count++] = a * x + c * y + tx; + vertexData[count++] = d * y + b * x + ty; + } + } + closePath() { + const currentPath = this.currentPath; + if (currentPath) { + currentPath.closeStroke = true; + this.finishPoly(); + } + return this; + } + setMatrix(matrix) { + this._matrix = matrix; + return this; + } + beginHole() { + this.finishPoly(); + this._holeMode = true; + return this; + } + endHole() { + this.finishPoly(); + this._holeMode = false; + return this; + } + destroy(options) { + this._geometry.refCount--; + if (this._geometry.refCount === 0) { + this._geometry.dispose(); + } + this._matrix = null; + this.currentPath = null; + this._lineStyle.destroy(); + this._lineStyle = null; + this._fillStyle.destroy(); + this._fillStyle = null; + this._geometry = null; + this.shader = null; + this.vertexData = null; + this.batches.length = 0; + this.batches = null; + super.destroy(options); + } + }; + let Graphics = _Graphics; + Graphics.curves = curves; + Graphics._TEMP_POINT = new Point(); + + const graphicsUtils = { + buildPoly, + buildCircle, + buildRectangle, + buildRoundedRectangle, + buildLine, + ArcUtils, + BezierUtils, + QuadraticUtils, + BatchPart, + FILL_COMMANDS, + BATCH_POOL, + DRAW_CALL_POOL + }; + + class MeshBatchUvs { + constructor(uvBuffer, uvMatrix) { + this.uvBuffer = uvBuffer; + this.uvMatrix = uvMatrix; + this.data = null; + this._bufferUpdateId = -1; + this._textureUpdateId = -1; + this._updateID = 0; + } + update(forceUpdate) { + if (!forceUpdate && this._bufferUpdateId === this.uvBuffer._updateID && this._textureUpdateId === this.uvMatrix._updateID) { + return; + } + this._bufferUpdateId = this.uvBuffer._updateID; + this._textureUpdateId = this.uvMatrix._updateID; + const data = this.uvBuffer.data; + if (!this.data || this.data.length !== data.length) { + this.data = new Float32Array(data.length); + } + this.uvMatrix.multiplyUvs(data, this.data); + this._updateID++; + } + } + + const tempPoint = new Point(); + const tempPolygon = new Polygon(); + const _Mesh = class extends Container { + constructor(geometry, shader, state, drawMode = DRAW_MODES.TRIANGLES) { + super(); + this.geometry = geometry; + this.shader = shader; + this.state = state || State.for2d(); + this.drawMode = drawMode; + this.start = 0; + this.size = 0; + this.uvs = null; + this.indices = null; + this.vertexData = new Float32Array(1); + this.vertexDirty = -1; + this._transformID = -1; + this._roundPixels = settings.ROUND_PIXELS; + this.batchUvs = null; + } + get geometry() { + return this._geometry; + } + set geometry(value) { + if (this._geometry === value) { + return; + } + if (this._geometry) { + this._geometry.refCount--; + if (this._geometry.refCount === 0) { + this._geometry.dispose(); + } + } + this._geometry = value; + if (this._geometry) { + this._geometry.refCount++; + } + this.vertexDirty = -1; + } + get uvBuffer() { + return this.geometry.buffers[1]; + } + get verticesBuffer() { + return this.geometry.buffers[0]; + } + set material(value) { + this.shader = value; + } + get material() { + return this.shader; + } + set blendMode(value) { + this.state.blendMode = value; + } + get blendMode() { + return this.state.blendMode; + } + set roundPixels(value) { + if (this._roundPixels !== value) { + this._transformID = -1; + } + this._roundPixels = value; + } + get roundPixels() { + return this._roundPixels; + } + get tint() { + return "tint" in this.shader ? this.shader.tint : null; + } + set tint(value) { + this.shader.tint = value; + } + get tintValue() { + return this.shader.tintValue; + } + get texture() { + return "texture" in this.shader ? this.shader.texture : null; + } + set texture(value) { + this.shader.texture = value; + } + _render(renderer) { + const vertices = this.geometry.buffers[0].data; + const shader = this.shader; + if (shader.batchable && this.drawMode === DRAW_MODES.TRIANGLES && vertices.length < _Mesh.BATCHABLE_SIZE * 2) { + this._renderToBatch(renderer); + } else { + this._renderDefault(renderer); + } + } + _renderDefault(renderer) { + const shader = this.shader; + shader.alpha = this.worldAlpha; + if (shader.update) { + shader.update(); + } + renderer.batch.flush(); + shader.uniforms.translationMatrix = this.transform.worldTransform.toArray(true); + renderer.shader.bind(shader); + renderer.state.set(this.state); + renderer.geometry.bind(this.geometry, shader); + renderer.geometry.draw(this.drawMode, this.size, this.start, this.geometry.instanceCount); + } + _renderToBatch(renderer) { + const geometry = this.geometry; + const shader = this.shader; + if (shader.uvMatrix) { + shader.uvMatrix.update(); + this.calculateUvs(); + } + this.calculateVertices(); + this.indices = geometry.indexBuffer.data; + this._tintRGB = shader._tintRGB; + this._texture = shader.texture; + const pluginName = this.material.pluginName; + renderer.batch.setObjectRenderer(renderer.plugins[pluginName]); + renderer.plugins[pluginName].render(this); + } + calculateVertices() { + const geometry = this.geometry; + const verticesBuffer = geometry.buffers[0]; + const vertices = verticesBuffer.data; + const vertexDirtyId = verticesBuffer._updateID; + if (vertexDirtyId === this.vertexDirty && this._transformID === this.transform._worldID) { + return; + } + this._transformID = this.transform._worldID; + if (this.vertexData.length !== vertices.length) { + this.vertexData = new Float32Array(vertices.length); + } + const wt = this.transform.worldTransform; + const a = wt.a; + const b = wt.b; + const c = wt.c; + const d = wt.d; + const tx = wt.tx; + const ty = wt.ty; + const vertexData = this.vertexData; + for (let i = 0; i < vertexData.length / 2; i++) { + const x = vertices[i * 2]; + const y = vertices[i * 2 + 1]; + vertexData[i * 2] = a * x + c * y + tx; + vertexData[i * 2 + 1] = b * x + d * y + ty; + } + if (this._roundPixels) { + const resolution = settings.RESOLUTION; + for (let i = 0; i < vertexData.length; ++i) { + vertexData[i] = Math.round(vertexData[i] * resolution) / resolution; + } + } + this.vertexDirty = vertexDirtyId; + } + calculateUvs() { + const geomUvs = this.geometry.buffers[1]; + const shader = this.shader; + if (!shader.uvMatrix.isSimple) { + if (!this.batchUvs) { + this.batchUvs = new MeshBatchUvs(geomUvs, shader.uvMatrix); + } + this.batchUvs.update(); + this.uvs = this.batchUvs.data; + } else { + this.uvs = geomUvs.data; + } + } + _calculateBounds() { + this.calculateVertices(); + this._bounds.addVertexData(this.vertexData, 0, this.vertexData.length); + } + containsPoint(point) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + this.worldTransform.applyInverse(point, tempPoint); + const vertices = this.geometry.getBuffer("aVertexPosition").data; + const points = tempPolygon.points; + const indices = this.geometry.getIndex().data; + const len = indices.length; + const step = this.drawMode === 4 ? 3 : 1; + for (let i = 0; i + 2 < len; i += step) { + const ind0 = indices[i] * 2; + const ind1 = indices[i + 1] * 2; + const ind2 = indices[i + 2] * 2; + points[0] = vertices[ind0]; + points[1] = vertices[ind0 + 1]; + points[2] = vertices[ind1]; + points[3] = vertices[ind1 + 1]; + points[4] = vertices[ind2]; + points[5] = vertices[ind2 + 1]; + if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + return false; + } + destroy(options) { + super.destroy(options); + if (this._cachedTexture) { + this._cachedTexture.destroy(); + this._cachedTexture = null; + } + this.geometry = null; + this.shader = null; + this.state = null; + this.uvs = null; + this.indices = null; + this.vertexData = null; + } + }; + let Mesh = _Mesh; + Mesh.BATCHABLE_SIZE = 100; + + class MeshGeometry extends Geometry { + constructor(vertices, uvs, index) { + super(); + const verticesBuffer = new Buffer(vertices); + const uvsBuffer = new Buffer(uvs, true); + const indexBuffer = new Buffer(index, true, true); + this.addAttribute("aVertexPosition", verticesBuffer, 2, false, TYPES.FLOAT).addAttribute("aTextureCoord", uvsBuffer, 2, false, TYPES.FLOAT).addIndex(indexBuffer); + this._updateId = -1; + } + get vertexDirtyId() { + return this.buffers[0]._updateID; + } + } + + var fragment = "varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n"; + + var vertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTextureMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\n}\n"; + + class MeshMaterial extends Shader { + constructor(uSampler, options) { + const uniforms = { + uSampler, + alpha: 1, + uTextureMatrix: Matrix.IDENTITY, + uColor: new Float32Array([1, 1, 1, 1]) + }; + options = Object.assign({ + tint: 16777215, + alpha: 1, + pluginName: "batch" + }, options); + if (options.uniforms) { + Object.assign(uniforms, options.uniforms); + } + super(options.program || Program.from(vertex, fragment), uniforms); + this._colorDirty = false; + this.uvMatrix = new TextureMatrix(uSampler); + this.batchable = options.program === void 0; + this.pluginName = options.pluginName; + this._tintColor = new Color(options.tint); + this._tintRGB = this._tintColor.toLittleEndianNumber(); + this._colorDirty = true; + this.alpha = options.alpha; + } + get texture() { + return this.uniforms.uSampler; + } + set texture(value) { + if (this.uniforms.uSampler !== value) { + if (!this.uniforms.uSampler.baseTexture.alphaMode !== !value.baseTexture.alphaMode) { + this._colorDirty = true; + } + this.uniforms.uSampler = value; + this.uvMatrix.texture = value; + } + } + set alpha(value) { + if (value === this._alpha) + return; + this._alpha = value; + this._colorDirty = true; + } + get alpha() { + return this._alpha; + } + set tint(value) { + if (value === this.tint) + return; + this._tintColor.setValue(value); + this._tintRGB = this._tintColor.toLittleEndianNumber(); + this._colorDirty = true; + } + get tint() { + return this._tintColor.value; + } + get tintValue() { + return this._tintColor.toNumber(); + } + update() { + if (this._colorDirty) { + this._colorDirty = false; + const baseTexture = this.texture.baseTexture; + const applyToChannels = baseTexture.alphaMode; + Color.shared.setValue(this._tintColor).premultiply(this._alpha, applyToChannels).toArray(this.uniforms.uColor); + } + if (this.uvMatrix.update()) { + this.uniforms.uTextureMatrix = this.uvMatrix.mapCoord; + } + } + } + + class PlaneGeometry extends MeshGeometry { + constructor(width = 100, height = 100, segWidth = 10, segHeight = 10) { + super(); + this.segWidth = segWidth; + this.segHeight = segHeight; + this.width = width; + this.height = height; + this.build(); + } + build() { + const total = this.segWidth * this.segHeight; + const verts = []; + const uvs = []; + const indices = []; + const segmentsX = this.segWidth - 1; + const segmentsY = this.segHeight - 1; + const sizeX = this.width / segmentsX; + const sizeY = this.height / segmentsY; + for (let i = 0; i < total; i++) { + const x = i % this.segWidth; + const y = i / this.segWidth | 0; + verts.push(x * sizeX, y * sizeY); + uvs.push(x / segmentsX, y / segmentsY); + } + const totalSub = segmentsX * segmentsY; + for (let i = 0; i < totalSub; i++) { + const xpos = i % segmentsX; + const ypos = i / segmentsX | 0; + const value = ypos * this.segWidth + xpos; + const value2 = ypos * this.segWidth + xpos + 1; + const value3 = (ypos + 1) * this.segWidth + xpos; + const value4 = (ypos + 1) * this.segWidth + xpos + 1; + indices.push(value, value2, value3, value2, value4, value3); + } + this.buffers[0].data = new Float32Array(verts); + this.buffers[1].data = new Float32Array(uvs); + this.indexBuffer.data = new Uint16Array(indices); + this.buffers[0].update(); + this.buffers[1].update(); + this.indexBuffer.update(); + } + } + + class RopeGeometry extends MeshGeometry { + constructor(width = 200, points, textureScale = 0) { + super(new Float32Array(points.length * 4), new Float32Array(points.length * 4), new Uint16Array((points.length - 1) * 6)); + this.points = points; + this._width = width; + this.textureScale = textureScale; + this.build(); + } + get width() { + return this._width; + } + build() { + const points = this.points; + if (!points) + return; + const vertexBuffer = this.getBuffer("aVertexPosition"); + const uvBuffer = this.getBuffer("aTextureCoord"); + const indexBuffer = this.getIndex(); + if (points.length < 1) { + return; + } + if (vertexBuffer.data.length / 4 !== points.length) { + vertexBuffer.data = new Float32Array(points.length * 4); + uvBuffer.data = new Float32Array(points.length * 4); + indexBuffer.data = new Uint16Array((points.length - 1) * 6); + } + const uvs = uvBuffer.data; + const indices = indexBuffer.data; + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + let amount = 0; + let prev = points[0]; + const textureWidth = this._width * this.textureScale; + const total = points.length; + for (let i = 0; i < total; i++) { + const index = i * 4; + if (this.textureScale > 0) { + const dx = prev.x - points[i].x; + const dy = prev.y - points[i].y; + const distance = Math.sqrt(dx * dx + dy * dy); + prev = points[i]; + amount += distance / textureWidth; + } else { + amount = i / (total - 1); + } + uvs[index] = amount; + uvs[index + 1] = 0; + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + let indexCount = 0; + for (let i = 0; i < total - 1; i++) { + const index = i * 2; + indices[indexCount++] = index; + indices[indexCount++] = index + 1; + indices[indexCount++] = index + 2; + indices[indexCount++] = index + 2; + indices[indexCount++] = index + 1; + indices[indexCount++] = index + 3; + } + uvBuffer.update(); + indexBuffer.update(); + this.updateVertices(); + } + updateVertices() { + const points = this.points; + if (points.length < 1) { + return; + } + let lastPoint = points[0]; + let nextPoint; + let perpX = 0; + let perpY = 0; + const vertices = this.buffers[0].data; + const total = points.length; + const halfWidth = this.textureScale > 0 ? this.textureScale * this._width / 2 : this._width / 2; + for (let i = 0; i < total; i++) { + const point = points[i]; + const index = i * 4; + if (i < points.length - 1) { + nextPoint = points[i + 1]; + } else { + nextPoint = point; + } + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + let ratio = (1 - i / (total - 1)) * 10; + if (ratio > 1) { + ratio = 1; + } + const perpLength = Math.sqrt(perpX * perpX + perpY * perpY); + if (perpLength < 1e-6) { + perpX = 0; + perpY = 0; + } else { + perpX /= perpLength; + perpY /= perpLength; + perpX *= halfWidth; + perpY *= halfWidth; + } + vertices[index] = point.x + perpX; + vertices[index + 1] = point.y + perpY; + vertices[index + 2] = point.x - perpX; + vertices[index + 3] = point.y - perpY; + lastPoint = point; + } + this.buffers[0].update(); + } + update() { + if (this.textureScale > 0) { + this.build(); + } else { + this.updateVertices(); + } + } + } + + class SimplePlane extends Mesh { + constructor(texture, verticesX, verticesY) { + const planeGeometry = new PlaneGeometry(texture.width, texture.height, verticesX, verticesY); + const meshMaterial = new MeshMaterial(Texture.WHITE); + super(planeGeometry, meshMaterial); + this.texture = texture; + this.autoResize = true; + } + textureUpdated() { + this._textureID = this.shader.texture._updateID; + const geometry = this.geometry; + const { width, height } = this.shader.texture; + if (this.autoResize && (geometry.width !== width || geometry.height !== height)) { + geometry.width = this.shader.texture.width; + geometry.height = this.shader.texture.height; + geometry.build(); + } + } + set texture(value) { + if (this.shader.texture === value) { + return; + } + this.shader.texture = value; + this._textureID = -1; + if (value.baseTexture.valid) { + this.textureUpdated(); + } else { + value.once("update", this.textureUpdated, this); + } + } + get texture() { + return this.shader.texture; + } + _render(renderer) { + if (this._textureID !== this.shader.texture._updateID) { + this.textureUpdated(); + } + super._render(renderer); + } + destroy(options) { + this.shader.texture.off("update", this.textureUpdated, this); + super.destroy(options); + } + } + + const DEFAULT_BORDER_SIZE = 10; + class NineSlicePlane extends SimplePlane { + constructor(texture, leftWidth, topHeight, rightWidth, bottomHeight) { + super(Texture.WHITE, 4, 4); + this._origWidth = texture.orig.width; + this._origHeight = texture.orig.height; + this._width = this._origWidth; + this._height = this._origHeight; + this._leftWidth = leftWidth ?? texture.defaultBorders?.left ?? DEFAULT_BORDER_SIZE; + this._rightWidth = rightWidth ?? texture.defaultBorders?.right ?? DEFAULT_BORDER_SIZE; + this._topHeight = topHeight ?? texture.defaultBorders?.top ?? DEFAULT_BORDER_SIZE; + this._bottomHeight = bottomHeight ?? texture.defaultBorders?.bottom ?? DEFAULT_BORDER_SIZE; + this.texture = texture; + } + textureUpdated() { + this._textureID = this.shader.texture._updateID; + this._refresh(); + } + get vertices() { + return this.geometry.getBuffer("aVertexPosition").data; + } + set vertices(value) { + this.geometry.getBuffer("aVertexPosition").data = value; + } + updateHorizontalVertices() { + const vertices = this.vertices; + const scale = this._getMinScale(); + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight * scale; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - this._bottomHeight * scale; + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; + } + updateVerticalVertices() { + const vertices = this.vertices; + const scale = this._getMinScale(); + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth * scale; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - this._rightWidth * scale; + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; + } + _getMinScale() { + const w = this._leftWidth + this._rightWidth; + const scaleW = this._width > w ? 1 : this._width / w; + const h = this._topHeight + this._bottomHeight; + const scaleH = this._height > h ? 1 : this._height / h; + const scale = Math.min(scaleW, scaleH); + return scale; + } + get width() { + return this._width; + } + set width(value) { + this._width = value; + this._refresh(); + } + get height() { + return this._height; + } + set height(value) { + this._height = value; + this._refresh(); + } + get leftWidth() { + return this._leftWidth; + } + set leftWidth(value) { + this._leftWidth = value; + this._refresh(); + } + get rightWidth() { + return this._rightWidth; + } + set rightWidth(value) { + this._rightWidth = value; + this._refresh(); + } + get topHeight() { + return this._topHeight; + } + set topHeight(value) { + this._topHeight = value; + this._refresh(); + } + get bottomHeight() { + return this._bottomHeight; + } + set bottomHeight(value) { + this._bottomHeight = value; + this._refresh(); + } + _refresh() { + const texture = this.texture; + const uvs = this.geometry.buffers[1].data; + this._origWidth = texture.orig.width; + this._origHeight = texture.orig.height; + const _uvw = 1 / this._origWidth; + const _uvh = 1 / this._origHeight; + uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0; + uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0; + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - _uvw * this._rightWidth; + uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - _uvh * this._bottomHeight; + this.updateHorizontalVertices(); + this.updateVerticalVertices(); + this.geometry.buffers[0].update(); + this.geometry.buffers[1].update(); + } + } + + class SimpleMesh extends Mesh { + constructor(texture = Texture.EMPTY, vertices, uvs, indices, drawMode) { + const geometry = new MeshGeometry(vertices, uvs, indices); + geometry.getBuffer("aVertexPosition").static = false; + const meshMaterial = new MeshMaterial(texture); + super(geometry, meshMaterial, null, drawMode); + this.autoUpdate = true; + } + get vertices() { + return this.geometry.getBuffer("aVertexPosition").data; + } + set vertices(value) { + this.geometry.getBuffer("aVertexPosition").data = value; + } + _render(renderer) { + if (this.autoUpdate) { + this.geometry.getBuffer("aVertexPosition").update(); + } + super._render(renderer); + } + } + + class SimpleRope extends Mesh { + constructor(texture, points, textureScale = 0) { + const ropeGeometry = new RopeGeometry(texture.height, points, textureScale); + const meshMaterial = new MeshMaterial(texture); + if (textureScale > 0) { + texture.baseTexture.wrapMode = WRAP_MODES.REPEAT; + } + super(ropeGeometry, meshMaterial); + this.autoUpdate = true; + } + _render(renderer) { + const geometry = this.geometry; + if (this.autoUpdate || geometry._width !== this.shader.texture.height) { + geometry._width = this.shader.texture.height; + geometry.update(); + } + super._render(renderer); + } + } + + class CountLimiter { + constructor(maxItemsPerFrame) { + this.maxItemsPerFrame = maxItemsPerFrame; + this.itemsLeft = 0; + } + beginFrame() { + this.itemsLeft = this.maxItemsPerFrame; + } + allowedToUpload() { + return this.itemsLeft-- > 0; + } + } + + function findMultipleBaseTextures(item, queue) { + let result = false; + if (item?._textures?.length) { + for (let i = 0; i < item._textures.length; i++) { + if (item._textures[i] instanceof Texture) { + const baseTexture = item._textures[i].baseTexture; + if (!queue.includes(baseTexture)) { + queue.push(baseTexture); + result = true; + } + } + } + } + return result; + } + function findBaseTexture(item, queue) { + if (item.baseTexture instanceof BaseTexture) { + const texture = item.baseTexture; + if (!queue.includes(texture)) { + queue.push(texture); + } + return true; + } + return false; + } + function findTexture(item, queue) { + if (item._texture && item._texture instanceof Texture) { + const texture = item._texture.baseTexture; + if (!queue.includes(texture)) { + queue.push(texture); + } + return true; + } + return false; + } + function drawText(_helper, item) { + if (item instanceof Text) { + item.updateText(true); + return true; + } + return false; + } + function calculateTextStyle(_helper, item) { + if (item instanceof TextStyle) { + const font = item.toFontString(); + TextMetrics.measureFont(font); + return true; + } + return false; + } + function findText(item, queue) { + if (item instanceof Text) { + if (!queue.includes(item.style)) { + queue.push(item.style); + } + if (!queue.includes(item)) { + queue.push(item); + } + const texture = item._texture.baseTexture; + if (!queue.includes(texture)) { + queue.push(texture); + } + return true; + } + return false; + } + function findTextStyle(item, queue) { + if (item instanceof TextStyle) { + if (!queue.includes(item)) { + queue.push(item); + } + return true; + } + return false; + } + const _BasePrepare = class { + constructor(renderer) { + this.limiter = new CountLimiter(_BasePrepare.uploadsPerFrame); + this.renderer = renderer; + this.uploadHookHelper = null; + this.queue = []; + this.addHooks = []; + this.uploadHooks = []; + this.completes = []; + this.ticking = false; + this.delayedTick = () => { + if (!this.queue) { + return; + } + this.prepareItems(); + }; + this.registerFindHook(findText); + this.registerFindHook(findTextStyle); + this.registerFindHook(findMultipleBaseTextures); + this.registerFindHook(findBaseTexture); + this.registerFindHook(findTexture); + this.registerUploadHook(drawText); + this.registerUploadHook(calculateTextStyle); + } + upload(item) { + return new Promise((resolve) => { + if (item) { + this.add(item); + } + if (this.queue.length) { + this.completes.push(resolve); + if (!this.ticking) { + this.ticking = true; + Ticker.system.addOnce(this.tick, this, UPDATE_PRIORITY.UTILITY); + } + } else { + resolve(); + } + }); + } + tick() { + setTimeout(this.delayedTick, 0); + } + prepareItems() { + this.limiter.beginFrame(); + while (this.queue.length && this.limiter.allowedToUpload()) { + const item = this.queue[0]; + let uploaded = false; + if (item && !item._destroyed) { + for (let i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this.uploadHookHelper, item)) { + this.queue.shift(); + uploaded = true; + break; + } + } + } + if (!uploaded) { + this.queue.shift(); + } + } + if (!this.queue.length) { + this.ticking = false; + const completes = this.completes.slice(0); + this.completes.length = 0; + for (let i = 0, len = completes.length; i < len; i++) { + completes[i](); + } + } else { + Ticker.system.addOnce(this.tick, this, UPDATE_PRIORITY.UTILITY); + } + } + registerFindHook(addHook) { + if (addHook) { + this.addHooks.push(addHook); + } + return this; + } + registerUploadHook(uploadHook) { + if (uploadHook) { + this.uploadHooks.push(uploadHook); + } + return this; + } + add(item) { + for (let i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } + } + if (item instanceof Container) { + for (let i = item.children.length - 1; i >= 0; i--) { + this.add(item.children[i]); + } + } + return this; + } + destroy() { + if (this.ticking) { + Ticker.system.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + this.limiter = null; + this.uploadHookHelper = null; + } + }; + let BasePrepare = _BasePrepare; + BasePrepare.uploadsPerFrame = 4; + + Object.defineProperties(settings, { + UPLOADS_PER_FRAME: { + get() { + return BasePrepare.uploadsPerFrame; + }, + set(value) { + deprecation$1("7.1.0", "settings.UPLOADS_PER_FRAME is deprecated, use prepare.BasePrepare.uploadsPerFrame"); + BasePrepare.uploadsPerFrame = value; + } + } + }); + + function uploadBaseTextures$1(renderer, item) { + if (item instanceof BaseTexture) { + if (!item._glTextures[renderer.CONTEXT_UID]) { + renderer.texture.bind(item); + } + return true; + } + return false; + } + function uploadGraphics(renderer, item) { + if (!(item instanceof Graphics)) { + return false; + } + const { geometry } = item; + item.finishPoly(); + geometry.updateBatches(); + const { batches } = geometry; + for (let i = 0; i < batches.length; i++) { + const { texture } = batches[i].style; + if (texture) { + uploadBaseTextures$1(renderer, texture.baseTexture); + } + } + if (!geometry.batchable) { + renderer.geometry.bind(geometry, item._resolveDirectShader(renderer)); + } + return true; + } + function findGraphics(item, queue) { + if (item instanceof Graphics) { + queue.push(item); + return true; + } + return false; + } + class Prepare extends BasePrepare { + constructor(renderer) { + super(renderer); + this.uploadHookHelper = this.renderer; + this.registerFindHook(findGraphics); + this.registerUploadHook(uploadBaseTextures$1); + this.registerUploadHook(uploadGraphics); + } + } + Prepare.extension = { + name: "prepare", + type: ExtensionType.RendererSystem + }; + extensions$1.add(Prepare); + + class TimeLimiter { + constructor(maxMilliseconds) { + this.maxMilliseconds = maxMilliseconds; + this.frameStart = 0; + } + beginFrame() { + this.frameStart = Date.now(); + } + allowedToUpload() { + return Date.now() - this.frameStart < this.maxMilliseconds; + } + } + + class AnimatedSprite extends Sprite { + constructor(textures, autoUpdate = true) { + super(textures[0] instanceof Texture ? textures[0] : textures[0].texture); + this._textures = null; + this._durations = null; + this._autoUpdate = autoUpdate; + this._isConnectedToTicker = false; + this.animationSpeed = 1; + this.loop = true; + this.updateAnchor = false; + this.onComplete = null; + this.onFrameChange = null; + this.onLoop = null; + this._currentTime = 0; + this._playing = false; + this._previousFrame = null; + this.textures = textures; + } + stop() { + if (!this._playing) { + return; + } + this._playing = false; + if (this._autoUpdate && this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + } + play() { + if (this._playing) { + return; + } + this._playing = true; + if (this._autoUpdate && !this._isConnectedToTicker) { + Ticker.shared.add(this.update, this, UPDATE_PRIORITY.HIGH); + this._isConnectedToTicker = true; + } + } + gotoAndStop(frameNumber) { + this.stop(); + this.currentFrame = frameNumber; + } + gotoAndPlay(frameNumber) { + this.currentFrame = frameNumber; + this.play(); + } + update(deltaTime) { + if (!this._playing) { + return; + } + const elapsed = this.animationSpeed * deltaTime; + const previousFrame = this.currentFrame; + if (this._durations !== null) { + let lag = this._currentTime % 1 * this._durations[this.currentFrame]; + lag += elapsed / 60 * 1e3; + while (lag < 0) { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + const sign = Math.sign(this.animationSpeed * deltaTime); + this._currentTime = Math.floor(this._currentTime); + while (lag >= this._durations[this.currentFrame]) { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + this._currentTime += lag / this._durations[this.currentFrame]; + } else { + this._currentTime += elapsed; + } + if (this._currentTime < 0 && !this.loop) { + this.gotoAndStop(0); + if (this.onComplete) { + this.onComplete(); + } + } else if (this._currentTime >= this._textures.length && !this.loop) { + this.gotoAndStop(this._textures.length - 1); + if (this.onComplete) { + this.onComplete(); + } + } else if (previousFrame !== this.currentFrame) { + if (this.loop && this.onLoop) { + if (this.animationSpeed > 0 && this.currentFrame < previousFrame || this.animationSpeed < 0 && this.currentFrame > previousFrame) { + this.onLoop(); + } + } + this.updateTexture(); + } + } + updateTexture() { + const currentFrame = this.currentFrame; + if (this._previousFrame === currentFrame) { + return; + } + this._previousFrame = currentFrame; + this._texture = this._textures[currentFrame]; + this._textureID = -1; + this._textureTrimmedID = -1; + this._cachedTint = 16777215; + this.uvs = this._texture._uvs.uvsFloat32; + if (this.updateAnchor) { + this._anchor.copyFrom(this._texture.defaultAnchor); + } + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + } + destroy(options) { + this.stop(); + super.destroy(options); + this.onComplete = null; + this.onFrameChange = null; + this.onLoop = null; + } + static fromFrames(frames) { + const textures = []; + for (let i = 0; i < frames.length; ++i) { + textures.push(Texture.from(frames[i])); + } + return new AnimatedSprite(textures); + } + static fromImages(images) { + const textures = []; + for (let i = 0; i < images.length; ++i) { + textures.push(Texture.from(images[i])); + } + return new AnimatedSprite(textures); + } + get totalFrames() { + return this._textures.length; + } + get textures() { + return this._textures; + } + set textures(value) { + if (value[0] instanceof Texture) { + this._textures = value; + this._durations = null; + } else { + this._textures = []; + this._durations = []; + for (let i = 0; i < value.length; i++) { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + this._previousFrame = null; + this.gotoAndStop(0); + this.updateTexture(); + } + get currentFrame() { + let currentFrame = Math.floor(this._currentTime) % this._textures.length; + if (currentFrame < 0) { + currentFrame += this._textures.length; + } + return currentFrame; + } + set currentFrame(value) { + if (value < 0 || value > this.totalFrames - 1) { + throw new Error(`[AnimatedSprite]: Invalid frame index value ${value}, expected to be between 0 and totalFrames ${this.totalFrames}.`); + } + const previousFrame = this.currentFrame; + this._currentTime = value; + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + } + get playing() { + return this._playing; + } + get autoUpdate() { + return this._autoUpdate; + } + set autoUpdate(value) { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + if (!this._autoUpdate && this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } else if (this._autoUpdate && !this._isConnectedToTicker && this._playing) { + Ticker.shared.add(this.update, this); + this._isConnectedToTicker = true; + } + } + } + } + + const _Spritesheet = class { + constructor(texture, data, resolutionFilename = null) { + this.linkedSheets = []; + this._texture = texture instanceof Texture ? texture : null; + this.baseTexture = texture instanceof BaseTexture ? texture : this._texture.baseTexture; + this.textures = {}; + this.animations = {}; + this.data = data; + const resource = this.baseTexture.resource; + this.resolution = this._updateResolution(resolutionFilename || (resource ? resource.url : null)); + this._frames = this.data.frames; + this._frameKeys = Object.keys(this._frames); + this._batchIndex = 0; + this._callback = null; + } + _updateResolution(resolutionFilename = null) { + const { scale } = this.data.meta; + let resolution = getResolutionOfUrl(resolutionFilename, null); + if (resolution === null) { + resolution = parseFloat(scale ?? "1"); + } + if (resolution !== 1) { + this.baseTexture.setResolution(resolution); + } + return resolution; + } + parse() { + return new Promise((resolve) => { + this._callback = resolve; + this._batchIndex = 0; + if (this._frameKeys.length <= _Spritesheet.BATCH_SIZE) { + this._processFrames(0); + this._processAnimations(); + this._parseComplete(); + } else { + this._nextBatch(); + } + }); + } + _processFrames(initialFrameIndex) { + let frameIndex = initialFrameIndex; + const maxFrames = _Spritesheet.BATCH_SIZE; + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { + const i = this._frameKeys[frameIndex]; + const data = this._frames[i]; + const rect = data.frame; + if (rect) { + let frame = null; + let trim = null; + const sourceSize = data.trimmed !== false && data.sourceSize ? data.sourceSize : data.frame; + const orig = new Rectangle(0, 0, Math.floor(sourceSize.w) / this.resolution, Math.floor(sourceSize.h) / this.resolution); + if (data.rotated) { + frame = new Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.h) / this.resolution, Math.floor(rect.w) / this.resolution); + } else { + frame = new Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution); + } + if (data.trimmed !== false && data.spriteSourceSize) { + trim = new Rectangle(Math.floor(data.spriteSourceSize.x) / this.resolution, Math.floor(data.spriteSourceSize.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution); + } + this.textures[i] = new Texture(this.baseTexture, frame, orig, trim, data.rotated ? 2 : 0, data.anchor, data.borders); + Texture.addToCache(this.textures[i], i); + } + frameIndex++; + } + } + _processAnimations() { + const animations = this.data.animations || {}; + for (const animName in animations) { + this.animations[animName] = []; + for (let i = 0; i < animations[animName].length; i++) { + const frameName = animations[animName][i]; + this.animations[animName].push(this.textures[frameName]); + } + } + } + _parseComplete() { + const callback = this._callback; + this._callback = null; + this._batchIndex = 0; + callback.call(this, this.textures); + } + _nextBatch() { + this._processFrames(this._batchIndex * _Spritesheet.BATCH_SIZE); + this._batchIndex++; + setTimeout(() => { + if (this._batchIndex * _Spritesheet.BATCH_SIZE < this._frameKeys.length) { + this._nextBatch(); + } else { + this._processAnimations(); + this._parseComplete(); + } + }, 0); + } + destroy(destroyBase = false) { + for (const i in this.textures) { + this.textures[i].destroy(); + } + this._frames = null; + this._frameKeys = null; + this.data = null; + this.textures = null; + if (destroyBase) { + this._texture?.destroy(); + this.baseTexture.destroy(); + } + this._texture = null; + this.baseTexture = null; + this.linkedSheets = []; + } + }; + let Spritesheet = _Spritesheet; + Spritesheet.BATCH_SIZE = 1e3; + + const validImages = ["jpg", "png", "jpeg", "avif", "webp"]; + function getCacheableAssets(keys, asset, ignoreMultiPack) { + const out = {}; + keys.forEach((key) => { + out[key] = asset; + }); + Object.keys(asset.textures).forEach((key) => { + out[key] = asset.textures[key]; + }); + if (!ignoreMultiPack) { + const basePath = path.dirname(keys[0]); + asset.linkedSheets.forEach((item, i) => { + const out2 = getCacheableAssets([`${basePath}/${asset.data.meta.related_multi_packs[i]}`], item, true); + Object.assign(out, out2); + }); + } + return out; + } + const spritesheetAsset = { + extension: ExtensionType.Asset, + cache: { + test: (asset) => asset instanceof Spritesheet, + getCacheableAssets: (keys, asset) => getCacheableAssets(keys, asset, false) + }, + resolver: { + test: (value) => { + const tempURL = value.split("?")[0]; + const split = tempURL.split("."); + const extension = split.pop(); + const format = split.pop(); + return extension === "json" && validImages.includes(format); + }, + parse: (value) => { + const split = value.split("."); + return { + resolution: parseFloat(settings.RETINA_PREFIX.exec(value)?.[1] ?? "1"), + format: split[split.length - 2], + src: value + }; + } + }, + loader: { + name: "spritesheetLoader", + extension: { + type: ExtensionType.LoadParser, + priority: LoaderParserPriority.Normal + }, + async testParse(asset, options) { + return path.extname(options.src).toLowerCase() === ".json" && !!asset.frames; + }, + async parse(asset, options, loader) { + let basePath = path.dirname(options.src); + if (basePath && basePath.lastIndexOf("/") !== basePath.length - 1) { + basePath += "/"; + } + let imagePath = basePath + asset.meta.image; + imagePath = copySearchParams(imagePath, options.src); + const assets = await loader.load([imagePath]); + const texture = assets[imagePath]; + const spritesheet = new Spritesheet(texture.baseTexture, asset, options.src); + await spritesheet.parse(); + const multiPacks = asset?.meta?.related_multi_packs; + if (Array.isArray(multiPacks)) { + const promises = []; + for (const item of multiPacks) { + if (typeof item !== "string") { + continue; + } + let itemUrl = basePath + item; + if (options.data?.ignoreMultiPack) { + continue; + } + itemUrl = copySearchParams(itemUrl, options.src); + promises.push(loader.load({ + src: itemUrl, + data: { + ignoreMultiPack: true + } + })); + } + const res = await Promise.all(promises); + spritesheet.linkedSheets = res; + res.forEach((item) => { + item.linkedSheets = [spritesheet].concat(spritesheet.linkedSheets.filter((sp) => sp !== item)); + }); + } + return spritesheet; + }, + unload(spritesheet) { + spritesheet.destroy(true); + } + } + }; + extensions$1.add(spritesheetAsset); + + class BitmapFontData { + constructor() { + this.info = []; + this.common = []; + this.page = []; + this.char = []; + this.kerning = []; + this.distanceField = []; + } + } + + class TextFormat { + static test(data) { + return typeof data === "string" && data.startsWith("info face="); + } + static parse(txt) { + const items = txt.match(/^[a-z]+\s+.+$/gm); + const rawData = { + info: [], + common: [], + page: [], + char: [], + chars: [], + kerning: [], + kernings: [], + distanceField: [] + }; + for (const i in items) { + const name = items[i].match(/^[a-z]+/gm)[0]; + const attributeList = items[i].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm); + const itemData = {}; + for (const i2 in attributeList) { + const split = attributeList[i2].split("="); + const key = split[0]; + const strValue = split[1].replace(/"/gm, ""); + const floatValue = parseFloat(strValue); + const value = isNaN(floatValue) ? strValue : floatValue; + itemData[key] = value; + } + rawData[name].push(itemData); + } + const font = new BitmapFontData(); + rawData.info.forEach((info) => font.info.push({ + face: info.face, + size: parseInt(info.size, 10) + })); + rawData.common.forEach((common) => font.common.push({ + lineHeight: parseInt(common.lineHeight, 10) + })); + rawData.page.forEach((page) => font.page.push({ + id: parseInt(page.id, 10), + file: page.file + })); + rawData.char.forEach((char) => font.char.push({ + id: parseInt(char.id, 10), + page: parseInt(char.page, 10), + x: parseInt(char.x, 10), + y: parseInt(char.y, 10), + width: parseInt(char.width, 10), + height: parseInt(char.height, 10), + xoffset: parseInt(char.xoffset, 10), + yoffset: parseInt(char.yoffset, 10), + xadvance: parseInt(char.xadvance, 10) + })); + rawData.kerning.forEach((kerning) => font.kerning.push({ + first: parseInt(kerning.first, 10), + second: parseInt(kerning.second, 10), + amount: parseInt(kerning.amount, 10) + })); + rawData.distanceField.forEach((df) => font.distanceField.push({ + distanceRange: parseInt(df.distanceRange, 10), + fieldType: df.fieldType + })); + return font; + } + } + + class XMLFormat { + static test(data) { + const xml = data; + return "getElementsByTagName" in xml && xml.getElementsByTagName("page").length && xml.getElementsByTagName("info")[0].getAttribute("face") !== null; + } + static parse(xml) { + const data = new BitmapFontData(); + const info = xml.getElementsByTagName("info"); + const common = xml.getElementsByTagName("common"); + const page = xml.getElementsByTagName("page"); + const char = xml.getElementsByTagName("char"); + const kerning = xml.getElementsByTagName("kerning"); + const distanceField = xml.getElementsByTagName("distanceField"); + for (let i = 0; i < info.length; i++) { + data.info.push({ + face: info[i].getAttribute("face"), + size: parseInt(info[i].getAttribute("size"), 10) + }); + } + for (let i = 0; i < common.length; i++) { + data.common.push({ + lineHeight: parseInt(common[i].getAttribute("lineHeight"), 10) + }); + } + for (let i = 0; i < page.length; i++) { + data.page.push({ + id: parseInt(page[i].getAttribute("id"), 10) || 0, + file: page[i].getAttribute("file") + }); + } + for (let i = 0; i < char.length; i++) { + const letter = char[i]; + data.char.push({ + id: parseInt(letter.getAttribute("id"), 10), + page: parseInt(letter.getAttribute("page"), 10) || 0, + x: parseInt(letter.getAttribute("x"), 10), + y: parseInt(letter.getAttribute("y"), 10), + width: parseInt(letter.getAttribute("width"), 10), + height: parseInt(letter.getAttribute("height"), 10), + xoffset: parseInt(letter.getAttribute("xoffset"), 10), + yoffset: parseInt(letter.getAttribute("yoffset"), 10), + xadvance: parseInt(letter.getAttribute("xadvance"), 10) + }); + } + for (let i = 0; i < kerning.length; i++) { + data.kerning.push({ + first: parseInt(kerning[i].getAttribute("first"), 10), + second: parseInt(kerning[i].getAttribute("second"), 10), + amount: parseInt(kerning[i].getAttribute("amount"), 10) + }); + } + for (let i = 0; i < distanceField.length; i++) { + data.distanceField.push({ + fieldType: distanceField[i].getAttribute("fieldType"), + distanceRange: parseInt(distanceField[i].getAttribute("distanceRange"), 10) + }); + } + return data; + } + } + + class XMLStringFormat { + static test(data) { + if (typeof data === "string" && data.includes("")) { + return XMLFormat.test(settings.ADAPTER.parseXML(data)); + } + return false; + } + static parse(xmlTxt) { + return XMLFormat.parse(settings.ADAPTER.parseXML(xmlTxt)); + } + } + + const formats = [ + TextFormat, + XMLFormat, + XMLStringFormat + ]; + function autoDetectFormat(data) { + for (let i = 0; i < formats.length; i++) { + if (formats[i].test(data)) { + return formats[i]; + } + } + return null; + } + + function generateFillStyle(canvas, context, style, resolution, lines, metrics) { + const fillStyle = style.fill; + if (!Array.isArray(fillStyle)) { + return fillStyle; + } else if (fillStyle.length === 1) { + return fillStyle[0]; + } + let gradient; + const dropShadowCorrection = style.dropShadow ? style.dropShadowDistance : 0; + const padding = style.padding || 0; + const width = canvas.width / resolution - dropShadowCorrection - padding * 2; + const height = canvas.height / resolution - dropShadowCorrection - padding * 2; + const fill = fillStyle.slice(); + const fillGradientStops = style.fillGradientStops.slice(); + if (!fillGradientStops.length) { + const lengthPlus1 = fill.length + 1; + for (let i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + fill.unshift(fillStyle[0]); + fillGradientStops.unshift(0); + fill.push(fillStyle[fillStyle.length - 1]); + fillGradientStops.push(1); + if (style.fillGradientType === TEXT_GRADIENT.LINEAR_VERTICAL) { + gradient = context.createLinearGradient(width / 2, padding, width / 2, height + padding); + let lastIterationStop = 0; + const textHeight = metrics.fontProperties.fontSize + style.strokeThickness; + const gradStopLineHeight = textHeight / height; + for (let i = 0; i < lines.length; i++) { + const thisLineTop = metrics.lineHeight * i; + for (let j = 0; j < fill.length; j++) { + let lineStop = 0; + if (typeof fillGradientStops[j] === "number") { + lineStop = fillGradientStops[j]; + } else { + lineStop = j / fill.length; + } + const globalStop = thisLineTop / height + lineStop * gradStopLineHeight; + let clampedStop = Math.max(lastIterationStop, globalStop); + clampedStop = Math.min(clampedStop, 1); + gradient.addColorStop(clampedStop, fill[j]); + lastIterationStop = clampedStop; + } + } + } else { + gradient = context.createLinearGradient(padding, height / 2, width + padding, height / 2); + const totalIterations = fill.length + 1; + let currentIteration = 1; + for (let i = 0; i < fill.length; i++) { + let stop; + if (typeof fillGradientStops[i] === "number") { + stop = fillGradientStops[i]; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[i]); + currentIteration++; + } + } + return gradient; + } + + function drawGlyph(canvas, context, metrics, x, y, resolution, style) { + const char = metrics.text; + const fontProperties = metrics.fontProperties; + context.translate(x, y); + context.scale(resolution, resolution); + const tx = style.strokeThickness / 2; + const ty = -(style.strokeThickness / 2); + context.font = style.toFontString(); + context.lineWidth = style.strokeThickness; + context.textBaseline = style.textBaseline; + context.lineJoin = style.lineJoin; + context.miterLimit = style.miterLimit; + context.fillStyle = generateFillStyle(canvas, context, style, resolution, [char], metrics); + context.strokeStyle = style.stroke; + if (style.dropShadow) { + const dropShadowColor = style.dropShadowColor; + const dropShadowBlur = style.dropShadowBlur * resolution; + const dropShadowDistance = style.dropShadowDistance * resolution; + context.shadowColor = Color.shared.setValue(dropShadowColor).setAlpha(style.dropShadowAlpha).toRgbaString(); + context.shadowBlur = dropShadowBlur; + context.shadowOffsetX = Math.cos(style.dropShadowAngle) * dropShadowDistance; + context.shadowOffsetY = Math.sin(style.dropShadowAngle) * dropShadowDistance; + } else { + context.shadowColor = "black"; + context.shadowBlur = 0; + context.shadowOffsetX = 0; + context.shadowOffsetY = 0; + } + if (style.stroke && style.strokeThickness) { + context.strokeText(char, tx, ty + metrics.lineHeight - fontProperties.descent); + } + if (style.fill) { + context.fillText(char, tx, ty + metrics.lineHeight - fontProperties.descent); + } + context.setTransform(1, 0, 0, 1, 0, 0); + context.fillStyle = "rgba(0, 0, 0, 0)"; + } + + function extractCharCode(str) { + return str.codePointAt ? str.codePointAt(0) : str.charCodeAt(0); + } + + function splitTextToCharacters(text) { + return Array.from ? Array.from(text) : text.split(""); + } + + function resolveCharacters(chars) { + if (typeof chars === "string") { + chars = [chars]; + } + const result = []; + for (let i = 0, j = chars.length; i < j; i++) { + const item = chars[i]; + if (Array.isArray(item)) { + if (item.length !== 2) { + throw new Error(`[BitmapFont]: Invalid character range length, expecting 2 got ${item.length}.`); + } + const startCode = item[0].charCodeAt(0); + const endCode = item[1].charCodeAt(0); + if (endCode < startCode) { + throw new Error("[BitmapFont]: Invalid character range."); + } + for (let i2 = startCode, j2 = endCode; i2 <= j2; i2++) { + result.push(String.fromCharCode(i2)); + } + } else { + result.push(...splitTextToCharacters(item)); + } + } + if (result.length === 0) { + throw new Error("[BitmapFont]: Empty set when resolving characters."); + } + return result; + } + + const _BitmapFont = class { + constructor(data, textures, ownsTextures) { + const [info] = data.info; + const [common] = data.common; + const [page] = data.page; + const [distanceField] = data.distanceField; + const res = getResolutionOfUrl(page.file); + const pageTextures = {}; + this._ownsTextures = ownsTextures; + this.font = info.face; + this.size = info.size; + this.lineHeight = common.lineHeight / res; + this.chars = {}; + this.pageTextures = pageTextures; + for (let i = 0; i < data.page.length; i++) { + const { id, file } = data.page[i]; + pageTextures[id] = textures instanceof Array ? textures[i] : textures[file]; + if (distanceField?.fieldType && distanceField.fieldType !== "none") { + pageTextures[id].baseTexture.alphaMode = ALPHA_MODES.NO_PREMULTIPLIED_ALPHA; + pageTextures[id].baseTexture.mipmap = MIPMAP_MODES.OFF; + } + } + for (let i = 0; i < data.char.length; i++) { + const { id, page: page2 } = data.char[i]; + let { x, y, width, height, xoffset, yoffset, xadvance } = data.char[i]; + x /= res; + y /= res; + width /= res; + height /= res; + xoffset /= res; + yoffset /= res; + xadvance /= res; + const rect = new Rectangle(x + pageTextures[page2].frame.x / res, y + pageTextures[page2].frame.y / res, width, height); + this.chars[id] = { + xOffset: xoffset, + yOffset: yoffset, + xAdvance: xadvance, + kerning: {}, + texture: new Texture(pageTextures[page2].baseTexture, rect), + page: page2 + }; + } + for (let i = 0; i < data.kerning.length; i++) { + let { first, second, amount } = data.kerning[i]; + first /= res; + second /= res; + amount /= res; + if (this.chars[second]) { + this.chars[second].kerning[first] = amount; + } + } + this.distanceFieldRange = distanceField?.distanceRange; + this.distanceFieldType = distanceField?.fieldType?.toLowerCase() ?? "none"; + } + destroy() { + for (const id in this.chars) { + this.chars[id].texture.destroy(); + this.chars[id].texture = null; + } + for (const id in this.pageTextures) { + if (this._ownsTextures) { + this.pageTextures[id].destroy(true); + } + this.pageTextures[id] = null; + } + this.chars = null; + this.pageTextures = null; + } + static install(data, textures, ownsTextures) { + let fontData; + if (data instanceof BitmapFontData) { + fontData = data; + } else { + const format = autoDetectFormat(data); + if (!format) { + throw new Error("Unrecognized data format for font."); + } + fontData = format.parse(data); + } + if (textures instanceof Texture) { + textures = [textures]; + } + const font = new _BitmapFont(fontData, textures, ownsTextures); + _BitmapFont.available[font.font] = font; + return font; + } + static uninstall(name) { + const font = _BitmapFont.available[name]; + if (!font) { + throw new Error(`No font found named '${name}'`); + } + font.destroy(); + delete _BitmapFont.available[name]; + } + static from(name, textStyle, options) { + if (!name) { + throw new Error("[BitmapFont] Property `name` is required."); + } + const { + chars, + padding, + resolution, + textureWidth, + textureHeight, + ...baseOptions + } = Object.assign({}, _BitmapFont.defaultOptions, options); + const charsList = resolveCharacters(chars); + const style = textStyle instanceof TextStyle ? textStyle : new TextStyle(textStyle); + const lineWidth = textureWidth; + const fontData = new BitmapFontData(); + fontData.info[0] = { + face: style.fontFamily, + size: style.fontSize + }; + fontData.common[0] = { + lineHeight: style.fontSize + }; + let positionX = 0; + let positionY = 0; + let canvas; + let context; + let baseTexture; + let maxCharHeight = 0; + const baseTextures = []; + const textures = []; + for (let i = 0; i < charsList.length; i++) { + if (!canvas) { + canvas = settings.ADAPTER.createCanvas(); + canvas.width = textureWidth; + canvas.height = textureHeight; + context = canvas.getContext("2d"); + baseTexture = new BaseTexture(canvas, { resolution, ...baseOptions }); + baseTextures.push(baseTexture); + textures.push(new Texture(baseTexture)); + fontData.page.push({ + id: textures.length - 1, + file: "" + }); + } + const character = charsList[i]; + const metrics = TextMetrics.measureText(character, style, false, canvas); + const width = metrics.width; + const height = Math.ceil(metrics.height); + const textureGlyphWidth = Math.ceil((style.fontStyle === "italic" ? 2 : 1) * width); + if (positionY >= textureHeight - height * resolution) { + if (positionY === 0) { + throw new Error(`[BitmapFont] textureHeight ${textureHeight}px is too small (fontFamily: '${style.fontFamily}', fontSize: ${style.fontSize}px, char: '${character}')`); + } + --i; + canvas = null; + context = null; + baseTexture = null; + positionY = 0; + positionX = 0; + maxCharHeight = 0; + continue; + } + maxCharHeight = Math.max(height + metrics.fontProperties.descent, maxCharHeight); + if (textureGlyphWidth * resolution + positionX >= lineWidth) { + if (positionX === 0) { + throw new Error(`[BitmapFont] textureWidth ${textureWidth}px is too small (fontFamily: '${style.fontFamily}', fontSize: ${style.fontSize}px, char: '${character}')`); + } + --i; + positionY += maxCharHeight * resolution; + positionY = Math.ceil(positionY); + positionX = 0; + maxCharHeight = 0; + continue; + } + drawGlyph(canvas, context, metrics, positionX, positionY, resolution, style); + const id = extractCharCode(metrics.text); + fontData.char.push({ + id, + page: textures.length - 1, + x: positionX / resolution, + y: positionY / resolution, + width: textureGlyphWidth, + height, + xoffset: 0, + yoffset: 0, + xadvance: width - (style.dropShadow ? style.dropShadowDistance : 0) - (style.stroke ? style.strokeThickness : 0) + }); + positionX += (textureGlyphWidth + 2 * padding) * resolution; + positionX = Math.ceil(positionX); + } + for (let i = 0, len = charsList.length; i < len; i++) { + const first = charsList[i]; + for (let j = 0; j < len; j++) { + const second = charsList[j]; + const c1 = context.measureText(first).width; + const c2 = context.measureText(second).width; + const total = context.measureText(first + second).width; + const amount = total - (c1 + c2); + if (amount) { + fontData.kerning.push({ + first: extractCharCode(first), + second: extractCharCode(second), + amount + }); + } + } + } + const font = new _BitmapFont(fontData, textures, true); + if (_BitmapFont.available[name] !== void 0) { + _BitmapFont.uninstall(name); + } + _BitmapFont.available[name] = font; + return font; + } + }; + let BitmapFont = _BitmapFont; + BitmapFont.ALPHA = [["a", "z"], ["A", "Z"], " "]; + BitmapFont.NUMERIC = [["0", "9"]]; + BitmapFont.ALPHANUMERIC = [["a", "z"], ["A", "Z"], ["0", "9"], " "]; + BitmapFont.ASCII = [[" ", "~"]]; + BitmapFont.defaultOptions = { + resolution: 1, + textureWidth: 512, + textureHeight: 512, + padding: 4, + chars: _BitmapFont.ALPHANUMERIC + }; + BitmapFont.available = {}; + + var msdfFrag = "// Pixi texture info\r\nvarying vec2 vTextureCoord;\r\nuniform sampler2D uSampler;\r\n\r\n// Tint\r\nuniform vec4 uColor;\r\n\r\n// on 2D applications fwidth is screenScale / glyphAtlasScale * distanceFieldRange\r\nuniform float uFWidth;\r\n\r\nvoid main(void) {\r\n\r\n // To stack MSDF and SDF we need a non-pre-multiplied-alpha texture.\r\n vec4 texColor = texture2D(uSampler, vTextureCoord);\r\n\r\n // MSDF\r\n float median = texColor.r + texColor.g + texColor.b -\r\n min(texColor.r, min(texColor.g, texColor.b)) -\r\n max(texColor.r, max(texColor.g, texColor.b));\r\n // SDF\r\n median = min(median, texColor.a);\r\n\r\n float screenPxDistance = uFWidth * (median - 0.5);\r\n float alpha = clamp(screenPxDistance + 0.5, 0.0, 1.0);\r\n if (median < 0.01) {\r\n alpha = 0.0;\r\n } else if (median > 0.99) {\r\n alpha = 1.0;\r\n }\r\n\r\n // Gamma correction for coverage-like alpha\r\n float luma = dot(uColor.rgb, vec3(0.299, 0.587, 0.114));\r\n float gamma = mix(1.0, 1.0 / 2.2, luma);\r\n float coverage = pow(uColor.a * alpha, gamma); \r\n\r\n // NPM Textures, NPM outputs\r\n gl_FragColor = vec4(uColor.rgb, coverage);\r\n}\r\n"; + + var msdfVert = "// Mesh material default fragment\r\nattribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\nuniform mat3 translationMatrix;\r\nuniform mat3 uTextureMatrix;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\r\n}\r\n"; + + const pageMeshDataDefaultPageMeshData = []; + const pageMeshDataMSDFPageMeshData = []; + const charRenderDataPool = []; + const _BitmapText = class extends Container { + constructor(text, style = {}) { + super(); + const { align, tint, maxWidth, letterSpacing, fontName, fontSize } = Object.assign({}, _BitmapText.styleDefaults, style); + if (!BitmapFont.available[fontName]) { + throw new Error(`Missing BitmapFont "${fontName}"`); + } + this._activePagesMeshData = []; + this._textWidth = 0; + this._textHeight = 0; + this._align = align; + this._tintColor = new Color(tint); + this._font = void 0; + this._fontName = fontName; + this._fontSize = fontSize; + this.text = text; + this._maxWidth = maxWidth; + this._maxLineHeight = 0; + this._letterSpacing = letterSpacing; + this._anchor = new ObservablePoint(() => { + this.dirty = true; + }, this, 0, 0); + this._roundPixels = settings.ROUND_PIXELS; + this.dirty = true; + this._resolution = settings.RESOLUTION; + this._autoResolution = true; + this._textureCache = {}; + } + updateText() { + const data = BitmapFont.available[this._fontName]; + const fontSize = this.fontSize; + const scale = fontSize / data.size; + const pos = new Point(); + const chars = []; + const lineWidths = []; + const lineSpaces = []; + const text = this._text.replace(/(?:\r\n|\r)/g, "\n") || " "; + const charsInput = splitTextToCharacters(text); + const maxWidth = this._maxWidth * data.size / fontSize; + const pageMeshDataPool = data.distanceFieldType === "none" ? pageMeshDataDefaultPageMeshData : pageMeshDataMSDFPageMeshData; + let prevCharCode = null; + let lastLineWidth = 0; + let maxLineWidth = 0; + let line = 0; + let lastBreakPos = -1; + let lastBreakWidth = 0; + let spacesRemoved = 0; + let maxLineHeight = 0; + let spaceCount = 0; + for (let i = 0; i < charsInput.length; i++) { + const char = charsInput[i]; + const charCode = extractCharCode(char); + if (/(?:\s)/.test(char)) { + lastBreakPos = i; + lastBreakWidth = lastLineWidth; + spaceCount++; + } + if (char === "\r" || char === "\n") { + lineWidths.push(lastLineWidth); + lineSpaces.push(-1); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + ++line; + ++spacesRemoved; + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + spaceCount = 0; + continue; + } + const charData = data.chars[charCode]; + if (!charData) { + continue; + } + if (prevCharCode && charData.kerning[prevCharCode]) { + pos.x += charData.kerning[prevCharCode]; + } + const charRenderData = charRenderDataPool.pop() || { + texture: Texture.EMPTY, + line: 0, + charCode: 0, + prevSpaces: 0, + position: new Point() + }; + charRenderData.texture = charData.texture; + charRenderData.line = line; + charRenderData.charCode = charCode; + charRenderData.position.x = Math.round(pos.x + charData.xOffset + this._letterSpacing / 2); + charRenderData.position.y = Math.round(pos.y + charData.yOffset); + charRenderData.prevSpaces = spaceCount; + chars.push(charRenderData); + lastLineWidth = charRenderData.position.x + Math.max(charData.xAdvance - charData.xOffset, charData.texture.orig.width); + pos.x += charData.xAdvance + this._letterSpacing; + maxLineHeight = Math.max(maxLineHeight, charData.yOffset + charData.texture.height); + prevCharCode = charCode; + if (lastBreakPos !== -1 && maxWidth > 0 && pos.x > maxWidth) { + ++spacesRemoved; + removeItems(chars, 1 + lastBreakPos - spacesRemoved, 1 + i - lastBreakPos); + i = lastBreakPos; + lastBreakPos = -1; + lineWidths.push(lastBreakWidth); + lineSpaces.push(chars.length > 0 ? chars[chars.length - 1].prevSpaces : 0); + maxLineWidth = Math.max(maxLineWidth, lastBreakWidth); + line++; + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + spaceCount = 0; + } + } + const lastChar = charsInput[charsInput.length - 1]; + if (lastChar !== "\r" && lastChar !== "\n") { + if (/(?:\s)/.test(lastChar)) { + lastLineWidth = lastBreakWidth; + } + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + lineSpaces.push(-1); + } + const lineAlignOffsets = []; + for (let i = 0; i <= line; i++) { + let alignOffset = 0; + if (this._align === "right") { + alignOffset = maxLineWidth - lineWidths[i]; + } else if (this._align === "center") { + alignOffset = (maxLineWidth - lineWidths[i]) / 2; + } else if (this._align === "justify") { + alignOffset = lineSpaces[i] < 0 ? 0 : (maxLineWidth - lineWidths[i]) / lineSpaces[i]; + } + lineAlignOffsets.push(alignOffset); + } + const lenChars = chars.length; + const pagesMeshData = {}; + const newPagesMeshData = []; + const activePagesMeshData = this._activePagesMeshData; + pageMeshDataPool.push(...activePagesMeshData); + for (let i = 0; i < lenChars; i++) { + const texture = chars[i].texture; + const baseTextureUid = texture.baseTexture.uid; + if (!pagesMeshData[baseTextureUid]) { + let pageMeshData = pageMeshDataPool.pop(); + if (!pageMeshData) { + const geometry = new MeshGeometry(); + let material; + let meshBlendMode; + if (data.distanceFieldType === "none") { + material = new MeshMaterial(Texture.EMPTY); + meshBlendMode = BLEND_MODES.NORMAL; + } else { + material = new MeshMaterial(Texture.EMPTY, { program: Program.from(msdfVert, msdfFrag), uniforms: { uFWidth: 0 } }); + meshBlendMode = BLEND_MODES.NORMAL_NPM; + } + const mesh = new Mesh(geometry, material); + mesh.blendMode = meshBlendMode; + pageMeshData = { + index: 0, + indexCount: 0, + vertexCount: 0, + uvsCount: 0, + total: 0, + mesh, + vertices: null, + uvs: null, + indices: null + }; + } + pageMeshData.index = 0; + pageMeshData.indexCount = 0; + pageMeshData.vertexCount = 0; + pageMeshData.uvsCount = 0; + pageMeshData.total = 0; + const { _textureCache } = this; + _textureCache[baseTextureUid] = _textureCache[baseTextureUid] || new Texture(texture.baseTexture); + pageMeshData.mesh.texture = _textureCache[baseTextureUid]; + pageMeshData.mesh.tint = this._tintColor.value; + newPagesMeshData.push(pageMeshData); + pagesMeshData[baseTextureUid] = pageMeshData; + } + pagesMeshData[baseTextureUid].total++; + } + for (let i = 0; i < activePagesMeshData.length; i++) { + if (!newPagesMeshData.includes(activePagesMeshData[i])) { + this.removeChild(activePagesMeshData[i].mesh); + } + } + for (let i = 0; i < newPagesMeshData.length; i++) { + if (newPagesMeshData[i].mesh.parent !== this) { + this.addChild(newPagesMeshData[i].mesh); + } + } + this._activePagesMeshData = newPagesMeshData; + for (const i in pagesMeshData) { + const pageMeshData = pagesMeshData[i]; + const total = pageMeshData.total; + if (!(pageMeshData.indices?.length > 6 * total) || pageMeshData.vertices.length < Mesh.BATCHABLE_SIZE * 2) { + pageMeshData.vertices = new Float32Array(4 * 2 * total); + pageMeshData.uvs = new Float32Array(4 * 2 * total); + pageMeshData.indices = new Uint16Array(6 * total); + } else { + const total2 = pageMeshData.total; + const vertices = pageMeshData.vertices; + for (let i2 = total2 * 4 * 2; i2 < vertices.length; i2++) { + vertices[i2] = 0; + } + } + pageMeshData.mesh.size = 6 * total; + } + for (let i = 0; i < lenChars; i++) { + const char = chars[i]; + let offset = char.position.x + lineAlignOffsets[char.line] * (this._align === "justify" ? char.prevSpaces : 1); + if (this._roundPixels) { + offset = Math.round(offset); + } + const xPos = offset * scale; + const yPos = char.position.y * scale; + const texture = char.texture; + const pageMesh = pagesMeshData[texture.baseTexture.uid]; + const textureFrame = texture.frame; + const textureUvs = texture._uvs; + const index = pageMesh.index++; + pageMesh.indices[index * 6 + 0] = 0 + index * 4; + pageMesh.indices[index * 6 + 1] = 1 + index * 4; + pageMesh.indices[index * 6 + 2] = 2 + index * 4; + pageMesh.indices[index * 6 + 3] = 0 + index * 4; + pageMesh.indices[index * 6 + 4] = 2 + index * 4; + pageMesh.indices[index * 6 + 5] = 3 + index * 4; + pageMesh.vertices[index * 8 + 0] = xPos; + pageMesh.vertices[index * 8 + 1] = yPos; + pageMesh.vertices[index * 8 + 2] = xPos + textureFrame.width * scale; + pageMesh.vertices[index * 8 + 3] = yPos; + pageMesh.vertices[index * 8 + 4] = xPos + textureFrame.width * scale; + pageMesh.vertices[index * 8 + 5] = yPos + textureFrame.height * scale; + pageMesh.vertices[index * 8 + 6] = xPos; + pageMesh.vertices[index * 8 + 7] = yPos + textureFrame.height * scale; + pageMesh.uvs[index * 8 + 0] = textureUvs.x0; + pageMesh.uvs[index * 8 + 1] = textureUvs.y0; + pageMesh.uvs[index * 8 + 2] = textureUvs.x1; + pageMesh.uvs[index * 8 + 3] = textureUvs.y1; + pageMesh.uvs[index * 8 + 4] = textureUvs.x2; + pageMesh.uvs[index * 8 + 5] = textureUvs.y2; + pageMesh.uvs[index * 8 + 6] = textureUvs.x3; + pageMesh.uvs[index * 8 + 7] = textureUvs.y3; + } + this._textWidth = maxLineWidth * scale; + this._textHeight = (pos.y + data.lineHeight) * scale; + for (const i in pagesMeshData) { + const pageMeshData = pagesMeshData[i]; + if (this.anchor.x !== 0 || this.anchor.y !== 0) { + let vertexCount = 0; + const anchorOffsetX = this._textWidth * this.anchor.x; + const anchorOffsetY = this._textHeight * this.anchor.y; + for (let i2 = 0; i2 < pageMeshData.total; i2++) { + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + } + } + this._maxLineHeight = maxLineHeight * scale; + const vertexBuffer = pageMeshData.mesh.geometry.getBuffer("aVertexPosition"); + const textureBuffer = pageMeshData.mesh.geometry.getBuffer("aTextureCoord"); + const indexBuffer = pageMeshData.mesh.geometry.getIndex(); + vertexBuffer.data = pageMeshData.vertices; + textureBuffer.data = pageMeshData.uvs; + indexBuffer.data = pageMeshData.indices; + vertexBuffer.update(); + textureBuffer.update(); + indexBuffer.update(); + } + for (let i = 0; i < chars.length; i++) { + charRenderDataPool.push(chars[i]); + } + this._font = data; + this.dirty = false; + } + updateTransform() { + this.validate(); + this.containerUpdateTransform(); + } + _render(renderer) { + if (this._autoResolution && this._resolution !== renderer.resolution) { + this._resolution = renderer.resolution; + this.dirty = true; + } + const { distanceFieldRange, distanceFieldType, size } = BitmapFont.available[this._fontName]; + if (distanceFieldType !== "none") { + const { a, b, c, d } = this.worldTransform; + const dx = Math.sqrt(a * a + b * b); + const dy = Math.sqrt(c * c + d * d); + const worldScale = (Math.abs(dx) + Math.abs(dy)) / 2; + const fontScale = this.fontSize / size; + const resolution = renderer._view.resolution; + for (const mesh of this._activePagesMeshData) { + mesh.mesh.shader.uniforms.uFWidth = worldScale * distanceFieldRange * fontScale * resolution; + } + } + super._render(renderer); + } + getLocalBounds() { + this.validate(); + return super.getLocalBounds(); + } + validate() { + const font = BitmapFont.available[this._fontName]; + if (!font) { + throw new Error(`Missing BitmapFont "${this._fontName}"`); + } + if (this._font !== font) { + this.dirty = true; + } + if (this.dirty) { + this.updateText(); + } + } + get tint() { + return this._tintColor.value; + } + set tint(value) { + if (this.tint === value) + return; + this._tintColor.setValue(value); + for (let i = 0; i < this._activePagesMeshData.length; i++) { + this._activePagesMeshData[i].mesh.tint = value; + } + } + get align() { + return this._align; + } + set align(value) { + if (this._align !== value) { + this._align = value; + this.dirty = true; + } + } + get fontName() { + return this._fontName; + } + set fontName(value) { + if (!BitmapFont.available[value]) { + throw new Error(`Missing BitmapFont "${value}"`); + } + if (this._fontName !== value) { + this._fontName = value; + this.dirty = true; + } + } + get fontSize() { + return this._fontSize ?? BitmapFont.available[this._fontName].size; + } + set fontSize(value) { + if (this._fontSize !== value) { + this._fontSize = value; + this.dirty = true; + } + } + get anchor() { + return this._anchor; + } + set anchor(value) { + if (typeof value === "number") { + this._anchor.set(value); + } else { + this._anchor.copyFrom(value); + } + } + get text() { + return this._text; + } + set text(text) { + text = String(text === null || text === void 0 ? "" : text); + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + } + get maxWidth() { + return this._maxWidth; + } + set maxWidth(value) { + if (this._maxWidth === value) { + return; + } + this._maxWidth = value; + this.dirty = true; + } + get maxLineHeight() { + this.validate(); + return this._maxLineHeight; + } + get textWidth() { + this.validate(); + return this._textWidth; + } + get letterSpacing() { + return this._letterSpacing; + } + set letterSpacing(value) { + if (this._letterSpacing !== value) { + this._letterSpacing = value; + this.dirty = true; + } + } + get roundPixels() { + return this._roundPixels; + } + set roundPixels(value) { + if (value !== this._roundPixels) { + this._roundPixels = value; + this.dirty = true; + } + } + get textHeight() { + this.validate(); + return this._textHeight; + } + get resolution() { + return this._resolution; + } + set resolution(value) { + this._autoResolution = false; + if (this._resolution === value) { + return; + } + this._resolution = value; + this.dirty = true; + } + destroy(options) { + const { _textureCache } = this; + const data = BitmapFont.available[this._fontName]; + const pageMeshDataPool = data.distanceFieldType === "none" ? pageMeshDataDefaultPageMeshData : pageMeshDataMSDFPageMeshData; + pageMeshDataPool.push(...this._activePagesMeshData); + for (const pageMeshData of this._activePagesMeshData) { + this.removeChild(pageMeshData.mesh); + } + this._activePagesMeshData = []; + pageMeshDataPool.filter((page) => _textureCache[page.mesh.texture.baseTexture.uid]).forEach((page) => { + page.mesh.texture = Texture.EMPTY; + }); + for (const id in _textureCache) { + const texture = _textureCache[id]; + texture.destroy(); + delete _textureCache[id]; + } + this._font = null; + this._tintColor = null; + this._textureCache = null; + super.destroy(options); + } + }; + let BitmapText = _BitmapText; + BitmapText.styleDefaults = { + align: "left", + tint: 16777215, + maxWidth: 0, + letterSpacing: 0 + }; + + const validExtensions = [".xml", ".fnt"]; + const loadBitmapFont = { + extension: { + type: ExtensionType.LoadParser, + priority: LoaderParserPriority.Normal + }, + name: "loadBitmapFont", + test(url) { + return validExtensions.includes(path.extname(url).toLowerCase()); + }, + async testParse(data) { + return TextFormat.test(data) || XMLStringFormat.test(data); + }, + async parse(asset, data, loader) { + const fontData = TextFormat.test(asset) ? TextFormat.parse(asset) : XMLStringFormat.parse(asset); + const { src } = data; + const { page: pages } = fontData; + const textureUrls = []; + for (let i = 0; i < pages.length; ++i) { + const pageFile = pages[i].file; + let imagePath = path.join(path.dirname(src), pageFile); + imagePath = copySearchParams(imagePath, src); + textureUrls.push(imagePath); + } + const loadedTextures = await loader.load(textureUrls); + const textures = textureUrls.map((url) => loadedTextures[url]); + return BitmapFont.install(fontData, textures, true); + }, + async load(url, _options) { + const response = await settings.ADAPTER.fetch(url); + return response.text(); + }, + unload(bitmapFont) { + bitmapFont.destroy(); + } + }; + extensions$1.add(loadBitmapFont); + + const _HTMLTextStyle = class extends TextStyle { + constructor() { + super(...arguments); + this._fonts = []; + this._overrides = []; + this._stylesheet = ""; + this.fontsDirty = false; + } + static from(originalStyle) { + return new _HTMLTextStyle(Object.keys(_HTMLTextStyle.defaultOptions).reduce((obj, prop) => ({ ...obj, [prop]: originalStyle[prop] }), {})); + } + cleanFonts() { + if (this._fonts.length > 0) { + this._fonts.forEach((font) => { + URL.revokeObjectURL(font.src); + font.refs--; + if (font.refs === 0) { + if (font.fontFace) { + document.fonts.delete(font.fontFace); + } + delete _HTMLTextStyle.availableFonts[font.originalUrl]; + } + }); + this.fontFamily = "Arial"; + this._fonts.length = 0; + this.styleID++; + this.fontsDirty = true; + } + } + loadFont(url, options = {}) { + const { availableFonts } = _HTMLTextStyle; + if (availableFonts[url]) { + const font = availableFonts[url]; + this._fonts.push(font); + font.refs++; + this.styleID++; + this.fontsDirty = true; + return Promise.resolve(); + } + return settings.ADAPTER.fetch(url).then((response) => response.blob()).then(async (blob) => new Promise((resolve, reject) => { + const src = URL.createObjectURL(blob); + const reader = new FileReader(); + reader.onload = () => resolve([src, reader.result]); + reader.onerror = reject; + reader.readAsDataURL(blob); + })).then(async ([src, dataSrc]) => { + const font = Object.assign({ + family: path.basename(url, path.extname(url)), + weight: "normal", + style: "normal", + src, + dataSrc, + refs: 1, + originalUrl: url, + fontFace: null + }, options); + availableFonts[url] = font; + this._fonts.push(font); + this.styleID++; + const fontFace = new FontFace(font.family, `url(${font.src})`, { + weight: font.weight, + style: font.style + }); + font.fontFace = fontFace; + await fontFace.load(); + document.fonts.add(fontFace); + await document.fonts.ready; + this.styleID++; + this.fontsDirty = true; + }); + } + addOverride(...value) { + const toAdd = value.filter((v) => !this._overrides.includes(v)); + if (toAdd.length > 0) { + this._overrides.push(...toAdd); + this.styleID++; + } + } + removeOverride(...value) { + const toRemove = value.filter((v) => this._overrides.includes(v)); + if (toRemove.length > 0) { + this._overrides = this._overrides.filter((v) => !toRemove.includes(v)); + this.styleID++; + } + } + toCSS(scale) { + return [ + `transform: scale(${scale})`, + `transform-origin: top left`, + "display: inline-block", + `color: ${this.normalizeColor(this.fill)}`, + `font-size: ${this.fontSize}px`, + `font-family: ${this.fontFamily}`, + `font-weight: ${this.fontWeight}`, + `font-style: ${this.fontStyle}`, + `font-variant: ${this.fontVariant}`, + `letter-spacing: ${this.letterSpacing}px`, + `text-align: ${this.align}`, + `padding: ${this.padding}px`, + `white-space: ${this.whiteSpace}`, + ...this.lineHeight ? [`line-height: ${this.lineHeight}px`] : [], + ...this.wordWrap ? [ + `word-wrap: ${this.breakWords ? "break-all" : "break-word"}`, + `max-width: ${this.wordWrapWidth}px` + ] : [], + ...this.strokeThickness ? [ + `-webkit-text-stroke-width: ${this.strokeThickness}px`, + `-webkit-text-stroke-color: ${this.normalizeColor(this.stroke)}`, + `text-stroke-width: ${this.strokeThickness}px`, + `text-stroke-color: ${this.normalizeColor(this.stroke)}`, + "paint-order: stroke" + ] : [], + ...this.dropShadow ? [this.dropShadowToCSS()] : [], + ...this._overrides + ].join(";"); + } + toGlobalCSS() { + return this._fonts.reduce((result, font) => `${result} + @font-face { + font-family: "${font.family}"; + src: url('${font.dataSrc}'); + font-weight: ${font.weight}; + font-style: ${font.style}; + }`, this._stylesheet); + } + get stylesheet() { + return this._stylesheet; + } + set stylesheet(value) { + if (this._stylesheet !== value) { + this._stylesheet = value; + this.styleID++; + } + } + normalizeColor(color) { + if (Array.isArray(color)) { + color = rgb2hex(color); + } + if (typeof color === "number") { + return hex2string(color); + } + return color; + } + dropShadowToCSS() { + let color = this.normalizeColor(this.dropShadowColor); + const alpha = this.dropShadowAlpha; + const x = Math.round(Math.cos(this.dropShadowAngle) * this.dropShadowDistance); + const y = Math.round(Math.sin(this.dropShadowAngle) * this.dropShadowDistance); + if (color.startsWith("#") && alpha < 1) { + color += (alpha * 255 | 0).toString(16).padStart(2, "0"); + } + const position = `${x}px ${y}px`; + if (this.dropShadowBlur > 0) { + return `text-shadow: ${position} ${this.dropShadowBlur}px ${color}`; + } + return `text-shadow: ${position} ${color}`; + } + reset() { + Object.assign(this, _HTMLTextStyle.defaultOptions); + } + onBeforeDraw() { + const { fontsDirty: prevFontsDirty } = this; + this.fontsDirty = false; + if (this.isSafari && this._fonts.length > 0 && prevFontsDirty) { + return new Promise((resolve) => setTimeout(resolve, 100)); + } + return Promise.resolve(); + } + get isSafari() { + const { userAgent } = settings.ADAPTER.getNavigator(); + return /^((?!chrome|android).)*safari/i.test(userAgent); + } + set fillGradientStops(_value) { + console.warn("[HTMLTextStyle] fillGradientStops is not supported by HTMLText"); + } + get fillGradientStops() { + return super.fillGradientStops; + } + set fillGradientType(_value) { + console.warn("[HTMLTextStyle] fillGradientType is not supported by HTMLText"); + } + get fillGradientType() { + return super.fillGradientType; + } + set miterLimit(_value) { + console.warn("[HTMLTextStyle] miterLimit is not supported by HTMLText"); + } + get miterLimit() { + return super.miterLimit; + } + set trim(_value) { + console.warn("[HTMLTextStyle] trim is not supported by HTMLText"); + } + get trim() { + return super.trim; + } + set textBaseline(_value) { + console.warn("[HTMLTextStyle] textBaseline is not supported by HTMLText"); + } + get textBaseline() { + return super.textBaseline; + } + set leading(_value) { + console.warn("[HTMLTextStyle] leading is not supported by HTMLText"); + } + get leading() { + return super.leading; + } + set lineJoin(_value) { + console.warn("[HTMLTextStyle] lineJoin is not supported by HTMLText"); + } + get lineJoin() { + return super.lineJoin; + } + }; + let HTMLTextStyle = _HTMLTextStyle; + HTMLTextStyle.availableFonts = {}; + HTMLTextStyle.defaultOptions = { + align: "left", + breakWords: false, + dropShadow: false, + dropShadowAlpha: 1, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: "black", + dropShadowDistance: 5, + fill: "black", + fontFamily: "Arial", + fontSize: 26, + fontStyle: "normal", + fontVariant: "normal", + fontWeight: "normal", + letterSpacing: 0, + lineHeight: 0, + padding: 0, + stroke: "black", + strokeThickness: 0, + whiteSpace: "normal", + wordWrap: false, + wordWrapWidth: 100 + }; + + const _HTMLText = class extends Sprite { + constructor(text = "", style = {}) { + super(Texture.EMPTY); + this._text = null; + this._style = null; + this._autoResolution = true; + this._loading = false; + this.localStyleID = -1; + this.dirty = false; + this.ownsStyle = false; + const image = new Image(); + const texture = Texture.from(image, { + scaleMode: settings.SCALE_MODE, + resourceOptions: { + autoLoad: false + } + }); + texture.orig = new Rectangle(); + texture.trim = new Rectangle(); + this.texture = texture; + const nssvg = "http://www.w3.org/2000/svg"; + const nsxhtml = "http://www.w3.org/1999/xhtml"; + const svgRoot = document.createElementNS(nssvg, "svg"); + const foreignObject = document.createElementNS(nssvg, "foreignObject"); + const domElement = document.createElementNS(nsxhtml, "div"); + const styleElement = document.createElementNS(nsxhtml, "style"); + foreignObject.setAttribute("width", "10000"); + foreignObject.setAttribute("height", "10000"); + foreignObject.style.overflow = "hidden"; + svgRoot.appendChild(foreignObject); + this.maxWidth = _HTMLText.defaultMaxWidth; + this.maxHeight = _HTMLText.defaultMaxHeight; + this._domElement = domElement; + this._styleElement = styleElement; + this._svgRoot = svgRoot; + this._foreignObject = foreignObject; + this._foreignObject.appendChild(styleElement); + this._foreignObject.appendChild(domElement); + this._image = image; + this._loadImage = new Image(); + this._autoResolution = _HTMLText.defaultAutoResolution; + this._resolution = _HTMLText.defaultResolution ?? settings.RESOLUTION; + this.text = text; + this.style = style; + } + measureText(overrides) { + const { text, style, resolution } = Object.assign({ + text: this._text, + style: this._style, + resolution: this._resolution + }, overrides); + Object.assign(this._domElement, { + innerHTML: text, + style: style.toCSS(resolution) + }); + this._styleElement.textContent = style.toGlobalCSS(); + document.body.appendChild(this._svgRoot); + const contentBounds = this._domElement.getBoundingClientRect(); + this._svgRoot.remove(); + const contentWidth = Math.min(this.maxWidth, Math.ceil(contentBounds.width)); + const contentHeight = Math.min(this.maxHeight, Math.ceil(contentBounds.height)); + this._svgRoot.setAttribute("width", contentWidth.toString()); + this._svgRoot.setAttribute("height", contentHeight.toString()); + if (text !== this._text) { + this._domElement.innerHTML = this._text; + } + if (style !== this._style) { + Object.assign(this._domElement, { style: this._style?.toCSS(resolution) }); + this._styleElement.textContent = this._style?.toGlobalCSS(); + } + return { + width: contentWidth + style.padding * 2, + height: contentHeight + style.padding * 2 + }; + } + async updateText(respectDirty = true) { + const { style, _image: image, _loadImage: loadImage } = this; + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } + if (!this.dirty && respectDirty) { + return; + } + const { width, height } = this.measureText(); + image.width = loadImage.width = Math.ceil(Math.max(1, width)); + image.height = loadImage.height = Math.ceil(Math.max(1, height)); + if (!this._loading) { + this._loading = true; + await new Promise((resolve) => { + loadImage.onload = async () => { + await style.onBeforeDraw(); + this._loading = false; + image.src = loadImage.src; + loadImage.onload = null; + loadImage.src = ""; + this.updateTexture(); + resolve(); + }; + const svgURL = new XMLSerializer().serializeToString(this._svgRoot); + loadImage.src = `data:image/svg+xml;charset=utf8,${encodeURIComponent(svgURL)}`; + }); + } + } + get source() { + return this._image; + } + updateTexture() { + const { style, texture, _image: image, resolution } = this; + const { padding } = style; + const { baseTexture } = texture; + texture.trim.width = texture._frame.width = image.width / resolution; + texture.trim.height = texture._frame.height = image.height / resolution; + texture.trim.x = -padding; + texture.trim.y = -padding; + texture.orig.width = texture._frame.width - padding * 2; + texture.orig.height = texture._frame.height - padding * 2; + this._onTextureUpdate(); + baseTexture.setRealSize(image.width, image.height, resolution); + this.dirty = false; + } + _render(renderer) { + if (this._autoResolution && this._resolution !== renderer.resolution) { + this._resolution = renderer.resolution; + this.dirty = true; + } + this.updateText(true); + super._render(renderer); + } + _renderCanvas(renderer) { + if (this._autoResolution && this._resolution !== renderer.resolution) { + this._resolution = renderer.resolution; + this.dirty = true; + } + this.updateText(true); + super._renderCanvas(renderer); + } + getLocalBounds(rect) { + this.updateText(true); + return super.getLocalBounds(rect); + } + _calculateBounds() { + this.updateText(true); + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } + _onStyleChange() { + this.dirty = true; + } + destroy(options) { + if (typeof options === "boolean") { + options = { children: options }; + } + options = Object.assign({}, _HTMLText.defaultDestroyOptions, options); + super.destroy(options); + const forceClear = null; + if (this.ownsStyle) { + this._style?.cleanFonts(); + } + this._style = forceClear; + this._svgRoot?.remove(); + this._svgRoot = forceClear; + this._domElement?.remove(); + this._domElement = forceClear; + this._foreignObject?.remove(); + this._foreignObject = forceClear; + this._styleElement?.remove(); + this._styleElement = forceClear; + this._loadImage.src = ""; + this._loadImage.onload = null; + this._loadImage = forceClear; + this._image.src = ""; + this._image = forceClear; + } + get width() { + this.updateText(true); + return Math.abs(this.scale.x) * this._image.width / this.resolution; + } + set width(value) { + this.updateText(true); + const s = sign(this.scale.x) || 1; + this.scale.x = s * value / this._image.width / this.resolution; + this._width = value; + } + get height() { + this.updateText(true); + return Math.abs(this.scale.y) * this._image.height / this.resolution; + } + set height(value) { + this.updateText(true); + const s = sign(this.scale.y) || 1; + this.scale.y = s * value / this._image.height / this.resolution; + this._height = value; + } + get style() { + return this._style; + } + set style(style) { + if (this._style === style) { + return; + } + style = style || {}; + if (style instanceof HTMLTextStyle) { + this.ownsStyle = false; + this._style = style; + } else if (style instanceof TextStyle) { + console.warn("[HTMLText] Cloning TextStyle, if this is not what you want, use HTMLTextStyle"); + this.ownsStyle = true; + this._style = HTMLTextStyle.from(style); + } else { + this.ownsStyle = true; + this._style = new HTMLTextStyle(style); + } + this.localStyleID = -1; + this.dirty = true; + } + get text() { + return this._text; + } + set text(text) { + text = String(text === "" || text === null || text === void 0 ? " " : text); + text = this.sanitiseText(text); + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + } + get resolution() { + return this._resolution; + } + set resolution(value) { + this._autoResolution = false; + if (this._resolution === value) { + return; + } + this._resolution = value; + this.dirty = true; + } + sanitiseText(text) { + return text.replace(/

/gi, "
").replace(/
/gi, "
").replace(/ /gi, " "); + } + }; + let HTMLText = _HTMLText; + HTMLText.defaultDestroyOptions = { + texture: true, + children: false, + baseTexture: true + }; + HTMLText.defaultMaxWidth = 2024; + HTMLText.defaultMaxHeight = 2024; + HTMLText.defaultAutoResolution = true; + + const TEMP_RECT = new Rectangle(); + class CanvasExtract { + constructor(renderer) { + this.renderer = renderer; + } + async image(target, format, quality) { + const image = new Image(); + image.src = await this.base64(target, format, quality); + return image; + } + async base64(target, format, quality) { + const canvas = this.canvas(target); + if (canvas.toBlob !== void 0) { + return new Promise((resolve, reject) => { + canvas.toBlob((blob) => { + if (!blob) { + reject(new Error("ICanvas.toBlob failed!")); + return; + } + const reader = new FileReader(); + reader.onload = () => resolve(reader.result); + reader.onerror = reject; + reader.readAsDataURL(blob); + }, format, quality); + }); + } + if (canvas.toDataURL !== void 0) { + return canvas.toDataURL(format, quality); + } + if (canvas.convertToBlob !== void 0) { + const blob = await canvas.convertToBlob({ type: format, quality }); + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(reader.result); + reader.onerror = reject; + reader.readAsDataURL(blob); + }); + } + throw new Error("CanvasExtract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented"); + } + canvas(target, frame) { + const renderer = this.renderer; + if (!renderer) { + throw new Error("The CanvasExtract has already been destroyed"); + } + let context; + let resolution; + let renderTexture; + if (target) { + if (target instanceof RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target, { + resolution: renderer.resolution + }); + } + } + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = frame ?? renderTexture.frame; + } else { + context = renderer.canvasContext.rootContext; + resolution = renderer._view.resolution; + if (!frame) { + frame = TEMP_RECT; + frame.width = renderer.width / resolution; + frame.height = renderer.height / resolution; + } + } + const x = Math.round(frame.x * resolution); + const y = Math.round(frame.y * resolution); + const width = Math.round(frame.width * resolution); + const height = Math.round(frame.height * resolution); + const canvasBuffer = new CanvasRenderTarget(width, height, 1); + const canvasData = context.getImageData(x, y, width, height); + canvasBuffer.context.putImageData(canvasData, 0, 0); + return canvasBuffer.canvas; + } + pixels(target, frame) { + const renderer = this.renderer; + if (!renderer) { + throw new Error("The CanvasExtract has already been destroyed"); + } + let context; + let resolution; + let renderTexture; + if (target) { + if (target instanceof RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target, { + resolution: renderer.resolution + }); + } + } + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = frame ?? renderTexture.frame; + } else { + context = renderer.canvasContext.rootContext; + resolution = renderer.resolution; + if (!frame) { + frame = TEMP_RECT; + frame.width = renderer.width / resolution; + frame.height = renderer.height / resolution; + } + } + const x = Math.round(frame.x * resolution); + const y = Math.round(frame.y * resolution); + const width = Math.round(frame.width * resolution); + const height = Math.round(frame.height * resolution); + return context.getImageData(x, y, width, height).data; + } + destroy() { + this.renderer = null; + } + } + CanvasExtract.extension = { + name: "extract", + type: ExtensionType.CanvasRendererSystem + }; + extensions$1.add(CanvasExtract); + + let canvasRenderer; + const tempMatrix = new Matrix(); + Graphics.prototype.generateCanvasTexture = function generateCanvasTexture(scaleMode, resolution = 1) { + const bounds = this.getLocalBounds(); + const canvasBuffer = RenderTexture.create({ + width: bounds.width, + height: bounds.height, + scaleMode, + resolution + }); + if (!canvasRenderer) { + canvasRenderer = new CanvasRenderer(); + } + this.transform.updateLocalTransform(); + this.transform.localTransform.copyTo(tempMatrix); + tempMatrix.invert(); + tempMatrix.tx -= bounds.x; + tempMatrix.ty -= bounds.y; + canvasRenderer.render(this, { renderTexture: canvasBuffer, clear: true, transform: tempMatrix }); + const texture = Texture.from(canvasBuffer.baseTexture._canvasRenderTarget.canvas, { scaleMode }); + texture.baseTexture.setResolution(resolution); + return texture; + }; + Graphics.prototype.cachedGraphicsData = []; + Graphics.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.isMask === true) { + return; + } + this.finishPoly(); + renderer.plugins.graphics.render(this); + }; + + class PolygonUtils { + static offsetPolygon(points, offset) { + const offsetPoints = []; + const length = points.length; + offset = PolygonUtils.isPolygonClockwise(points) ? offset : -1 * offset; + for (let j = 0; j < length; j += 2) { + let i = j - 2; + if (i < 0) { + i += length; + } + const k = (j + 2) % length; + let v1x = points[j] - points[i]; + let v1y = points[j + 1] - points[i + 1]; + let len = Math.sqrt(v1x * v1x + v1y * v1y); + v1x /= len; + v1y /= len; + v1x *= offset; + v1y *= offset; + const norm1x = -v1y; + const norm1y = v1x; + const pij1 = [points[i] + norm1x, points[i + 1] + norm1y]; + const pij2 = [points[j] + norm1x, points[j + 1] + norm1y]; + let v2x = points[k] - points[j]; + let v2y = points[k + 1] - points[j + 1]; + len = Math.sqrt(v2x * v2x + v2y * v2y); + v2x /= len; + v2y /= len; + v2x *= offset; + v2y *= offset; + const norm2x = -v2y; + const norm2y = v2x; + const pjk1 = [points[j] + norm2x, points[j + 1] + norm2y]; + const pjk2 = [points[k] + norm2x, points[k + 1] + norm2y]; + const intersectPoint = PolygonUtils.findIntersection(pij1[0], pij1[1], pij2[0], pij2[1], pjk1[0], pjk1[1], pjk2[0], pjk2[1]); + if (intersectPoint) { + offsetPoints.push(...intersectPoint); + } + } + return offsetPoints; + } + static findIntersection(x1, y1, x2, y2, x3, y3, x4, y4) { + const denominator = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); + const numeratorA = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3); + const numeratorB = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3); + if (denominator === 0) { + if (numeratorA === 0 && numeratorB === 0) { + return [(x1 + x2) / 2, (y1 + y2) / 2]; + } + return null; + } + const uA = numeratorA / denominator; + return [x1 + uA * (x2 - x1), y1 + uA * (y2 - y1)]; + } + static isPolygonClockwise(polygon) { + let sum = 0; + for (let i = 0, j = polygon.length - 2; i < polygon.length; j = i, i += 2) { + sum += (polygon[i] - polygon[j]) * (polygon[i + 1] + polygon[j + 1]); + } + return sum > 0; + } + } + + class CanvasGraphicsRenderer { + constructor(renderer) { + this._svgMatrix = null; + this._tempMatrix = new Matrix(); + this.renderer = renderer; + } + _calcCanvasStyle(style, tint) { + let res; + if (style.texture && style.texture.baseTexture !== Texture.WHITE.baseTexture) { + if (style.texture.valid) { + res = canvasUtils.getTintedPattern(style.texture, tint); + this.setPatternTransform(res, style.matrix || Matrix.IDENTITY); + } else { + res = "#808080"; + } + } else { + res = `#${`00000${(tint | 0).toString(16)}`.slice(-6)}`; + } + return res; + } + render(graphics) { + const renderer = this.renderer; + const context = renderer.canvasContext.activeContext; + const worldAlpha = graphics.worldAlpha; + const transform = graphics.transform.worldTransform; + renderer.canvasContext.setContextTransform(transform); + renderer.canvasContext.setBlendMode(graphics.blendMode); + const graphicsData = graphics.geometry.graphicsData; + let contextFillStyle; + let contextStrokeStyle; + const tint = Color.shared.setValue(graphics.tint).toArray(); + for (let i = 0; i < graphicsData.length; i++) { + const data = graphicsData[i]; + const shape = data.shape; + const fillStyle = data.fillStyle; + const lineStyle = data.lineStyle; + const fillColor = data.fillStyle.color | 0; + const lineColor = data.lineStyle.color | 0; + if (data.matrix) { + renderer.canvasContext.setContextTransform(transform.copyTo(this._tempMatrix).append(data.matrix)); + } + if (fillStyle.visible) { + contextFillStyle = this._calcCanvasStyle(fillStyle, Color.shared.setValue(fillColor).multiply(tint).toNumber()); + } + if (lineStyle.visible) { + contextStrokeStyle = this._calcCanvasStyle(lineStyle, Color.shared.setValue(lineColor).multiply(tint).toNumber()); + } + context.lineWidth = lineStyle.width; + context.lineCap = lineStyle.cap; + context.lineJoin = lineStyle.join; + context.miterLimit = lineStyle.miterLimit; + if (data.type === SHAPES.POLY) { + context.beginPath(); + const tempShape = shape; + let points = tempShape.points; + const holes = data.holes; + let outerArea; + let innerArea; + let px; + let py; + let holesDirection; + context.moveTo(points[0], points[1]); + for (let j = 2; j < points.length; j += 2) { + context.lineTo(points[j], points[j + 1]); + } + if (tempShape.closeStroke) { + context.closePath(); + } + if (holes.length > 0) { + holesDirection = []; + outerArea = 0; + px = points[0]; + py = points[1]; + for (let j = 2; j + 2 < points.length; j += 2) { + outerArea += (points[j] - px) * (points[j + 3] - py) - (points[j + 2] - px) * (points[j + 1] - py); + } + for (let k = 0; k < holes.length; k++) { + points = holes[k].shape.points; + if (!points) { + continue; + } + innerArea = 0; + px = points[0]; + py = points[1]; + for (let j = 2; j + 2 < points.length; j += 2) { + innerArea += (points[j] - px) * (points[j + 3] - py) - (points[j + 2] - px) * (points[j + 1] - py); + } + if (innerArea * outerArea < 0) { + context.moveTo(points[0], points[1]); + for (let j = 2; j < points.length; j += 2) { + context.lineTo(points[j], points[j + 1]); + } + } else { + context.moveTo(points[points.length - 2], points[points.length - 1]); + for (let j = points.length - 4; j >= 0; j -= 2) { + context.lineTo(points[j], points[j + 1]); + } + } + if (holes[k].shape.closeStroke) { + context.closePath(); + } + holesDirection[k] = innerArea * outerArea < 0; + } + } + if (fillStyle.visible) { + context.globalAlpha = fillStyle.alpha * worldAlpha; + context.fillStyle = contextFillStyle; + context.fill(); + } + if (lineStyle.visible) { + this.paintPolygonStroke(tempShape, lineStyle, contextStrokeStyle, holes, holesDirection, worldAlpha, context); + } + } else if (data.type === SHAPES.RECT) { + const tempShape = shape; + if (fillStyle.visible) { + context.globalAlpha = fillStyle.alpha * worldAlpha; + context.fillStyle = contextFillStyle; + context.fillRect(tempShape.x, tempShape.y, tempShape.width, tempShape.height); + } + if (lineStyle.visible) { + const alignmentOffset = lineStyle.width * (0.5 - (1 - lineStyle.alignment)); + const width = tempShape.width + 2 * alignmentOffset; + const height = tempShape.height + 2 * alignmentOffset; + context.globalAlpha = lineStyle.alpha * worldAlpha; + context.strokeStyle = contextStrokeStyle; + context.strokeRect(tempShape.x - alignmentOffset, tempShape.y - alignmentOffset, width, height); + } + } else if (data.type === SHAPES.CIRC) { + const tempShape = shape; + context.beginPath(); + context.arc(tempShape.x, tempShape.y, tempShape.radius, 0, 2 * Math.PI); + context.closePath(); + if (fillStyle.visible) { + context.globalAlpha = fillStyle.alpha * worldAlpha; + context.fillStyle = contextFillStyle; + context.fill(); + } + if (lineStyle.visible) { + if (lineStyle.alignment !== 0.5) { + const alignmentOffset = lineStyle.width * (0.5 - (1 - lineStyle.alignment)); + context.beginPath(); + context.arc(tempShape.x, tempShape.y, tempShape.radius + alignmentOffset, 0, 2 * Math.PI); + context.closePath(); + } + context.globalAlpha = lineStyle.alpha * worldAlpha; + context.strokeStyle = contextStrokeStyle; + context.stroke(); + } + } else if (data.type === SHAPES.ELIP) { + const tempShape = shape; + const drawShapeOverStroke = lineStyle.alignment === 1; + if (!drawShapeOverStroke) { + this.paintEllipse(tempShape, fillStyle, lineStyle, contextFillStyle, worldAlpha, context); + } + if (lineStyle.visible) { + if (lineStyle.alignment !== 0.5) { + const kappa = 0.5522848; + const alignmentOffset = lineStyle.width * (0.5 - (1 - lineStyle.alignment)); + const sW = (tempShape.width + alignmentOffset) * 2; + const sH = (tempShape.height + alignmentOffset) * 2; + const sX = tempShape.x - sW / 2; + const sY = tempShape.y - sH / 2; + const sOx = sW / 2 * kappa; + const sOy = sH / 2 * kappa; + const sXe = sX + sW; + const sYe = sY + sH; + const sXm = sX + sW / 2; + const sYm = sY + sH / 2; + context.beginPath(); + context.moveTo(sX, sYm); + context.bezierCurveTo(sX, sYm - sOy, sXm - sOx, sY, sXm, sY); + context.bezierCurveTo(sXm + sOx, sY, sXe, sYm - sOy, sXe, sYm); + context.bezierCurveTo(sXe, sYm + sOy, sXm + sOx, sYe, sXm, sYe); + context.bezierCurveTo(sXm - sOx, sYe, sX, sYm + sOy, sX, sYm); + context.closePath(); + } + context.globalAlpha = lineStyle.alpha * worldAlpha; + context.strokeStyle = contextStrokeStyle; + context.stroke(); + } + if (drawShapeOverStroke) { + this.paintEllipse(tempShape, fillStyle, lineStyle, contextFillStyle, worldAlpha, context); + } + } else if (data.type === SHAPES.RREC) { + const tempShape = shape; + const drawShapeOverStroke = lineStyle.alignment === 1; + if (!drawShapeOverStroke) { + this.paintRoundedRectangle(tempShape, fillStyle, lineStyle, contextFillStyle, worldAlpha, context); + } + if (lineStyle.visible) { + if (lineStyle.alignment !== 0.5) { + const width = tempShape.width; + const height = tempShape.height; + const alignmentOffset = lineStyle.width * (0.5 - (1 - lineStyle.alignment)); + const sRx = tempShape.x - alignmentOffset; + const sRy = tempShape.y - alignmentOffset; + const sWidth = tempShape.width + 2 * alignmentOffset; + const sHeight = tempShape.height + 2 * alignmentOffset; + const radiusOffset = alignmentOffset * (lineStyle.alignment >= 1 ? Math.min(sWidth / width, sHeight / height) : Math.min(width / sWidth, height / sHeight)); + let sRadius = tempShape.radius + radiusOffset; + const sMaxRadius = Math.min(sWidth, sHeight) / 2; + sRadius = sRadius > sMaxRadius ? sMaxRadius : sRadius; + context.beginPath(); + context.moveTo(sRx, sRy + sRadius); + context.lineTo(sRx, sRy + sHeight - sRadius); + context.quadraticCurveTo(sRx, sRy + sHeight, sRx + sRadius, sRy + sHeight); + context.lineTo(sRx + sWidth - sRadius, sRy + sHeight); + context.quadraticCurveTo(sRx + sWidth, sRy + sHeight, sRx + sWidth, sRy + sHeight - sRadius); + context.lineTo(sRx + sWidth, sRy + sRadius); + context.quadraticCurveTo(sRx + sWidth, sRy, sRx + sWidth - sRadius, sRy); + context.lineTo(sRx + sRadius, sRy); + context.quadraticCurveTo(sRx, sRy, sRx, sRy + sRadius); + context.closePath(); + } + context.globalAlpha = lineStyle.alpha * worldAlpha; + context.strokeStyle = contextStrokeStyle; + context.stroke(); + } + if (drawShapeOverStroke) { + this.paintRoundedRectangle(tempShape, fillStyle, lineStyle, contextFillStyle, worldAlpha, context); + } + } + } + } + paintPolygonStroke(shape, lineStyle, contextStrokeStyle, holes, holesDirection, worldAlpha, context) { + if (lineStyle.alignment !== 0.5) { + const alignmentOffset = lineStyle.width * (0.5 - (1 - lineStyle.alignment)); + let offsetPoints = PolygonUtils.offsetPolygon(shape.points, alignmentOffset); + let points; + context.beginPath(); + context.moveTo(offsetPoints[0], offsetPoints[1]); + for (let j = 2; j < offsetPoints.length; j += 2) { + context.lineTo(offsetPoints[j], offsetPoints[j + 1]); + } + if (shape.closeStroke) { + context.closePath(); + } + for (let k = 0; k < holes.length; k++) { + points = holes[k].shape.points; + offsetPoints = PolygonUtils.offsetPolygon(points, alignmentOffset); + if (holesDirection[k]) { + context.moveTo(offsetPoints[0], offsetPoints[1]); + for (let j = 2; j < offsetPoints.length; j += 2) { + context.lineTo(offsetPoints[j], offsetPoints[j + 1]); + } + } else { + context.moveTo(offsetPoints[offsetPoints.length - 2], offsetPoints[offsetPoints.length - 1]); + for (let j = offsetPoints.length - 4; j >= 0; j -= 2) { + context.lineTo(offsetPoints[j], offsetPoints[j + 1]); + } + } + if (holes[k].shape.closeStroke) { + context.closePath(); + } + } + } + context.globalAlpha = lineStyle.alpha * worldAlpha; + context.strokeStyle = contextStrokeStyle; + context.stroke(); + } + paintEllipse(shape, fillStyle, lineStyle, contextFillStyle, worldAlpha, context) { + const w = shape.width * 2; + const h = shape.height * 2; + const x = shape.x - w / 2; + const y = shape.y - h / 2; + const kappa = 0.5522848; + const ox = w / 2 * kappa; + const oy = h / 2 * kappa; + const xe = x + w; + const ye = y + h; + const xm = x + w / 2; + const ym = y + h / 2; + if (lineStyle.alignment === 0) { + context.save(); + } + context.beginPath(); + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + if (lineStyle.alignment === 0) { + context.clip(); + } + if (fillStyle.visible) { + context.globalAlpha = fillStyle.alpha * worldAlpha; + context.fillStyle = contextFillStyle; + context.fill(); + } + if (lineStyle.alignment === 0) { + context.restore(); + } + } + paintRoundedRectangle(shape, fillStyle, lineStyle, contextFillStyle, worldAlpha, context) { + const rx = shape.x; + const ry = shape.y; + const width = shape.width; + const height = shape.height; + let radius = shape.radius; + const maxRadius = Math.min(width, height) / 2; + radius = radius > maxRadius ? maxRadius : radius; + if (lineStyle.alignment === 0) { + context.save(); + } + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + if (lineStyle.alignment === 0) { + context.clip(); + } + if (fillStyle.visible) { + context.globalAlpha = fillStyle.alpha * worldAlpha; + context.fillStyle = contextFillStyle; + context.fill(); + } + if (lineStyle.alignment === 0) { + context.restore(); + } + } + setPatternTransform(pattern, matrix) { + if (this._svgMatrix === false) { + return; + } + if (!this._svgMatrix) { + const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + if (svg?.createSVGMatrix) { + this._svgMatrix = svg.createSVGMatrix(); + } + if (!this._svgMatrix || !pattern.setTransform) { + this._svgMatrix = false; + return; + } + } + this._svgMatrix.a = matrix.a; + this._svgMatrix.b = matrix.b; + this._svgMatrix.c = matrix.c; + this._svgMatrix.d = matrix.d; + this._svgMatrix.e = matrix.tx; + this._svgMatrix.f = matrix.ty; + pattern.setTransform(this._svgMatrix.inverse()); + } + destroy() { + this.renderer = null; + this._svgMatrix = null; + this._tempMatrix = null; + } + } + CanvasGraphicsRenderer.extension = { + name: "graphics", + type: ExtensionType.CanvasRendererPlugin + }; + extensions$1.add(CanvasGraphicsRenderer); + + Object.defineProperties(settings, { + MESH_CANVAS_PADDING: { + get() { + return Mesh.defaultCanvasPadding; + }, + set(value) { + deprecation$1("7.1.0", "settings.MESH_CANVAS_PADDING is deprecated, use Mesh.defaultCanvasPadding"); + Mesh.defaultCanvasPadding = value; + } + } + }); + + MeshMaterial.prototype._renderCanvas = function _renderCanvas(renderer, mesh) { + renderer.plugins.mesh.render(mesh); + }; + + NineSlicePlane.prototype._cachedTint = 16777215; + NineSlicePlane.prototype._tintedCanvas = null; + NineSlicePlane.prototype._canvasUvs = null; + NineSlicePlane.prototype._renderCanvas = function _renderCanvas(renderer) { + const context = renderer.canvasContext.activeContext; + const transform = this.worldTransform; + const isTinted = this.tintValue !== 16777215; + const texture = this.texture; + if (!texture.valid) { + return; + } + if (isTinted) { + if (this._cachedTint !== this.tintValue) { + this._cachedTint = this.tintValue; + this._tintedCanvas = canvasUtils.getTintedCanvas(this, this.tintValue); + } + } + const textureSource = !isTinted ? texture.baseTexture.getDrawableSource() : this._tintedCanvas; + if (!this._canvasUvs) { + this._canvasUvs = [0, 0, 0, 0, 0, 0, 0, 0]; + } + const vertices = this.vertices; + const uvs = this._canvasUvs; + const u0 = isTinted ? 0 : texture.frame.x; + const v0 = isTinted ? 0 : texture.frame.y; + const u1 = u0 + texture.frame.width; + const v1 = v0 + texture.frame.height; + uvs[0] = u0; + uvs[1] = u0 + this._leftWidth; + uvs[2] = u1 - this._rightWidth; + uvs[3] = u1; + uvs[4] = v0; + uvs[5] = v0 + this._topHeight; + uvs[6] = v1 - this._bottomHeight; + uvs[7] = v1; + for (let i = 0; i < 8; i++) { + uvs[i] *= texture.baseTexture.resolution; + } + context.globalAlpha = this.worldAlpha; + renderer.canvasContext.setBlendMode(this.blendMode); + renderer.canvasContext.setContextTransform(transform, this.roundPixels); + for (let row = 0; row < 3; row++) { + for (let col = 0; col < 3; col++) { + const ind = col * 2 + row * 8; + const sw = Math.max(1, uvs[col + 1] - uvs[col]); + const sh = Math.max(1, uvs[row + 5] - uvs[row + 4]); + const dw = Math.max(1, vertices[ind + 10] - vertices[ind]); + const dh = Math.max(1, vertices[ind + 11] - vertices[ind + 1]); + context.drawImage(textureSource, uvs[col], uvs[row + 4], sw, sh, vertices[ind], vertices[ind + 1], dw, dh); + } + } + }; + + let warned = false; + Mesh.prototype._cachedTint = 16777215; + Mesh.prototype._tintedCanvas = null; + Mesh.prototype._cachedTexture = null; + Mesh.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.shader.uvMatrix) { + this.shader.uvMatrix.update(); + this.calculateUvs(); + } + if (this.material._renderCanvas) { + this.material._renderCanvas(renderer, this); + } else if (!warned) { + warned = true; + globalThis.console.warn("Mesh with custom shaders are not supported in CanvasRenderer."); + } + }; + Mesh.prototype._canvasPadding = null; + Mesh.defaultCanvasPadding = 0; + Object.defineProperty(Mesh.prototype, "canvasPadding", { + get() { + return this._canvasPadding ?? Mesh.defaultCanvasPadding; + }, + set(value) { + this._canvasPadding = value; + } + }); + + SimpleMesh.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.autoUpdate) { + this.geometry.getBuffer("aVertexPosition").update(); + } + if (this.shader.update) { + this.shader.update(); + } + this.calculateUvs(); + this.material._renderCanvas(renderer, this); + }; + + SimpleRope.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.autoUpdate || this.geometry._width !== this.shader.texture.height) { + this.geometry._width = this.shader.texture.height; + this.geometry.update(); + } + if (this.shader.update) { + this.shader.update(); + } + this.calculateUvs(); + this.material._renderCanvas(renderer, this); + }; + + class CanvasMeshRenderer { + constructor(renderer) { + this.renderer = renderer; + } + render(mesh) { + const renderer = this.renderer; + const transform = mesh.worldTransform; + renderer.canvasContext.activeContext.globalAlpha = mesh.worldAlpha; + renderer.canvasContext.setBlendMode(mesh.blendMode); + renderer.canvasContext.setContextTransform(transform, mesh.roundPixels); + if (mesh.drawMode !== DRAW_MODES.TRIANGLES) { + this._renderTriangleMesh(mesh); + } else { + this._renderTriangles(mesh); + } + } + _renderTriangleMesh(mesh) { + const length = mesh.geometry.buffers[0].data.length; + for (let i = 0; i < length - 2; i++) { + const index = i * 2; + this._renderDrawTriangle(mesh, index, index + 2, index + 4); + } + } + _renderTriangles(mesh) { + const indices = mesh.geometry.getIndex().data; + const length = indices.length; + for (let i = 0; i < length; i += 3) { + const index0 = indices[i] * 2; + const index1 = indices[i + 1] * 2; + const index2 = indices[i + 2] * 2; + this._renderDrawTriangle(mesh, index0, index1, index2); + } + } + _renderDrawTriangle(mesh, index0, index1, index2) { + const context = this.renderer.canvasContext.activeContext; + const vertices = mesh.geometry.buffers[0].data; + const { uvs, texture } = mesh; + if (!texture.valid) { + return; + } + const isTinted = mesh.tintValue !== 16777215; + const base = texture.baseTexture; + const textureWidth = base.width; + const textureHeight = base.height; + if (mesh._cachedTexture && mesh._cachedTexture.baseTexture !== base) { + mesh._cachedTint = 16777215; + mesh._cachedTexture?.destroy(); + mesh._cachedTexture = null; + mesh._tintedCanvas = null; + } + if (isTinted) { + if (mesh._cachedTint !== mesh.tintValue) { + mesh._cachedTint = mesh.tintValue; + mesh._cachedTexture = mesh._cachedTexture || new Texture(base); + mesh._tintedCanvas = canvasUtils.getTintedCanvas({ texture: mesh._cachedTexture }, mesh.tintValue); + } + } + const textureSource = isTinted ? mesh._tintedCanvas : base.getDrawableSource(); + const u0 = uvs[index0] * base.width; + const u1 = uvs[index1] * base.width; + const u2 = uvs[index2] * base.width; + const v0 = uvs[index0 + 1] * base.height; + const v1 = uvs[index1 + 1] * base.height; + const v2 = uvs[index2 + 1] * base.height; + let x0 = vertices[index0]; + let x1 = vertices[index1]; + let x2 = vertices[index2]; + let y0 = vertices[index0 + 1]; + let y1 = vertices[index1 + 1]; + let y2 = vertices[index2 + 1]; + const screenPadding = mesh.canvasPadding / this.renderer.canvasContext.activeResolution; + if (screenPadding > 0) { + const { a, b, c, d } = mesh.worldTransform; + const centerX = (x0 + x1 + x2) / 3; + const centerY = (y0 + y1 + y2) / 3; + let normX = x0 - centerX; + let normY = y0 - centerY; + let screenX = a * normX + c * normY; + let screenY = b * normX + d * normY; + let screenDist = Math.sqrt(screenX * screenX + screenY * screenY); + let paddingFactor = 1 + screenPadding / screenDist; + x0 = centerX + normX * paddingFactor; + y0 = centerY + normY * paddingFactor; + normX = x1 - centerX; + normY = y1 - centerY; + screenX = a * normX + c * normY; + screenY = b * normX + d * normY; + screenDist = Math.sqrt(screenX * screenX + screenY * screenY); + paddingFactor = 1 + screenPadding / screenDist; + x1 = centerX + normX * paddingFactor; + y1 = centerY + normY * paddingFactor; + normX = x2 - centerX; + normY = y2 - centerY; + screenX = a * normX + c * normY; + screenY = b * normX + d * normY; + screenDist = Math.sqrt(screenX * screenX + screenY * screenY); + paddingFactor = 1 + screenPadding / screenDist; + x2 = centerX + normX * paddingFactor; + y2 = centerY + normY * paddingFactor; + } + context.save(); + context.beginPath(); + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + context.closePath(); + context.clip(); + const delta = u0 * v1 + v0 * u2 + u1 * v2 - v1 * u2 - v0 * u1 - u0 * v2; + const deltaA = x0 * v1 + v0 * x2 + x1 * v2 - v1 * x2 - v0 * x1 - x0 * v2; + const deltaB = u0 * x1 + x0 * u2 + u1 * x2 - x1 * u2 - x0 * u1 - u0 * x2; + const deltaC = u0 * v1 * x2 + v0 * x1 * u2 + x0 * u1 * v2 - x0 * v1 * u2 - v0 * u1 * x2 - u0 * x1 * v2; + const deltaD = y0 * v1 + v0 * y2 + y1 * v2 - v1 * y2 - v0 * y1 - y0 * v2; + const deltaE = u0 * y1 + y0 * u2 + u1 * y2 - y1 * u2 - y0 * u1 - u0 * y2; + const deltaF = u0 * v1 * y2 + v0 * y1 * u2 + y0 * u1 * v2 - y0 * v1 * u2 - v0 * u1 * y2 - u0 * y1 * v2; + context.transform(deltaA / delta, deltaD / delta, deltaB / delta, deltaE / delta, deltaC / delta, deltaF / delta); + context.drawImage(textureSource, 0, 0, textureWidth * base.resolution, textureHeight * base.resolution, 0, 0, textureWidth, textureHeight); + context.restore(); + this.renderer.canvasContext.invalidateBlendMode(); + } + renderMeshFlat(mesh) { + const context = this.renderer.canvasContext.activeContext; + const vertices = mesh.geometry.getBuffer("aVertexPosition").data; + const length = vertices.length / 2; + context.beginPath(); + for (let i = 1; i < length - 2; ++i) { + const index = i * 2; + const x0 = vertices[index]; + const y0 = vertices[index + 1]; + const x1 = vertices[index + 2]; + const y1 = vertices[index + 3]; + const x2 = vertices[index + 4]; + const y2 = vertices[index + 5]; + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + context.fillStyle = "#FF0000"; + context.fill(); + context.closePath(); + } + destroy() { + this.renderer = null; + } + } + CanvasMeshRenderer.extension = { + name: "mesh", + type: ExtensionType.CanvasRendererPlugin + }; + extensions$1.add(CanvasMeshRenderer); + + const CANVAS_START_SIZE = 16; + function uploadBaseTextures(prepare, item) { + const tempPrepare = prepare; + if (item instanceof BaseTexture) { + const image = item.source; + const imageWidth = image.width === 0 ? tempPrepare.canvas.width : Math.min(tempPrepare.canvas.width, image.width); + const imageHeight = image.height === 0 ? tempPrepare.canvas.height : Math.min(tempPrepare.canvas.height, image.height); + tempPrepare.ctx.drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, tempPrepare.canvas.width, tempPrepare.canvas.height); + return true; + } + return false; + } + class CanvasPrepare extends BasePrepare { + constructor(renderer) { + super(renderer); + this.uploadHookHelper = this; + this.canvas = settings.ADAPTER.createCanvas(CANVAS_START_SIZE, CANVAS_START_SIZE); + this.ctx = this.canvas.getContext("2d"); + this.registerUploadHook(uploadBaseTextures); + } + destroy() { + super.destroy(); + this.ctx = null; + this.canvas = null; + } + } + CanvasPrepare.extension = { + name: "prepare", + type: ExtensionType.CanvasRendererSystem + }; + extensions$1.add(CanvasPrepare); + + Sprite.prototype._tintedCanvas = null; + Sprite.prototype._renderCanvas = function _renderCanvas(renderer) { + renderer.plugins.sprite.render(this); + }; + + const canvasRenderWorldTransform = new Matrix(); + class CanvasSpriteRenderer { + constructor(renderer) { + this.renderer = renderer; + } + render(sprite) { + const texture = sprite._texture; + const renderer = this.renderer; + const context = renderer.canvasContext.activeContext; + const activeResolution = renderer.canvasContext.activeResolution; + if (!texture.valid) { + return; + } + const sourceWidth = texture._frame.width; + const sourceHeight = texture._frame.height; + let destWidth = texture._frame.width; + let destHeight = texture._frame.height; + if (texture.trim) { + destWidth = texture.trim.width; + destHeight = texture.trim.height; + } + let wt = sprite.transform.worldTransform; + let dx = 0; + let dy = 0; + const source = texture.baseTexture.getDrawableSource(); + if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.valid || !source) { + return; + } + renderer.canvasContext.setBlendMode(sprite.blendMode, true); + context.globalAlpha = sprite.worldAlpha; + const smoothingEnabled = texture.baseTexture.scaleMode === SCALE_MODES.LINEAR; + const smoothProperty = renderer.canvasContext.smoothProperty; + if (smoothProperty && context[smoothProperty] !== smoothingEnabled) { + context[smoothProperty] = smoothingEnabled; + } + if (texture.trim) { + dx = texture.trim.width / 2 + texture.trim.x - sprite.anchor.x * texture.orig.width; + dy = texture.trim.height / 2 + texture.trim.y - sprite.anchor.y * texture.orig.height; + } else { + dx = (0.5 - sprite.anchor.x) * texture.orig.width; + dy = (0.5 - sprite.anchor.y) * texture.orig.height; + } + if (texture.rotate) { + wt.copyTo(canvasRenderWorldTransform); + wt = canvasRenderWorldTransform; + groupD8.matrixAppendRotationInv(wt, texture.rotate, dx, dy); + dx = 0; + dy = 0; + } + dx -= destWidth / 2; + dy -= destHeight / 2; + renderer.canvasContext.setContextTransform(wt, sprite.roundPixels, 1); + if (sprite.roundPixels) { + dx = dx | 0; + dy = dy | 0; + } + const resolution = texture.baseTexture.resolution; + const outerBlend = renderer.canvasContext._outerBlend; + if (outerBlend) { + context.save(); + context.beginPath(); + context.rect(dx * activeResolution, dy * activeResolution, destWidth * activeResolution, destHeight * activeResolution); + context.clip(); + } + if (sprite.tint !== 16777215) { + if (sprite._cachedTint !== sprite.tintValue || sprite._tintedCanvas.tintId !== sprite._texture._updateID) { + sprite._cachedTint = sprite.tintValue; + sprite._tintedCanvas = canvasUtils.getTintedCanvas(sprite, sprite.tintValue); + } + context.drawImage(sprite._tintedCanvas, 0, 0, Math.floor(sourceWidth * resolution), Math.floor(sourceHeight * resolution), Math.floor(dx * activeResolution), Math.floor(dy * activeResolution), Math.floor(destWidth * activeResolution), Math.floor(destHeight * activeResolution)); + } else { + context.drawImage(source, texture._frame.x * resolution, texture._frame.y * resolution, Math.floor(sourceWidth * resolution), Math.floor(sourceHeight * resolution), Math.floor(dx * activeResolution), Math.floor(dy * activeResolution), Math.floor(destWidth * activeResolution), Math.floor(destHeight * activeResolution)); + } + if (outerBlend) { + context.restore(); + } + renderer.canvasContext.setBlendMode(BLEND_MODES.NORMAL); + } + destroy() { + this.renderer = null; + } + } + CanvasSpriteRenderer.extension = { + name: "sprite", + type: ExtensionType.CanvasRendererPlugin + }; + extensions$1.add(CanvasSpriteRenderer); + + exports.ALPHA_MODES = ALPHA_MODES; + exports.AbstractMultiResource = AbstractMultiResource; + exports.AccessibilityManager = AccessibilityManager; + exports.AlphaFilter = AlphaFilter; + exports.AnimatedSprite = AnimatedSprite; + exports.Application = Application; + exports.ArrayResource = ArrayResource; + exports.Assets = Assets; + exports.AssetsClass = AssetsClass; + exports.Attribute = Attribute; + exports.BLEND_MODES = BLEND_MODES; + exports.BUFFER_BITS = BUFFER_BITS; + exports.BUFFER_TYPE = BUFFER_TYPE; + exports.BackgroundSystem = BackgroundSystem; + exports.BaseImageResource = BaseImageResource; + exports.BasePrepare = BasePrepare; + exports.BaseRenderTexture = BaseRenderTexture; + exports.BaseTexture = BaseTexture; + exports.BatchDrawCall = BatchDrawCall; + exports.BatchGeometry = BatchGeometry; + exports.BatchRenderer = BatchRenderer; + exports.BatchShaderGenerator = BatchShaderGenerator; + exports.BatchSystem = BatchSystem; + exports.BatchTextureArray = BatchTextureArray; + exports.BitmapFont = BitmapFont; + exports.BitmapFontData = BitmapFontData; + exports.BitmapText = BitmapText; + exports.BlobResource = BlobResource; + exports.BlurFilter = BlurFilter; + exports.BlurFilterPass = BlurFilterPass; + exports.Bounds = Bounds; + exports.BrowserAdapter = BrowserAdapter; + exports.Buffer = Buffer; + exports.BufferResource = BufferResource; + exports.BufferSystem = BufferSystem; + exports.CLEAR_MODES = CLEAR_MODES; + exports.COLOR_MASK_BITS = COLOR_MASK_BITS; + exports.Cache = Cache; + exports.CanvasContextSystem = CanvasContextSystem; + exports.CanvasExtract = CanvasExtract; + exports.CanvasGraphicsRenderer = CanvasGraphicsRenderer; + exports.CanvasMaskSystem = CanvasMaskSystem; + exports.CanvasMeshRenderer = CanvasMeshRenderer; + exports.CanvasObjectRendererSystem = CanvasObjectRendererSystem; + exports.CanvasPrepare = CanvasPrepare; + exports.CanvasRenderer = CanvasRenderer; + exports.CanvasResource = CanvasResource; + exports.CanvasSpriteRenderer = CanvasSpriteRenderer; + exports.Circle = Circle; + exports.Color = Color; + exports.ColorMatrixFilter = ColorMatrixFilter; + exports.CompressedTextureResource = CompressedTextureResource; + exports.Container = Container; + exports.ContextSystem = ContextSystem; + exports.CountLimiter = CountLimiter; + exports.CubeResource = CubeResource; + exports.DEG_TO_RAD = DEG_TO_RAD; + exports.DRAW_MODES = DRAW_MODES; + exports.DisplacementFilter = DisplacementFilter; + exports.DisplayObject = DisplayObject; + exports.ENV = ENV; + exports.Ellipse = Ellipse; + exports.EventBoundary = EventBoundary; + exports.EventSystem = EventSystem; + exports.ExtensionType = ExtensionType; + exports.Extract = Extract; + exports.FORMATS = FORMATS; + exports.FORMATS_TO_COMPONENTS = FORMATS_TO_COMPONENTS; + exports.FXAAFilter = FXAAFilter; + exports.FederatedDisplayObject = FederatedDisplayObject; + exports.FederatedEvent = FederatedEvent; + exports.FederatedMouseEvent = FederatedMouseEvent; + exports.FederatedPointerEvent = FederatedPointerEvent; + exports.FederatedWheelEvent = FederatedWheelEvent; + exports.FillStyle = FillStyle; + exports.Filter = Filter; + exports.FilterState = FilterState; + exports.FilterSystem = FilterSystem; + exports.Framebuffer = Framebuffer; + exports.FramebufferSystem = FramebufferSystem; + exports.GC_MODES = GC_MODES; + exports.GLFramebuffer = GLFramebuffer; + exports.GLProgram = GLProgram; + exports.GLTexture = GLTexture; + exports.GRAPHICS_CURVES = GRAPHICS_CURVES; + exports.GenerateTextureSystem = GenerateTextureSystem; + exports.Geometry = Geometry; + exports.GeometrySystem = GeometrySystem; + exports.Graphics = Graphics; + exports.GraphicsData = GraphicsData; + exports.GraphicsGeometry = GraphicsGeometry; + exports.HTMLText = HTMLText; + exports.HTMLTextStyle = HTMLTextStyle; + exports.IGLUniformData = IGLUniformData; + exports.INSTALLED = INSTALLED; + exports.INTERNAL_FORMATS = INTERNAL_FORMATS; + exports.INTERNAL_FORMAT_TO_BYTES_PER_PIXEL = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL; + exports.ImageBitmapResource = ImageBitmapResource; + exports.ImageResource = ImageResource; + exports.LINE_CAP = LINE_CAP; + exports.LINE_JOIN = LINE_JOIN; + exports.LineStyle = LineStyle; + exports.LoaderParserPriority = LoaderParserPriority; + exports.MASK_TYPES = MASK_TYPES; + exports.MIPMAP_MODES = MIPMAP_MODES; + exports.MSAA_QUALITY = MSAA_QUALITY; + exports.MaskData = MaskData; + exports.MaskSystem = MaskSystem; + exports.Matrix = Matrix; + exports.Mesh = Mesh; + exports.MeshBatchUvs = MeshBatchUvs; + exports.MeshGeometry = MeshGeometry; + exports.MeshMaterial = MeshMaterial; + exports.MultisampleSystem = MultisampleSystem; + exports.NineSlicePlane = NineSlicePlane; + exports.NoiseFilter = NoiseFilter; + exports.ObjectRenderer = ObjectRenderer; + exports.ObjectRendererSystem = ObjectRendererSystem; + exports.ObservablePoint = ObservablePoint; + exports.PI_2 = PI_2; + exports.PRECISION = PRECISION; + exports.ParticleContainer = ParticleContainer; + exports.ParticleRenderer = ParticleRenderer; + exports.PlaneGeometry = PlaneGeometry; + exports.PluginSystem = PluginSystem; + exports.Point = Point; + exports.Polygon = Polygon; + exports.Prepare = Prepare; + exports.Program = Program; + exports.ProjectionSystem = ProjectionSystem; + exports.Quad = Quad; + exports.QuadUv = QuadUv; + exports.RAD_TO_DEG = RAD_TO_DEG; + exports.RENDERER_TYPE = RENDERER_TYPE; + exports.Rectangle = Rectangle; + exports.RenderTexture = RenderTexture; + exports.RenderTexturePool = RenderTexturePool; + exports.RenderTextureSystem = RenderTextureSystem; + exports.Renderer = Renderer; + exports.ResizePlugin = ResizePlugin; + exports.Resource = Resource; + exports.RopeGeometry = RopeGeometry; + exports.RoundedRectangle = RoundedRectangle; + exports.Runner = Runner; + exports.SAMPLER_TYPES = SAMPLER_TYPES; + exports.SCALE_MODES = SCALE_MODES; + exports.SHAPES = SHAPES; + exports.SVGResource = SVGResource; + exports.ScissorSystem = ScissorSystem; + exports.Shader = Shader; + exports.ShaderSystem = ShaderSystem; + exports.SimpleMesh = SimpleMesh; + exports.SimplePlane = SimplePlane; + exports.SimpleRope = SimpleRope; + exports.Sprite = Sprite; + exports.SpriteMaskFilter = SpriteMaskFilter; + exports.Spritesheet = Spritesheet; + exports.StartupSystem = StartupSystem; + exports.State = State; + exports.StateSystem = StateSystem; + exports.StencilSystem = StencilSystem; + exports.SystemManager = SystemManager; + exports.TARGETS = TARGETS; + exports.TEXT_GRADIENT = TEXT_GRADIENT; + exports.TYPES = TYPES; + exports.TYPES_TO_BYTES_PER_COMPONENT = TYPES_TO_BYTES_PER_COMPONENT; + exports.TYPES_TO_BYTES_PER_PIXEL = TYPES_TO_BYTES_PER_PIXEL; + exports.TemporaryDisplayObject = TemporaryDisplayObject; + exports.Text = Text; + exports.TextFormat = TextFormat; + exports.TextMetrics = TextMetrics; + exports.TextStyle = TextStyle; + exports.Texture = Texture; + exports.TextureGCSystem = TextureGCSystem; + exports.TextureMatrix = TextureMatrix; + exports.TextureSystem = TextureSystem; + exports.TextureUvs = TextureUvs; + exports.Ticker = Ticker; + exports.TickerPlugin = TickerPlugin; + exports.TilingSprite = TilingSprite; + exports.TilingSpriteRenderer = TilingSpriteRenderer; + exports.TimeLimiter = TimeLimiter; + exports.Transform = Transform; + exports.TransformFeedback = TransformFeedback; + exports.TransformFeedbackSystem = TransformFeedbackSystem; + exports.UPDATE_PRIORITY = UPDATE_PRIORITY; + exports.UniformGroup = UniformGroup; + exports.VERSION = VERSION; + exports.VideoResource = VideoResource; + exports.ViewSystem = ViewSystem; + exports.ViewableBuffer = ViewableBuffer; + exports.WRAP_MODES = WRAP_MODES; + exports.XMLFormat = XMLFormat; + exports.XMLStringFormat = XMLStringFormat; + exports.accessibleTarget = accessibleTarget; + exports.autoDetectFormat = autoDetectFormat; + exports.autoDetectRenderer = autoDetectRenderer; + exports.autoDetectResource = autoDetectResource; + exports.cacheTextureArray = cacheTextureArray; + exports.canUseNewCanvasBlendModes = canUseNewCanvasBlendModes; + exports.canvasUtils = canvasUtils; + exports.checkDataUrl = checkDataUrl; + exports.checkExtension = checkExtension; + exports.checkMaxIfStatementsInShader = checkMaxIfStatementsInShader; + exports.convertToList = convertToList; + exports.copySearchParams = copySearchParams; + exports.createStringVariations = createStringVariations; + exports.createTexture = createTexture; + exports.createUBOElements = createUBOElements; + exports.curves = curves; + exports.defaultFilterVertex = defaultFilterVertex; + exports.defaultVertex = defaultVertex; + exports.detectAvif = detectAvif; + exports.detectCompressedTextures = detectCompressedTextures; + exports.detectDefaults = detectDefaults; + exports.detectWebp = detectWebp; + exports.extensions = extensions$1; + exports.filters = filters; + exports.generateProgram = generateProgram; + exports.generateUniformBufferSync = generateUniformBufferSync; + exports.getFontFamilyName = getFontFamilyName; + exports.getTestContext = getTestContext; + exports.getUBOData = getUBOData; + exports.graphicsUtils = graphicsUtils; + exports.groupD8 = groupD8; + exports.isMobile = isMobile; + exports.isSingleItem = isSingleItem; + exports.loadBitmapFont = loadBitmapFont; + exports.loadDDS = loadDDS; + exports.loadImageBitmap = loadImageBitmap; + exports.loadJson = loadJson; + exports.loadKTX = loadKTX; + exports.loadSVG = loadSVG; + exports.loadTextures = loadTextures; + exports.loadTxt = loadTxt; + exports.loadWebFont = loadWebFont; + exports.parseDDS = parseDDS; + exports.parseKTX = parseKTX; + exports.resolveCompressedTextureUrl = resolveCompressedTextureUrl; + exports.resolveTextureUrl = resolveTextureUrl; + exports.settings = settings; + exports.spritesheetAsset = spritesheetAsset; + exports.uniformParsers = uniformParsers; + exports.unsafeEvalSupported = unsafeEvalSupported; + exports.utils = utils; + + Object.defineProperty(exports, '__esModule', { value: true }); + + return exports; + +})({}); +//# sourceMappingURL=pixi-legacy.js.map diff --git a/IDE/public/scope/js/pixi.js b/IDE/public/scope/js/pixi.js deleted file mode 100644 index 52fd42b73..000000000 --- a/IDE/public/scope/js/pixi.js +++ /dev/null @@ -1,38831 +0,0 @@ -/*! - * pixi.js - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * pixi.js is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ -var PIXI = (function (exports) { - 'use strict'; - - /** - * @this {Promise} - */ - function finallyConstructor(callback) { - var constructor = this.constructor; - return this.then( - function(value) { - // @ts-ignore - return constructor.resolve(callback()).then(function() { - return value; - }); - }, - function(reason) { - // @ts-ignore - return constructor.resolve(callback()).then(function() { - // @ts-ignore - return constructor.reject(reason); - }); - } - ); - } - - function allSettled(arr) { - var P = this; - return new P(function(resolve, reject) { - if (!(arr && typeof arr.length !== 'undefined')) { - return reject( - new TypeError( - typeof arr + - ' ' + - arr + - ' is not iterable(cannot read property Symbol(Symbol.iterator))' - ) - ); - } - var args = Array.prototype.slice.call(arr); - if (args.length === 0) { return resolve([]); } - var remaining = args.length; - - function res(i, val) { - if (val && (typeof val === 'object' || typeof val === 'function')) { - var then = val.then; - if (typeof then === 'function') { - then.call( - val, - function(val) { - res(i, val); - }, - function(e) { - args[i] = { status: 'rejected', reason: e }; - if (--remaining === 0) { - resolve(args); - } - } - ); - return; - } - } - args[i] = { status: 'fulfilled', value: val }; - if (--remaining === 0) { - resolve(args); - } - } - - for (var i = 0; i < args.length; i++) { - res(i, args[i]); - } - }); - } - - // Store setTimeout reference so promise-polyfill will be unaffected by - // other code modifying setTimeout (like sinon.useFakeTimers()) - var setTimeoutFunc = setTimeout; - - function isArray(x) { - return Boolean(x && typeof x.length !== 'undefined'); - } - - function noop() {} - - // Polyfill for Function.prototype.bind - function bind(fn, thisArg) { - return function() { - fn.apply(thisArg, arguments); - }; - } - - /** - * @constructor - * @param {Function} fn - */ - function Promise$1(fn) { - if (!(this instanceof Promise$1)) - { throw new TypeError('Promises must be constructed via new'); } - if (typeof fn !== 'function') { throw new TypeError('not a function'); } - /** @type {!number} */ - this._state = 0; - /** @type {!boolean} */ - this._handled = false; - /** @type {Promise|undefined} */ - this._value = undefined; - /** @type {!Array} */ - this._deferreds = []; - - doResolve(fn, this); - } - - function handle(self, deferred) { - while (self._state === 3) { - self = self._value; - } - if (self._state === 0) { - self._deferreds.push(deferred); - return; - } - self._handled = true; - Promise$1._immediateFn(function() { - var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected; - if (cb === null) { - (self._state === 1 ? resolve$1 : reject)(deferred.promise, self._value); - return; - } - var ret; - try { - ret = cb(self._value); - } catch (e) { - reject(deferred.promise, e); - return; - } - resolve$1(deferred.promise, ret); - }); - } - - function resolve$1(self, newValue) { - try { - // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure - if (newValue === self) - { throw new TypeError('A promise cannot be resolved with itself.'); } - if ( - newValue && - (typeof newValue === 'object' || typeof newValue === 'function') - ) { - var then = newValue.then; - if (newValue instanceof Promise$1) { - self._state = 3; - self._value = newValue; - finale(self); - return; - } else if (typeof then === 'function') { - doResolve(bind(then, newValue), self); - return; - } - } - self._state = 1; - self._value = newValue; - finale(self); - } catch (e) { - reject(self, e); - } - } - - function reject(self, newValue) { - self._state = 2; - self._value = newValue; - finale(self); - } - - function finale(self) { - if (self._state === 2 && self._deferreds.length === 0) { - Promise$1._immediateFn(function() { - if (!self._handled) { - Promise$1._unhandledRejectionFn(self._value); - } - }); - } - - for (var i = 0, len = self._deferreds.length; i < len; i++) { - handle(self, self._deferreds[i]); - } - self._deferreds = null; - } - - /** - * @constructor - */ - function Handler(onFulfilled, onRejected, promise) { - this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; - this.onRejected = typeof onRejected === 'function' ? onRejected : null; - this.promise = promise; - } - - /** - * Take a potentially misbehaving resolver function and make sure - * onFulfilled and onRejected are only called once. - * - * Makes no guarantees about asynchrony. - */ - function doResolve(fn, self) { - var done = false; - try { - fn( - function(value) { - if (done) { return; } - done = true; - resolve$1(self, value); - }, - function(reason) { - if (done) { return; } - done = true; - reject(self, reason); - } - ); - } catch (ex) { - if (done) { return; } - done = true; - reject(self, ex); - } - } - - Promise$1.prototype['catch'] = function(onRejected) { - return this.then(null, onRejected); - }; - - Promise$1.prototype.then = function(onFulfilled, onRejected) { - // @ts-ignore - var prom = new this.constructor(noop); - - handle(this, new Handler(onFulfilled, onRejected, prom)); - return prom; - }; - - Promise$1.prototype['finally'] = finallyConstructor; - - Promise$1.all = function(arr) { - return new Promise$1(function(resolve, reject) { - if (!isArray(arr)) { - return reject(new TypeError('Promise.all accepts an array')); - } - - var args = Array.prototype.slice.call(arr); - if (args.length === 0) { return resolve([]); } - var remaining = args.length; - - function res(i, val) { - try { - if (val && (typeof val === 'object' || typeof val === 'function')) { - var then = val.then; - if (typeof then === 'function') { - then.call( - val, - function(val) { - res(i, val); - }, - reject - ); - return; - } - } - args[i] = val; - if (--remaining === 0) { - resolve(args); - } - } catch (ex) { - reject(ex); - } - } - - for (var i = 0; i < args.length; i++) { - res(i, args[i]); - } - }); - }; - - Promise$1.allSettled = allSettled; - - Promise$1.resolve = function(value) { - if (value && typeof value === 'object' && value.constructor === Promise$1) { - return value; - } - - return new Promise$1(function(resolve) { - resolve(value); - }); - }; - - Promise$1.reject = function(value) { - return new Promise$1(function(resolve, reject) { - reject(value); - }); - }; - - Promise$1.race = function(arr) { - return new Promise$1(function(resolve, reject) { - if (!isArray(arr)) { - return reject(new TypeError('Promise.race accepts an array')); - } - - for (var i = 0, len = arr.length; i < len; i++) { - Promise$1.resolve(arr[i]).then(resolve, reject); - } - }); - }; - - // Use polyfill for setImmediate for performance gains - Promise$1._immediateFn = - // @ts-ignore - (typeof setImmediate === 'function' && - function(fn) { - // @ts-ignore - setImmediate(fn); - }) || - function(fn) { - setTimeoutFunc(fn, 0); - }; - - Promise$1._unhandledRejectionFn = function _unhandledRejectionFn(err) { - if (typeof console !== 'undefined' && console) { - console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console - } - }; - - /* - object-assign - (c) Sindre Sorhus - @license MIT - */ - - 'use strict'; - /* eslint-disable no-unused-vars */ - var getOwnPropertySymbols = Object.getOwnPropertySymbols; - var hasOwnProperty$1 = Object.prototype.hasOwnProperty; - var propIsEnumerable = Object.prototype.propertyIsEnumerable; - - function toObject(val) { - if (val === null || val === undefined) { - throw new TypeError('Object.assign cannot be called with null or undefined'); - } - - return Object(val); - } - - function shouldUseNative() { - try { - if (!Object.assign) { - return false; - } - - // Detect buggy property enumeration order in older V8 versions. - - // https://bugs.chromium.org/p/v8/issues/detail?id=4118 - var test1 = new String('abc'); // eslint-disable-line no-new-wrappers - test1[5] = 'de'; - if (Object.getOwnPropertyNames(test1)[0] === '5') { - return false; - } - - // https://bugs.chromium.org/p/v8/issues/detail?id=3056 - var test2 = {}; - for (var i = 0; i < 10; i++) { - test2['_' + String.fromCharCode(i)] = i; - } - var order2 = Object.getOwnPropertyNames(test2).map(function (n) { - return test2[n]; - }); - if (order2.join('') !== '0123456789') { - return false; - } - - // https://bugs.chromium.org/p/v8/issues/detail?id=3056 - var test3 = {}; - 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { - test3[letter] = letter; - }); - if (Object.keys(Object.assign({}, test3)).join('') !== - 'abcdefghijklmnopqrst') { - return false; - } - - return true; - } catch (err) { - // We don't expect any of the above to throw, but better to be safe. - return false; - } - } - - var objectAssign = shouldUseNative() ? Object.assign : function (target, source) { - var arguments$1 = arguments; - - var from; - var to = toObject(target); - var symbols; - - for (var s = 1; s < arguments.length; s++) { - from = Object(arguments$1[s]); - - for (var key in from) { - if (hasOwnProperty$1.call(from, key)) { - to[key] = from[key]; - } - } - - if (getOwnPropertySymbols) { - symbols = getOwnPropertySymbols(from); - for (var i = 0; i < symbols.length; i++) { - if (propIsEnumerable.call(from, symbols[i])) { - to[symbols[i]] = from[symbols[i]]; - } - } - } - } - - return to; - }; - - /*! - * @pixi/polyfill - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/polyfill is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - if (typeof globalThis === 'undefined') { - if (typeof self !== 'undefined') { - // covers browsers - // @ts-expect-error not-writable ts(2540) error only on node - self.globalThis = self; - } - else if (typeof global !== 'undefined') { - // covers versions of Node < 12 - // @ts-expect-error not-writable ts(2540) error only on node - global.globalThis = global; - } - } - - // Support for IE 9 - 11 which does not include Promises - if (!globalThis.Promise) { - globalThis.Promise = Promise$1; - } - - // References: - if (!Object.assign) { - Object.assign = objectAssign; - } - - // References: - // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ - // https://gist.github.com/1579671 - // http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision - // https://gist.github.com/timhall/4078614 - // https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame - // Expected to be used with Browserfiy - // Browserify automatically detects the use of `global` and passes the - // correct reference of `global`, `globalThis`, and finally `window` - var ONE_FRAME_TIME = 16; - // Date.now - if (!(Date.now && Date.prototype.getTime)) { - Date.now = function now() { - return new Date().getTime(); - }; - } - // performance.now - if (!(globalThis.performance && globalThis.performance.now)) { - var startTime_1 = Date.now(); - if (!globalThis.performance) { - globalThis.performance = {}; - } - globalThis.performance.now = function () { return Date.now() - startTime_1; }; - } - // requestAnimationFrame - var lastTime = Date.now(); - var vendors = ['ms', 'moz', 'webkit', 'o']; - for (var x = 0; x < vendors.length && !globalThis.requestAnimationFrame; ++x) { - var p = vendors[x]; - globalThis.requestAnimationFrame = globalThis[p + "RequestAnimationFrame"]; - globalThis.cancelAnimationFrame = globalThis[p + "CancelAnimationFrame"] - || globalThis[p + "CancelRequestAnimationFrame"]; - } - if (!globalThis.requestAnimationFrame) { - globalThis.requestAnimationFrame = function (callback) { - if (typeof callback !== 'function') { - throw new TypeError(callback + "is not a function"); - } - var currentTime = Date.now(); - var delay = ONE_FRAME_TIME + lastTime - currentTime; - if (delay < 0) { - delay = 0; - } - lastTime = currentTime; - return globalThis.self.setTimeout(function () { - lastTime = Date.now(); - callback(performance.now()); - }, delay); - }; - } - if (!globalThis.cancelAnimationFrame) { - globalThis.cancelAnimationFrame = function (id) { return clearTimeout(id); }; - } - - // References: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign - if (!Math.sign) { - Math.sign = function mathSign(x) { - x = Number(x); - if (x === 0 || isNaN(x)) { - return x; - } - return x > 0 ? 1 : -1; - }; - } - - // References: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger - if (!Number.isInteger) { - Number.isInteger = function numberIsInteger(value) { - return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; - }; - } - - if (!globalThis.ArrayBuffer) { - globalThis.ArrayBuffer = Array; - } - if (!globalThis.Float32Array) { - globalThis.Float32Array = Array; - } - if (!globalThis.Uint32Array) { - globalThis.Uint32Array = Array; - } - if (!globalThis.Uint16Array) { - globalThis.Uint16Array = Array; - } - if (!globalThis.Uint8Array) { - globalThis.Uint8Array = Array; - } - if (!globalThis.Int32Array) { - globalThis.Int32Array = Array; - } - - /*! - * @pixi/constants - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/constants is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - /** - * Different types of environments for WebGL. - * @static - * @memberof PIXI - * @name ENV - * @enum {number} - * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility - * with older / less advanced devices. If you experience unexplained flickering prefer this environment. - * @property {number} WEBGL - Version 1 of WebGL - * @property {number} WEBGL2 - Version 2 of WebGL - */ - exports.ENV = void 0; - (function (ENV) { - ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; - ENV[ENV["WEBGL"] = 1] = "WEBGL"; - ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; - })(exports.ENV || (exports.ENV = {})); - /** - * Constant to identify the Renderer Type. - * @static - * @memberof PIXI - * @name RENDERER_TYPE - * @enum {number} - * @property {number} UNKNOWN - Unknown render type. - * @property {number} WEBGL - WebGL render type. - * @property {number} CANVAS - Canvas render type. - */ - exports.RENDERER_TYPE = void 0; - (function (RENDERER_TYPE) { - RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; - RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; - RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; - })(exports.RENDERER_TYPE || (exports.RENDERER_TYPE = {})); - /** - * Bitwise OR of masks that indicate the buffers to be cleared. - * @static - * @memberof PIXI - * @name BUFFER_BITS - * @enum {number} - * @property {number} COLOR - Indicates the buffers currently enabled for color writing. - * @property {number} DEPTH - Indicates the depth buffer. - * @property {number} STENCIL - Indicates the stencil buffer. - */ - exports.BUFFER_BITS = void 0; - (function (BUFFER_BITS) { - BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; - BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; - BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; - })(exports.BUFFER_BITS || (exports.BUFFER_BITS = {})); - /** - * Various blend modes supported by PIXI. - * - * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. - * Anything else will silently act like NORMAL. - * @memberof PIXI - * @name BLEND_MODES - * @enum {number} - * @property {number} NORMAL - - * @property {number} ADD - - * @property {number} MULTIPLY - - * @property {number} SCREEN - - * @property {number} OVERLAY - - * @property {number} DARKEN - - * @property {number} LIGHTEN - - * @property {number} COLOR_DODGE - - * @property {number} COLOR_BURN - - * @property {number} HARD_LIGHT - - * @property {number} SOFT_LIGHT - - * @property {number} DIFFERENCE - - * @property {number} EXCLUSION - - * @property {number} HUE - - * @property {number} SATURATION - - * @property {number} COLOR - - * @property {number} LUMINOSITY - - * @property {number} NORMAL_NPM - - * @property {number} ADD_NPM - - * @property {number} SCREEN_NPM - - * @property {number} NONE - - * @property {number} SRC_IN - - * @property {number} SRC_OUT - - * @property {number} SRC_ATOP - - * @property {number} DST_OVER - - * @property {number} DST_IN - - * @property {number} DST_OUT - - * @property {number} DST_ATOP - - * @property {number} SUBTRACT - - * @property {number} SRC_OVER - - * @property {number} ERASE - - * @property {number} XOR - - */ - exports.BLEND_MODES = void 0; - (function (BLEND_MODES) { - BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; - BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; - BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; - BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; - BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; - BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; - BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; - BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; - BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; - BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; - BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; - BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; - BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; - BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; - BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; - BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; - BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; - BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; - BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; - BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; - BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; - BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; - BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; - BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; - BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; - BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; - BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; - BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; - BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; - BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; - BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; - BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; - })(exports.BLEND_MODES || (exports.BLEND_MODES = {})); - /** - * Various webgl draw modes. These can be used to specify which GL drawMode to use - * under certain situations and renderers. - * @memberof PIXI - * @static - * @name DRAW_MODES - * @enum {number} - * @property {number} POINTS - - * @property {number} LINES - - * @property {number} LINE_LOOP - - * @property {number} LINE_STRIP - - * @property {number} TRIANGLES - - * @property {number} TRIANGLE_STRIP - - * @property {number} TRIANGLE_FAN - - */ - exports.DRAW_MODES = void 0; - (function (DRAW_MODES) { - DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; - DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; - DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; - DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; - DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; - DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; - DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; - })(exports.DRAW_MODES || (exports.DRAW_MODES = {})); - /** - * Various GL texture/resources formats. - * @memberof PIXI - * @static - * @name FORMATS - * @enum {number} - * @property {number} [RGBA=6408] - - * @property {number} [RGB=6407] - - * @property {number} [RG=33319] - - * @property {number} [RED=6403] - - * @property {number} [RGBA_INTEGER=36249] - - * @property {number} [RGB_INTEGER=36248] - - * @property {number} [RG_INTEGER=33320] - - * @property {number} [RED_INTEGER=36244] - - * @property {number} [ALPHA=6406] - - * @property {number} [LUMINANCE=6409] - - * @property {number} [LUMINANCE_ALPHA=6410] - - * @property {number} [DEPTH_COMPONENT=6402] - - * @property {number} [DEPTH_STENCIL=34041] - - */ - exports.FORMATS = void 0; - (function (FORMATS) { - FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; - FORMATS[FORMATS["RGB"] = 6407] = "RGB"; - FORMATS[FORMATS["RG"] = 33319] = "RG"; - FORMATS[FORMATS["RED"] = 6403] = "RED"; - FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER"; - FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER"; - FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER"; - FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER"; - FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; - FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; - FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; - FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; - FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; - })(exports.FORMATS || (exports.FORMATS = {})); - /** - * Various GL target types. - * @memberof PIXI - * @static - * @name TARGETS - * @enum {number} - * @property {number} [TEXTURE_2D=3553] - - * @property {number} [TEXTURE_CUBE_MAP=34067] - - * @property {number} [TEXTURE_2D_ARRAY=35866] - - * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_X=34069] - - * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_X=34070] - - * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Y=34071] - - * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Y=34072] - - * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Z=34073] - - * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Z=34074] - - */ - exports.TARGETS = void 0; - (function (TARGETS) { - TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; - TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; - })(exports.TARGETS || (exports.TARGETS = {})); - /** - * Various GL data format types. - * @memberof PIXI - * @static - * @name TYPES - * @enum {number} - * @property {number} [UNSIGNED_BYTE=5121] - - * @property {number} [UNSIGNED_SHORT=5123] - - * @property {number} [UNSIGNED_SHORT_5_6_5=33635] - - * @property {number} [UNSIGNED_SHORT_4_4_4_4=32819] - - * @property {number} [UNSIGNED_SHORT_5_5_5_1=32820] - - * @property {number} [UNSIGNED_INT=5125] - - * @property {number} [UNSIGNED_INT_10F_11F_11F_REV=35899] - - * @property {number} [UNSIGNED_INT_2_10_10_10_REV=33640] - - * @property {number} [UNSIGNED_INT_24_8=34042] - - * @property {number} [UNSIGNED_INT_5_9_9_9_REV=35902] - - * @property {number} [BYTE=5120] - - * @property {number} [SHORT=5122] - - * @property {number} [INT=5124] - - * @property {number} [FLOAT=5126] - - * @property {number} [FLOAT_32_UNSIGNED_INT_24_8_REV=36269] - - * @property {number} [HALF_FLOAT=36193] - - */ - exports.TYPES = void 0; - (function (TYPES) { - TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; - TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; - TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; - TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; - TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; - TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; - TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV"; - TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV"; - TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8"; - TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV"; - TYPES[TYPES["BYTE"] = 5120] = "BYTE"; - TYPES[TYPES["SHORT"] = 5122] = "SHORT"; - TYPES[TYPES["INT"] = 5124] = "INT"; - TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; - TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV"; - TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; - })(exports.TYPES || (exports.TYPES = {})); - /** - * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively. - * WebGL1 works only with FLOAT. - * @memberof PIXI - * @static - * @name SAMPLER_TYPES - * @enum {number} - * @property {number} [FLOAT=0] - - * @property {number} [INT=1] - - * @property {number} [UINT=2] - - */ - exports.SAMPLER_TYPES = void 0; - (function (SAMPLER_TYPES) { - SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT"; - SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT"; - SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT"; - })(exports.SAMPLER_TYPES || (exports.SAMPLER_TYPES = {})); - /** - * The scale modes that are supported by pixi. - * - * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. - * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. - * @memberof PIXI - * @static - * @name SCALE_MODES - * @enum {number} - * @property {number} LINEAR Smooth scaling - * @property {number} NEAREST Pixelating scaling - */ - exports.SCALE_MODES = void 0; - (function (SCALE_MODES) { - SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; - SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; - })(exports.SCALE_MODES || (exports.SCALE_MODES = {})); - /** - * The wrap modes that are supported by pixi. - * - * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. - * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. - * If the texture is non power of two then clamp will be used regardless as WebGL can - * only use REPEAT if the texture is po2. - * - * This property only affects WebGL. - * @name WRAP_MODES - * @memberof PIXI - * @static - * @enum {number} - * @property {number} CLAMP - The textures uvs are clamped - * @property {number} REPEAT - The texture uvs tile and repeat - * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring - */ - exports.WRAP_MODES = void 0; - (function (WRAP_MODES) { - WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; - WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; - WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; - })(exports.WRAP_MODES || (exports.WRAP_MODES = {})); - /** - * Mipmap filtering modes that are supported by pixi. - * - * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering. - * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`, - * or its `POW2` and texture dimensions are powers of 2. - * Due to platform restriction, `ON` option will work like `POW2` for webgl-1. - * - * This property only affects WebGL. - * @name MIPMAP_MODES - * @memberof PIXI - * @static - * @enum {number} - * @property {number} OFF - No mipmaps - * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2 - * @property {number} ON - Always generate mipmaps - * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource - * that supports buffering each level-of-detail. - */ - exports.MIPMAP_MODES = void 0; - (function (MIPMAP_MODES) { - MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; - MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; - MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; - MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL"; - })(exports.MIPMAP_MODES || (exports.MIPMAP_MODES = {})); - /** - * How to treat textures with premultiplied alpha - * @name ALPHA_MODES - * @memberof PIXI - * @static - * @enum {number} - * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that. - * Option for compressed and data textures that are created from typed arrays. - * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload. - * Default option, used for all loaded images. - * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied - * Example: spine atlases with `_pma` suffix. - * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA. - * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD. - * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA. - */ - exports.ALPHA_MODES = void 0; - (function (ALPHA_MODES) { - ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; - ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; - ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; - ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; - ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; - ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; - ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA"; - })(exports.ALPHA_MODES || (exports.ALPHA_MODES = {})); - /** - * Configure whether filter textures are cleared after binding. - * - * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect - * this and skip clearing as an optimization. - * @name CLEAR_MODES - * @memberof PIXI - * @static - * @enum {number} - * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture. - * @property {number} CLEAR - Always clear the filter texture. - * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending. - * @property {number} NO - Alias for BLEND, same as `false` in earlier versions - * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions - * @property {number} AUTO - Alias for BLIT - */ - exports.CLEAR_MODES = void 0; - (function (CLEAR_MODES) { - CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; - CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; - CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; - CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; - CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; - CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; - })(exports.CLEAR_MODES || (exports.CLEAR_MODES = {})); - /** - * The gc modes that are supported by pixi. - * - * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO - * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not - * used for a specified period of time they will be removed from the GPU. They will of course - * be uploaded again when they are required. This is a silent behind the scenes process that - * should ensure that the GPU does not get filled up. - * - * Handy for mobile devices! - * This property only affects WebGL. - * @name GC_MODES - * @enum {number} - * @static - * @memberof PIXI - * @property {number} AUTO - Garbage collection will happen periodically automatically - * @property {number} MANUAL - Garbage collection will need to be called manually - */ - exports.GC_MODES = void 0; - (function (GC_MODES) { - GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; - GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; - })(exports.GC_MODES || (exports.GC_MODES = {})); - /** - * Constants that specify float precision in shaders. - * @name PRECISION - * @memberof PIXI - * @constant - * @static - * @enum {string} - * @property {string} [LOW='lowp'] - - * @property {string} [MEDIUM='mediump'] - - * @property {string} [HIGH='highp'] - - */ - exports.PRECISION = void 0; - (function (PRECISION) { - PRECISION["LOW"] = "lowp"; - PRECISION["MEDIUM"] = "mediump"; - PRECISION["HIGH"] = "highp"; - })(exports.PRECISION || (exports.PRECISION = {})); - /** - * Constants for mask implementations. - * We use `type` suffix because it leads to very different behaviours - * @name MASK_TYPES - * @memberof PIXI - * @static - * @enum {number} - * @property {number} NONE - Mask is ignored - * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap - * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil - * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture - * @property {number} COLOR - Color mask (RGBA) - */ - exports.MASK_TYPES = void 0; - (function (MASK_TYPES) { - MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; - MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; - MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; - MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; - MASK_TYPES[MASK_TYPES["COLOR"] = 4] = "COLOR"; - })(exports.MASK_TYPES || (exports.MASK_TYPES = {})); - /** - * Bitwise OR of masks that indicate the color channels that are rendered to. - * @static - * @memberof PIXI - * @name COLOR_MASK_BITS - * @enum {number} - * @property {number} RED - Red channel. - * @property {number} GREEN - Green channel - * @property {number} BLUE - Blue channel. - * @property {number} ALPHA - Alpha channel. - */ - exports.COLOR_MASK_BITS = void 0; - (function (COLOR_MASK_BITS) { - COLOR_MASK_BITS[COLOR_MASK_BITS["RED"] = 1] = "RED"; - COLOR_MASK_BITS[COLOR_MASK_BITS["GREEN"] = 2] = "GREEN"; - COLOR_MASK_BITS[COLOR_MASK_BITS["BLUE"] = 4] = "BLUE"; - COLOR_MASK_BITS[COLOR_MASK_BITS["ALPHA"] = 8] = "ALPHA"; - })(exports.COLOR_MASK_BITS || (exports.COLOR_MASK_BITS = {})); - /** - * Constants for multi-sampling antialiasing. - * @see PIXI.Framebuffer#multisample - * @name MSAA_QUALITY - * @memberof PIXI - * @static - * @enum {number} - * @property {number} NONE - No multisampling for this renderTexture - * @property {number} LOW - Try 2 samples - * @property {number} MEDIUM - Try 4 samples - * @property {number} HIGH - Try 8 samples - */ - exports.MSAA_QUALITY = void 0; - (function (MSAA_QUALITY) { - MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; - MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; - MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; - MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; - })(exports.MSAA_QUALITY || (exports.MSAA_QUALITY = {})); - /** - * Constants for various buffer types in Pixi - * @see PIXI.BUFFER_TYPE - * @name BUFFER_TYPE - * @memberof PIXI - * @static - * @enum {number} - * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer - * @property {number} ARRAY_BUFFER - buffer type for using attribute data - * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects - */ - exports.BUFFER_TYPE = void 0; - (function (BUFFER_TYPE) { - BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER"; - BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER"; - // NOT YET SUPPORTED - BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER"; - })(exports.BUFFER_TYPE || (exports.BUFFER_TYPE = {})); - - /*! - * @pixi/settings - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/settings is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - var BrowserAdapter = { - /** - * Creates a canvas element of the given size. - * This canvas is created using the browser's native canvas element. - * @param width - width of the canvas - * @param height - height of the canvas - */ - createCanvas: function (width, height) { - var canvas = document.createElement('canvas'); - canvas.width = width; - canvas.height = height; - return canvas; - }, - getWebGLRenderingContext: function () { return WebGLRenderingContext; }, - getNavigator: function () { return navigator; }, - getBaseUrl: function () { var _a; return ((_a = document.baseURI) !== null && _a !== void 0 ? _a : window.location.href); }, - fetch: function (url, options) { return fetch(url, options); }, - }; - - var appleIphone = /iPhone/i; - var appleIpod = /iPod/i; - var appleTablet = /iPad/i; - var appleUniversal = /\biOS-universal(?:.+)Mac\b/i; - var androidPhone = /\bAndroid(?:.+)Mobile\b/i; - var androidTablet = /Android/i; - var amazonPhone = /(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i; - var amazonTablet = /Silk/i; - var windowsPhone = /Windows Phone/i; - var windowsTablet = /\bWindows(?:.+)ARM\b/i; - var otherBlackBerry = /BlackBerry/i; - var otherBlackBerry10 = /BB10/i; - var otherOpera = /Opera Mini/i; - var otherChrome = /\b(CriOS|Chrome)(?:.+)Mobile/i; - var otherFirefox = /Mobile(?:.+)Firefox\b/i; - var isAppleTabletOnIos13 = function (navigator) { - return (typeof navigator !== 'undefined' && - navigator.platform === 'MacIntel' && - typeof navigator.maxTouchPoints === 'number' && - navigator.maxTouchPoints > 1 && - typeof MSStream === 'undefined'); - }; - function createMatch(userAgent) { - return function (regex) { return regex.test(userAgent); }; - } - function isMobile$1(param) { - var nav = { - userAgent: '', - platform: '', - maxTouchPoints: 0 - }; - if (!param && typeof navigator !== 'undefined') { - nav = { - userAgent: navigator.userAgent, - platform: navigator.platform, - maxTouchPoints: navigator.maxTouchPoints || 0 - }; - } - else if (typeof param === 'string') { - nav.userAgent = param; - } - else if (param && param.userAgent) { - nav = { - userAgent: param.userAgent, - platform: param.platform, - maxTouchPoints: param.maxTouchPoints || 0 - }; - } - var userAgent = nav.userAgent; - var tmp = userAgent.split('[FBAN'); - if (typeof tmp[1] !== 'undefined') { - userAgent = tmp[0]; - } - tmp = userAgent.split('Twitter'); - if (typeof tmp[1] !== 'undefined') { - userAgent = tmp[0]; - } - var match = createMatch(userAgent); - var result = { - apple: { - phone: match(appleIphone) && !match(windowsPhone), - ipod: match(appleIpod), - tablet: !match(appleIphone) && - (match(appleTablet) || isAppleTabletOnIos13(nav)) && - !match(windowsPhone), - universal: match(appleUniversal), - device: (match(appleIphone) || - match(appleIpod) || - match(appleTablet) || - match(appleUniversal) || - isAppleTabletOnIos13(nav)) && - !match(windowsPhone) - }, - amazon: { - phone: match(amazonPhone), - tablet: !match(amazonPhone) && match(amazonTablet), - device: match(amazonPhone) || match(amazonTablet) - }, - android: { - phone: (!match(windowsPhone) && match(amazonPhone)) || - (!match(windowsPhone) && match(androidPhone)), - tablet: !match(windowsPhone) && - !match(amazonPhone) && - !match(androidPhone) && - (match(amazonTablet) || match(androidTablet)), - device: (!match(windowsPhone) && - (match(amazonPhone) || - match(amazonTablet) || - match(androidPhone) || - match(androidTablet))) || - match(/\bokhttp\b/i) - }, - windows: { - phone: match(windowsPhone), - tablet: match(windowsTablet), - device: match(windowsPhone) || match(windowsTablet) - }, - other: { - blackberry: match(otherBlackBerry), - blackberry10: match(otherBlackBerry10), - opera: match(otherOpera), - firefox: match(otherFirefox), - chrome: match(otherChrome), - device: match(otherBlackBerry) || - match(otherBlackBerry10) || - match(otherOpera) || - match(otherFirefox) || - match(otherChrome) - }, - any: false, - phone: false, - tablet: false - }; - result.any = - result.apple.device || - result.android.device || - result.windows.device || - result.other.device; - result.phone = - result.apple.phone || result.android.phone || result.windows.phone; - result.tablet = - result.apple.tablet || result.android.tablet || result.windows.tablet; - return result; - } - - var isMobile = isMobile$1(globalThis.navigator); - - /** - * Uploading the same buffer multiple times in a single frame can cause performance issues. - * Apparent on iOS so only check for that at the moment - * This check may become more complex if this issue pops up elsewhere. - * @private - * @returns {boolean} `true` if the same buffer may be uploaded more than once. - */ - function canUploadSameBuffer() { - return !isMobile.apple.device; - } - - /** - * The maximum recommended texture units to use. - * In theory the bigger the better, and for desktop we'll use as many as we can. - * But some mobile devices slow down if there is to many branches in the shader. - * So in practice there seems to be a sweet spot size that varies depending on the device. - * - * In v4, all mobile devices were limited to 4 texture units because for this. - * In v5, we allow all texture units to be used on modern Apple or Android devices. - * @private - * @param {number} max - * @returns {number} The maximum recommended texture units to use. - */ - function maxRecommendedTextures(max) { - var allowMax = true; - if (isMobile.tablet || isMobile.phone) { - if (isMobile.apple.device) { - var match = (navigator.userAgent).match(/OS (\d+)_(\d+)?/); - if (match) { - var majorVersion = parseInt(match[1], 10); - // Limit texture units on devices below iOS 11, which will be older hardware - if (majorVersion < 11) { - allowMax = false; - } - } - } - if (isMobile.android.device) { - var match = (navigator.userAgent).match(/Android\s([0-9.]*)/); - if (match) { - var majorVersion = parseInt(match[1], 10); - // Limit texture units on devices below Android 7 (Nougat), which will be older hardware - if (majorVersion < 7) { - allowMax = false; - } - } - } - } - return allowMax ? max : 4; - } - - /** - * User's customizable globals for overriding the default PIXI settings, such - * as a renderer's default resolution, framerate, float precision, etc. - * @example - * // Use the native window resolution as the default resolution - * // will support high-density displays when rendering - * PIXI.settings.RESOLUTION = window.devicePixelRatio; - * - * // Disable interpolation when scaling, will make texture be pixelated - * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; - * @namespace PIXI.settings - */ - var settings = { - /** - * This adapter is used to call methods that are platform dependent. - * For example `document.createElement` only runs on the web but fails in node environments. - * This allows us to support more platforms by abstracting away specific implementations per platform. - * - * By default the adapter is set to work in the browser. However you can create your own - * by implementing the `IAdapter` interface. See `IAdapter` for more information. - * @name ADAPTER - * @memberof PIXI.settings - * @type {PIXI.IAdapter} - * @default PIXI.BrowserAdapter - */ - ADAPTER: BrowserAdapter, - /** - * If set to true WebGL will attempt make textures mimpaped by default. - * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. - * @static - * @name MIPMAP_TEXTURES - * @memberof PIXI.settings - * @type {PIXI.MIPMAP_MODES} - * @default PIXI.MIPMAP_MODES.POW2 - */ - MIPMAP_TEXTURES: exports.MIPMAP_MODES.POW2, - /** - * Default anisotropic filtering level of textures. - * Usually from 0 to 16 - * @static - * @name ANISOTROPIC_LEVEL - * @memberof PIXI.settings - * @type {number} - * @default 0 - */ - ANISOTROPIC_LEVEL: 0, - /** - * Default resolution / device pixel ratio of the renderer. - * @static - * @name RESOLUTION - * @memberof PIXI.settings - * @type {number} - * @default 1 - */ - RESOLUTION: 1, - /** - * Default filter resolution. - * @static - * @name FILTER_RESOLUTION - * @memberof PIXI.settings - * @type {number} - * @default 1 - */ - FILTER_RESOLUTION: 1, - /** - * Default filter samples. - * @static - * @name FILTER_MULTISAMPLE - * @memberof PIXI.settings - * @type {PIXI.MSAA_QUALITY} - * @default PIXI.MSAA_QUALITY.NONE - */ - FILTER_MULTISAMPLE: exports.MSAA_QUALITY.NONE, - /** - * The maximum textures that this device supports. - * @static - * @name SPRITE_MAX_TEXTURES - * @memberof PIXI.settings - * @type {number} - * @default 32 - */ - SPRITE_MAX_TEXTURES: maxRecommendedTextures(32), - // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 - // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 - /** - * The default sprite batch size. - * - * The default aims to balance desktop and mobile devices. - * @static - * @name SPRITE_BATCH_SIZE - * @memberof PIXI.settings - * @type {number} - * @default 4096 - */ - SPRITE_BATCH_SIZE: 4096, - /** - * The default render options if none are supplied to {@link PIXI.Renderer} - * or {@link PIXI.CanvasRenderer}. - * @static - * @name RENDER_OPTIONS - * @memberof PIXI.settings - * @type {object} - * @property {boolean} [antialias=false] - {@link PIXI.IRendererOptions.antialias} - * @property {boolean} [autoDensity=false] - {@link PIXI.IRendererOptions.autoDensity} - * @property {number} [backgroundAlpha=1] - {@link PIXI.IRendererOptions.backgroundAlpha} - * @property {number} [backgroundColor=0x000000] - {@link PIXI.IRendererOptions.backgroundColor} - * @property {boolean} [clearBeforeRender=true] - {@link PIXI.IRendererOptions.clearBeforeRender} - * @property {number} [height=600] - {@link PIXI.IRendererOptions.height} - * @property {boolean} [preserveDrawingBuffer=false] - {@link PIXI.IRendererOptions.preserveDrawingBuffer} - * @property {boolean|'notMultiplied'} [useContextAlpha=true] - {@link PIXI.IRendererOptions.useContextAlpha} - * @property {HTMLCanvasElement} [view=null] - {@link PIXI.IRendererOptions.view} - * @property {number} [width=800] - {@link PIXI.IRendererOptions.width} - */ - RENDER_OPTIONS: { - view: null, - width: 800, - height: 600, - autoDensity: false, - backgroundColor: 0x000000, - backgroundAlpha: 1, - useContextAlpha: true, - clearBeforeRender: true, - antialias: false, - preserveDrawingBuffer: false, - }, - /** - * Default Garbage Collection mode. - * @static - * @name GC_MODE - * @memberof PIXI.settings - * @type {PIXI.GC_MODES} - * @default PIXI.GC_MODES.AUTO - */ - GC_MODE: exports.GC_MODES.AUTO, - /** - * Default Garbage Collection max idle. - * @static - * @name GC_MAX_IDLE - * @memberof PIXI.settings - * @type {number} - * @default 3600 - */ - GC_MAX_IDLE: 60 * 60, - /** - * Default Garbage Collection maximum check count. - * @static - * @name GC_MAX_CHECK_COUNT - * @memberof PIXI.settings - * @type {number} - * @default 600 - */ - GC_MAX_CHECK_COUNT: 60 * 10, - /** - * Default wrap modes that are supported by pixi. - * @static - * @name WRAP_MODE - * @memberof PIXI.settings - * @type {PIXI.WRAP_MODES} - * @default PIXI.WRAP_MODES.CLAMP - */ - WRAP_MODE: exports.WRAP_MODES.CLAMP, - /** - * Default scale mode for textures. - * @static - * @name SCALE_MODE - * @memberof PIXI.settings - * @type {PIXI.SCALE_MODES} - * @default PIXI.SCALE_MODES.LINEAR - */ - SCALE_MODE: exports.SCALE_MODES.LINEAR, - /** - * Default specify float precision in vertex shader. - * @static - * @name PRECISION_VERTEX - * @memberof PIXI.settings - * @type {PIXI.PRECISION} - * @default PIXI.PRECISION.HIGH - */ - PRECISION_VERTEX: exports.PRECISION.HIGH, - /** - * Default specify float precision in fragment shader. - * iOS is best set at highp due to https://github.com/pixijs/pixi.js/issues/3742 - * @static - * @name PRECISION_FRAGMENT - * @memberof PIXI.settings - * @type {PIXI.PRECISION} - * @default PIXI.PRECISION.MEDIUM - */ - PRECISION_FRAGMENT: isMobile.apple.device ? exports.PRECISION.HIGH : exports.PRECISION.MEDIUM, - /** - * Can we upload the same buffer in a single frame? - * @static - * @name CAN_UPLOAD_SAME_BUFFER - * @memberof PIXI.settings - * @type {boolean} - */ - CAN_UPLOAD_SAME_BUFFER: canUploadSameBuffer(), - /** - * Enables bitmap creation before image load. This feature is experimental. - * @static - * @name CREATE_IMAGE_BITMAP - * @memberof PIXI.settings - * @type {boolean} - * @default false - */ - CREATE_IMAGE_BITMAP: false, - /** - * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. - * Advantages can include sharper image quality (like text) and faster rendering on canvas. - * The main disadvantage is movement of objects may appear less smooth. - * @static - * @constant - * @memberof PIXI.settings - * @type {boolean} - * @default false - */ - ROUND_PIXELS: false, - }; - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createCommonjsModule(fn, basedir, module) { - return module = { - path: basedir, - exports: {}, - require: function (path, base) { - return commonjsRequire(path, (base === undefined || base === null) ? module.path : base); - } - }, fn(module, module.exports), module.exports; - } - - function getDefaultExportFromNamespaceIfPresent (n) { - return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n; - } - - function getDefaultExportFromNamespaceIfNotNamed (n) { - return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n; - } - - function getAugmentedNamespace(n) { - if (n.__esModule) return n; - var a = Object.defineProperty({}, '__esModule', {value: true}); - Object.keys(n).forEach(function (k) { - var d = Object.getOwnPropertyDescriptor(n, k); - Object.defineProperty(a, k, d.get ? d : { - enumerable: true, - get: function () { - return n[k]; - } - }); - }); - return a; - } - - function commonjsRequire () { - throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); - } - - var eventemitter3 = createCommonjsModule(function (module) { - 'use strict'; - - var has = Object.prototype.hasOwnProperty - , prefix = '~'; - - /** - * Constructor to create a storage for our `EE` objects. - * An `Events` instance is a plain object whose properties are event names. - * - * @constructor - * @private - */ - function Events() {} - - // - // We try to not inherit from `Object.prototype`. In some engines creating an - // instance in this way is faster than calling `Object.create(null)` directly. - // If `Object.create(null)` is not supported we prefix the event names with a - // character to make sure that the built-in object properties are not - // overridden or used as an attack vector. - // - if (Object.create) { - Events.prototype = Object.create(null); - - // - // This hack is needed because the `__proto__` property is still inherited in - // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. - // - if (!new Events().__proto__) { prefix = false; } - } - - /** - * Representation of a single event listener. - * - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} [once=false] Specify if the listener is a one-time listener. - * @constructor - * @private - */ - function EE(fn, context, once) { - this.fn = fn; - this.context = context; - this.once = once || false; - } - - /** - * Add a listener for a given event. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} once Specify if the listener is a one-time listener. - * @returns {EventEmitter} - * @private - */ - function addListener(emitter, event, fn, context, once) { - if (typeof fn !== 'function') { - throw new TypeError('The listener must be a function'); - } - - var listener = new EE(fn, context || emitter, once) - , evt = prefix ? prefix + event : event; - - if (!emitter._events[evt]) { emitter._events[evt] = listener, emitter._eventsCount++; } - else if (!emitter._events[evt].fn) { emitter._events[evt].push(listener); } - else { emitter._events[evt] = [emitter._events[evt], listener]; } - - return emitter; - } - - /** - * Clear event by name. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} evt The Event name. - * @private - */ - function clearEvent(emitter, evt) { - if (--emitter._eventsCount === 0) { emitter._events = new Events(); } - else { delete emitter._events[evt]; } - } - - /** - * Minimal `EventEmitter` interface that is molded against the Node.js - * `EventEmitter` interface. - * - * @constructor - * @public - */ - function EventEmitter() { - this._events = new Events(); - this._eventsCount = 0; - } - - /** - * Return an array listing the events for which the emitter has registered - * listeners. - * - * @returns {Array} - * @public - */ - EventEmitter.prototype.eventNames = function eventNames() { - var names = [] - , events - , name; - - if (this._eventsCount === 0) { return names; } - - for (name in (events = this._events)) { - if (has.call(events, name)) { names.push(prefix ? name.slice(1) : name); } - } - - if (Object.getOwnPropertySymbols) { - return names.concat(Object.getOwnPropertySymbols(events)); - } - - return names; - }; - - /** - * Return the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Array} The registered listeners. - * @public - */ - EventEmitter.prototype.listeners = function listeners(event) { - var evt = prefix ? prefix + event : event - , handlers = this._events[evt]; - - if (!handlers) { return []; } - if (handlers.fn) { return [handlers.fn]; } - - for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { - ee[i] = handlers[i].fn; - } - - return ee; - }; - - /** - * Return the number of listeners listening to a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Number} The number of listeners. - * @public - */ - EventEmitter.prototype.listenerCount = function listenerCount(event) { - var evt = prefix ? prefix + event : event - , listeners = this._events[evt]; - - if (!listeners) { return 0; } - if (listeners.fn) { return 1; } - return listeners.length; - }; - - /** - * Calls each of the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Boolean} `true` if the event had listeners, else `false`. - * @public - */ - EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { - var arguments$1 = arguments; - - var evt = prefix ? prefix + event : event; - - if (!this._events[evt]) { return false; } - - var listeners = this._events[evt] - , len = arguments.length - , args - , i; - - if (listeners.fn) { - if (listeners.once) { this.removeListener(event, listeners.fn, undefined, true); } - - switch (len) { - case 1: return listeners.fn.call(listeners.context), true; - case 2: return listeners.fn.call(listeners.context, a1), true; - case 3: return listeners.fn.call(listeners.context, a1, a2), true; - case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; - case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; - case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; - } - - for (i = 1, args = new Array(len -1); i < len; i++) { - args[i - 1] = arguments$1[i]; - } - - listeners.fn.apply(listeners.context, args); - } else { - var length = listeners.length - , j; - - for (i = 0; i < length; i++) { - if (listeners[i].once) { this.removeListener(event, listeners[i].fn, undefined, true); } - - switch (len) { - case 1: listeners[i].fn.call(listeners[i].context); break; - case 2: listeners[i].fn.call(listeners[i].context, a1); break; - case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; - case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; - default: - if (!args) { for (j = 1, args = new Array(len -1); j < len; j++) { - args[j - 1] = arguments$1[j]; - } } - - listeners[i].fn.apply(listeners[i].context, args); - } - } - } - - return true; - }; - - /** - * Add a listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ - EventEmitter.prototype.on = function on(event, fn, context) { - return addListener(this, event, fn, context, false); - }; - - /** - * Add a one-time listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ - EventEmitter.prototype.once = function once(event, fn, context) { - return addListener(this, event, fn, context, true); - }; - - /** - * Remove the listeners of a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn Only remove the listeners that match this function. - * @param {*} context Only remove the listeners that have this context. - * @param {Boolean} once Only remove one-time listeners. - * @returns {EventEmitter} `this`. - * @public - */ - EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { - var evt = prefix ? prefix + event : event; - - if (!this._events[evt]) { return this; } - if (!fn) { - clearEvent(this, evt); - return this; - } - - var listeners = this._events[evt]; - - if (listeners.fn) { - if ( - listeners.fn === fn && - (!once || listeners.once) && - (!context || listeners.context === context) - ) { - clearEvent(this, evt); - } - } else { - for (var i = 0, events = [], length = listeners.length; i < length; i++) { - if ( - listeners[i].fn !== fn || - (once && !listeners[i].once) || - (context && listeners[i].context !== context) - ) { - events.push(listeners[i]); - } - } - - // - // Reset the array, or remove it completely if we have no more listeners. - // - if (events.length) { this._events[evt] = events.length === 1 ? events[0] : events; } - else { clearEvent(this, evt); } - } - - return this; - }; - - /** - * Remove all listeners, or those of the specified event. - * - * @param {(String|Symbol)} [event] The event name. - * @returns {EventEmitter} `this`. - * @public - */ - EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; - - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) { clearEvent(this, evt); } - } else { - this._events = new Events(); - this._eventsCount = 0; - } - - return this; - }; - - // - // Alias methods names because people roll like that. - // - EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - EventEmitter.prototype.addListener = EventEmitter.prototype.on; - - // - // Expose the prefix. - // - EventEmitter.prefixed = prefix; - - // - // Allow `EventEmitter` to be imported as module namespace. - // - EventEmitter.EventEmitter = EventEmitter; - - // - // Expose the module. - // - if ('undefined' !== 'object') { - module.exports = EventEmitter; - } - }); - - 'use strict'; - - var earcut_1 = earcut; - var _default = earcut; - - function earcut(data, holeIndices, dim) { - - dim = dim || 2; - - var hasHoles = holeIndices && holeIndices.length, - outerLen = hasHoles ? holeIndices[0] * dim : data.length, - outerNode = linkedList(data, 0, outerLen, dim, true), - triangles = []; - - if (!outerNode || outerNode.next === outerNode.prev) { return triangles; } - - var minX, minY, maxX, maxY, x, y, invSize; - - if (hasHoles) { outerNode = eliminateHoles(data, holeIndices, outerNode, dim); } - - // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox - if (data.length > 80 * dim) { - minX = maxX = data[0]; - minY = maxY = data[1]; - - for (var i = dim; i < outerLen; i += dim) { - x = data[i]; - y = data[i + 1]; - if (x < minX) { minX = x; } - if (y < minY) { minY = y; } - if (x > maxX) { maxX = x; } - if (y > maxY) { maxY = y; } - } - - // minX, minY and invSize are later used to transform coords into integers for z-order calculation - invSize = Math.max(maxX - minX, maxY - minY); - invSize = invSize !== 0 ? 32767 / invSize : 0; - } - - earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); - - return triangles; - } - - // create a circular doubly linked list from polygon points in the specified winding order - function linkedList(data, start, end, dim, clockwise) { - var i, last; - - if (clockwise === (signedArea(data, start, end, dim) > 0)) { - for (i = start; i < end; i += dim) { last = insertNode(i, data[i], data[i + 1], last); } - } else { - for (i = end - dim; i >= start; i -= dim) { last = insertNode(i, data[i], data[i + 1], last); } - } - - if (last && equals(last, last.next)) { - removeNode(last); - last = last.next; - } - - return last; - } - - // eliminate colinear or duplicate points - function filterPoints(start, end) { - if (!start) { return start; } - if (!end) { end = start; } - - var p = start, - again; - do { - again = false; - - if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { - removeNode(p); - p = end = p.prev; - if (p === p.next) { break; } - again = true; - - } else { - p = p.next; - } - } while (again || p !== end); - - return end; - } - - // main ear slicing loop which triangulates a polygon (given as a linked list) - function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { - if (!ear) { return; } - - // interlink polygon nodes in z-order - if (!pass && invSize) { indexCurve(ear, minX, minY, invSize); } - - var stop = ear, - prev, next; - - // iterate through ears, slicing them one by one - while (ear.prev !== ear.next) { - prev = ear.prev; - next = ear.next; - - if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { - // cut off the triangle - triangles.push(prev.i / dim | 0); - triangles.push(ear.i / dim | 0); - triangles.push(next.i / dim | 0); - - removeNode(ear); - - // skipping the next vertex leads to less sliver triangles - ear = next.next; - stop = next.next; - - continue; - } - - ear = next; - - // if we looped through the whole remaining polygon and can't find any more ears - if (ear === stop) { - // try filtering points and slicing again - if (!pass) { - earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); - - // if this didn't work, try curing all small self-intersections locally - } else if (pass === 1) { - ear = cureLocalIntersections(filterPoints(ear), triangles, dim); - earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); - - // as a last resort, try splitting the remaining polygon into two - } else if (pass === 2) { - splitEarcut(ear, triangles, dim, minX, minY, invSize); - } - - break; - } - } - } - - // check whether a polygon node forms a valid ear with adjacent nodes - function isEar(ear) { - var a = ear.prev, - b = ear, - c = ear.next; - - if (area(a, b, c) >= 0) { return false; } // reflex, can't be an ear - - // now make sure we don't have other points inside the potential ear - var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; - - // triangle bbox; min & max are calculated like this for speed - var x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx), - y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy), - x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx), - y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy); - - var p = c.next; - while (p !== a) { - if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && - pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && - area(p.prev, p, p.next) >= 0) { return false; } - p = p.next; - } - - return true; - } - - function isEarHashed(ear, minX, minY, invSize) { - var a = ear.prev, - b = ear, - c = ear.next; - - if (area(a, b, c) >= 0) { return false; } // reflex, can't be an ear - - var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; - - // triangle bbox; min & max are calculated like this for speed - var x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx), - y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy), - x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx), - y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy); - - // z-order range for the current triangle bbox; - var minZ = zOrder(x0, y0, minX, minY, invSize), - maxZ = zOrder(x1, y1, minX, minY, invSize); - - var p = ear.prevZ, - n = ear.nextZ; - - // look for points inside the triangle in both directions - while (p && p.z >= minZ && n && n.z <= maxZ) { - if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && - pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) { return false; } - p = p.prevZ; - - if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && - pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) { return false; } - n = n.nextZ; - } - - // look for remaining points in decreasing z-order - while (p && p.z >= minZ) { - if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && - pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) { return false; } - p = p.prevZ; - } - - // look for remaining points in increasing z-order - while (n && n.z <= maxZ) { - if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && - pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) { return false; } - n = n.nextZ; - } - - return true; - } - - // go through all polygon nodes and cure small local self-intersections - function cureLocalIntersections(start, triangles, dim) { - var p = start; - do { - var a = p.prev, - b = p.next.next; - - if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { - - triangles.push(a.i / dim | 0); - triangles.push(p.i / dim | 0); - triangles.push(b.i / dim | 0); - - // remove two nodes involved - removeNode(p); - removeNode(p.next); - - p = start = b; - } - p = p.next; - } while (p !== start); - - return filterPoints(p); - } - - // try splitting polygon into two and triangulate them independently - function splitEarcut(start, triangles, dim, minX, minY, invSize) { - // look for a valid diagonal that divides the polygon into two - var a = start; - do { - var b = a.next.next; - while (b !== a.prev) { - if (a.i !== b.i && isValidDiagonal(a, b)) { - // split the polygon in two by the diagonal - var c = splitPolygon(a, b); - - // filter colinear points around the cuts - a = filterPoints(a, a.next); - c = filterPoints(c, c.next); - - // run earcut on each half - earcutLinked(a, triangles, dim, minX, minY, invSize, 0); - earcutLinked(c, triangles, dim, minX, minY, invSize, 0); - return; - } - b = b.next; - } - a = a.next; - } while (a !== start); - } - - // link every hole into the outer loop, producing a single-ring polygon without holes - function eliminateHoles(data, holeIndices, outerNode, dim) { - var queue = [], - i, len, start, end, list; - - for (i = 0, len = holeIndices.length; i < len; i++) { - start = holeIndices[i] * dim; - end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; - list = linkedList(data, start, end, dim, false); - if (list === list.next) { list.steiner = true; } - queue.push(getLeftmost(list)); - } - - queue.sort(compareX); - - // process holes from left to right - for (i = 0; i < queue.length; i++) { - outerNode = eliminateHole(queue[i], outerNode); - } - - return outerNode; - } - - function compareX(a, b) { - return a.x - b.x; - } - - // find a bridge between vertices that connects hole with an outer ring and and link it - function eliminateHole(hole, outerNode) { - var bridge = findHoleBridge(hole, outerNode); - if (!bridge) { - return outerNode; - } - - var bridgeReverse = splitPolygon(bridge, hole); - - // filter collinear points around the cuts - filterPoints(bridgeReverse, bridgeReverse.next); - return filterPoints(bridge, bridge.next); - } - - // David Eberly's algorithm for finding a bridge between hole and outer polygon - function findHoleBridge(hole, outerNode) { - var p = outerNode, - hx = hole.x, - hy = hole.y, - qx = -Infinity, - m; - - // find a segment intersected by a ray from the hole's leftmost point to the left; - // segment's endpoint with lesser x will be potential connection point - do { - if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { - var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); - if (x <= hx && x > qx) { - qx = x; - m = p.x < p.next.x ? p : p.next; - if (x === hx) { return m; } // hole touches outer segment; pick leftmost endpoint - } - } - p = p.next; - } while (p !== outerNode); - - if (!m) { return null; } - - // look for points inside the triangle of hole point, segment intersection and endpoint; - // if there are no points found, we have a valid connection; - // otherwise choose the point of the minimum angle with the ray as connection point - - var stop = m, - mx = m.x, - my = m.y, - tanMin = Infinity, - tan; - - p = m; - - do { - if (hx >= p.x && p.x >= mx && hx !== p.x && - pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { - - tan = Math.abs(hy - p.y) / (hx - p.x); // tangential - - if (locallyInside(p, hole) && - (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) { - m = p; - tanMin = tan; - } - } - - p = p.next; - } while (p !== stop); - - return m; - } - - // whether sector in vertex m contains sector in vertex p in the same coordinates - function sectorContainsSector(m, p) { - return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; - } - - // interlink polygon nodes in z-order - function indexCurve(start, minX, minY, invSize) { - var p = start; - do { - if (p.z === 0) { p.z = zOrder(p.x, p.y, minX, minY, invSize); } - p.prevZ = p.prev; - p.nextZ = p.next; - p = p.next; - } while (p !== start); - - p.prevZ.nextZ = null; - p.prevZ = null; - - sortLinked(p); - } - - // Simon Tatham's linked list merge sort algorithm - // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html - function sortLinked(list) { - var i, p, q, e, tail, numMerges, pSize, qSize, - inSize = 1; - - do { - p = list; - list = null; - tail = null; - numMerges = 0; - - while (p) { - numMerges++; - q = p; - pSize = 0; - for (i = 0; i < inSize; i++) { - pSize++; - q = q.nextZ; - if (!q) { break; } - } - qSize = inSize; - - while (pSize > 0 || (qSize > 0 && q)) { - - if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { - e = p; - p = p.nextZ; - pSize--; - } else { - e = q; - q = q.nextZ; - qSize--; - } - - if (tail) { tail.nextZ = e; } - else { list = e; } - - e.prevZ = tail; - tail = e; - } - - p = q; - } - - tail.nextZ = null; - inSize *= 2; - - } while (numMerges > 1); - - return list; - } - - // z-order of a point given coords and inverse of the longer side of data bbox - function zOrder(x, y, minX, minY, invSize) { - // coords are transformed into non-negative 15-bit integer range - x = (x - minX) * invSize | 0; - y = (y - minY) * invSize | 0; - - x = (x | (x << 8)) & 0x00FF00FF; - x = (x | (x << 4)) & 0x0F0F0F0F; - x = (x | (x << 2)) & 0x33333333; - x = (x | (x << 1)) & 0x55555555; - - y = (y | (y << 8)) & 0x00FF00FF; - y = (y | (y << 4)) & 0x0F0F0F0F; - y = (y | (y << 2)) & 0x33333333; - y = (y | (y << 1)) & 0x55555555; - - return x | (y << 1); - } - - // find the leftmost node of a polygon ring - function getLeftmost(start) { - var p = start, - leftmost = start; - do { - if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) { leftmost = p; } - p = p.next; - } while (p !== start); - - return leftmost; - } - - // check if a point lies within a convex triangle - function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { - return (cx - px) * (ay - py) >= (ax - px) * (cy - py) && - (ax - px) * (by - py) >= (bx - px) * (ay - py) && - (bx - px) * (cy - py) >= (cx - px) * (by - py); - } - - // check if a diagonal between two polygon nodes is valid (lies in polygon interior) - function isValidDiagonal(a, b) { - return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges - (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible - (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors - equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case - } - - // signed area of a triangle - function area(p, q, r) { - return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); - } - - // check if two points are equal - function equals(p1, p2) { - return p1.x === p2.x && p1.y === p2.y; - } - - // check if two segments intersect - function intersects(p1, q1, p2, q2) { - var o1 = sign$1(area(p1, q1, p2)); - var o2 = sign$1(area(p1, q1, q2)); - var o3 = sign$1(area(p2, q2, p1)); - var o4 = sign$1(area(p2, q2, q1)); - - if (o1 !== o2 && o3 !== o4) { return true; } // general case - - if (o1 === 0 && onSegment(p1, p2, q1)) { return true; } // p1, q1 and p2 are collinear and p2 lies on p1q1 - if (o2 === 0 && onSegment(p1, q2, q1)) { return true; } // p1, q1 and q2 are collinear and q2 lies on p1q1 - if (o3 === 0 && onSegment(p2, p1, q2)) { return true; } // p2, q2 and p1 are collinear and p1 lies on p2q2 - if (o4 === 0 && onSegment(p2, q1, q2)) { return true; } // p2, q2 and q1 are collinear and q1 lies on p2q2 - - return false; - } - - // for collinear points p, q, r, check if point q lies on segment pr - function onSegment(p, q, r) { - return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); - } - - function sign$1(num) { - return num > 0 ? 1 : num < 0 ? -1 : 0; - } - - // check if a polygon diagonal intersects any polygon segments - function intersectsPolygon(a, b) { - var p = a; - do { - if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && - intersects(p, p.next, a, b)) { return true; } - p = p.next; - } while (p !== a); - - return false; - } - - // check if a polygon diagonal is locally inside the polygon - function locallyInside(a, b) { - return area(a.prev, a, a.next) < 0 ? - area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : - area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; - } - - // check if the middle point of a polygon diagonal is inside the polygon - function middleInside(a, b) { - var p = a, - inside = false, - px = (a.x + b.x) / 2, - py = (a.y + b.y) / 2; - do { - if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && - (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) - { inside = !inside; } - p = p.next; - } while (p !== a); - - return inside; - } - - // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; - // if one belongs to the outer ring and another to a hole, it merges it into a single ring - function splitPolygon(a, b) { - var a2 = new Node(a.i, a.x, a.y), - b2 = new Node(b.i, b.x, b.y), - an = a.next, - bp = b.prev; - - a.next = b; - b.prev = a; - - a2.next = an; - an.prev = a2; - - b2.next = a2; - a2.prev = b2; - - bp.next = b2; - b2.prev = bp; - - return b2; - } - - // create a node and optionally link it with previous one (in a circular doubly linked list) - function insertNode(i, x, y, last) { - var p = new Node(i, x, y); - - if (!last) { - p.prev = p; - p.next = p; - - } else { - p.next = last.next; - p.prev = last; - last.next.prev = p; - last.next = p; - } - return p; - } - - function removeNode(p) { - p.next.prev = p.prev; - p.prev.next = p.next; - - if (p.prevZ) { p.prevZ.nextZ = p.nextZ; } - if (p.nextZ) { p.nextZ.prevZ = p.prevZ; } - } - - function Node(i, x, y) { - // vertex index in coordinates array - this.i = i; - - // vertex coordinates - this.x = x; - this.y = y; - - // previous and next vertex nodes in a polygon ring - this.prev = null; - this.next = null; - - // z-order curve value - this.z = 0; - - // previous and next nodes in z-order - this.prevZ = null; - this.nextZ = null; - - // indicates whether this is a steiner point - this.steiner = false; - } - - // return a percentage difference between the polygon area and its triangulation area; - // used to verify correctness of triangulation - earcut.deviation = function (data, holeIndices, dim, triangles) { - var hasHoles = holeIndices && holeIndices.length; - var outerLen = hasHoles ? holeIndices[0] * dim : data.length; - - var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); - if (hasHoles) { - for (var i = 0, len = holeIndices.length; i < len; i++) { - var start = holeIndices[i] * dim; - var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; - polygonArea -= Math.abs(signedArea(data, start, end, dim)); - } - } - - var trianglesArea = 0; - for (i = 0; i < triangles.length; i += 3) { - var a = triangles[i] * dim; - var b = triangles[i + 1] * dim; - var c = triangles[i + 2] * dim; - trianglesArea += Math.abs( - (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - - (data[a] - data[b]) * (data[c + 1] - data[a + 1])); - } - - return polygonArea === 0 && trianglesArea === 0 ? 0 : - Math.abs((trianglesArea - polygonArea) / polygonArea); - }; - - function signedArea(data, start, end, dim) { - var sum = 0; - for (var i = start, j = end - dim; i < end; i += dim) { - sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); - j = i; - } - return sum; - } - - // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts - earcut.flatten = function (data) { - var dim = data[0][0].length, - result = {vertices: [], holes: [], dimensions: dim}, - holeIndex = 0; - - for (var i = 0; i < data.length; i++) { - for (var j = 0; j < data[i].length; j++) { - for (var d = 0; d < dim; d++) { result.vertices.push(data[i][j][d]); } - } - if (i > 0) { - holeIndex += data[i - 1].length; - result.holes.push(holeIndex); - } - } - return result; - }; - earcut_1.default = _default; - - var punycode = createCommonjsModule(function (module, exports) { - /*! https://mths.be/punycode v1.3.2 by @mathias */ - ;(function(root) { - - /** Detect free variables */ - var freeExports = 'object' == 'object' && exports && - !exports.nodeType && exports; - var freeModule = 'object' == 'object' && module && - !module.nodeType && module; - var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal; - if ( - freeGlobal.global === freeGlobal || - freeGlobal.window === freeGlobal || - freeGlobal.self === freeGlobal - ) { - root = freeGlobal; - } - - /** - * The `punycode` object. - * @name punycode - * @type Object - */ - var punycode, - - /** Highest positive signed 32-bit float value */ - maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 - - /** Bootstring parameters */ - base = 36, - tMin = 1, - tMax = 26, - skew = 38, - damp = 700, - initialBias = 72, - initialN = 128, // 0x80 - delimiter = '-', // '\x2D' - - /** Regular expressions */ - regexPunycode = /^xn--/, - regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars - regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators - - /** Error messages */ - errors = { - 'overflow': 'Overflow: input needs wider integers to process', - 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', - 'invalid-input': 'Invalid input' - }, - - /** Convenience shortcuts */ - baseMinusTMin = base - tMin, - floor = Math.floor, - stringFromCharCode = String.fromCharCode, - - /** Temporary variable */ - key; - - /*--------------------------------------------------------------------------*/ - - /** - * A generic error utility function. - * @private - * @param {String} type The error type. - * @returns {Error} Throws a `RangeError` with the applicable error message. - */ - function error(type) { - throw RangeError(errors[type]); - } - - /** - * A generic `Array#map` utility function. - * @private - * @param {Array} array The array to iterate over. - * @param {Function} callback The function that gets called for every array - * item. - * @returns {Array} A new array of values returned by the callback function. - */ - function map(array, fn) { - var length = array.length; - var result = []; - while (length--) { - result[length] = fn(array[length]); - } - return result; - } - - /** - * A simple `Array#map`-like wrapper to work with domain name strings or email - * addresses. - * @private - * @param {String} domain The domain name or email address. - * @param {Function} callback The function that gets called for every - * character. - * @returns {Array} A new string of characters returned by the callback - * function. - */ - function mapDomain(string, fn) { - var parts = string.split('@'); - var result = ''; - if (parts.length > 1) { - // In email addresses, only the domain name should be punycoded. Leave - // the local part (i.e. everything up to `@`) intact. - result = parts[0] + '@'; - string = parts[1]; - } - // Avoid `split(regex)` for IE8 compatibility. See #17. - string = string.replace(regexSeparators, '\x2E'); - var labels = string.split('.'); - var encoded = map(labels, fn).join('.'); - return result + encoded; - } - - /** - * Creates an array containing the numeric code points of each Unicode - * character in the string. While JavaScript uses UCS-2 internally, - * this function will convert a pair of surrogate halves (each of which - * UCS-2 exposes as separate characters) into a single code point, - * matching UTF-16. - * @see `punycode.ucs2.encode` - * @see - * @memberOf punycode.ucs2 - * @name decode - * @param {String} string The Unicode input string (UCS-2). - * @returns {Array} The new array of code points. - */ - function ucs2decode(string) { - var output = [], - counter = 0, - length = string.length, - value, - extra; - while (counter < length) { - value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // high surrogate, and there is a next character - extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { // low surrogate - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else { - // unmatched surrogate; only append this code unit, in case the next - // code unit is the high surrogate of a surrogate pair - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; - } - - /** - * Creates a string based on an array of numeric code points. - * @see `punycode.ucs2.decode` - * @memberOf punycode.ucs2 - * @name encode - * @param {Array} codePoints The array of numeric code points. - * @returns {String} The new Unicode string (UCS-2). - */ - function ucs2encode(array) { - return map(array, function(value) { - var output = ''; - if (value > 0xFFFF) { - value -= 0x10000; - output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); - value = 0xDC00 | value & 0x3FF; - } - output += stringFromCharCode(value); - return output; - }).join(''); - } - - /** - * Converts a basic code point into a digit/integer. - * @see `digitToBasic()` - * @private - * @param {Number} codePoint The basic numeric code point value. - * @returns {Number} The numeric value of a basic code point (for use in - * representing integers) in the range `0` to `base - 1`, or `base` if - * the code point does not represent a value. - */ - function basicToDigit(codePoint) { - if (codePoint - 48 < 10) { - return codePoint - 22; - } - if (codePoint - 65 < 26) { - return codePoint - 65; - } - if (codePoint - 97 < 26) { - return codePoint - 97; - } - return base; - } - - /** - * Converts a digit/integer into a basic code point. - * @see `basicToDigit()` - * @private - * @param {Number} digit The numeric value of a basic code point. - * @returns {Number} The basic code point whose value (when used for - * representing integers) is `digit`, which needs to be in the range - * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is - * used; else, the lowercase form is used. The behavior is undefined - * if `flag` is non-zero and `digit` has no uppercase form. - */ - function digitToBasic(digit, flag) { - // 0..25 map to ASCII a..z or A..Z - // 26..35 map to ASCII 0..9 - return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); - } - - /** - * Bias adaptation function as per section 3.4 of RFC 3492. - * http://tools.ietf.org/html/rfc3492#section-3.4 - * @private - */ - function adapt(delta, numPoints, firstTime) { - var k = 0; - delta = firstTime ? floor(delta / damp) : delta >> 1; - delta += floor(delta / numPoints); - for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { - delta = floor(delta / baseMinusTMin); - } - return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); - } - - /** - * Converts a Punycode string of ASCII-only symbols to a string of Unicode - * symbols. - * @memberOf punycode - * @param {String} input The Punycode string of ASCII-only symbols. - * @returns {String} The resulting string of Unicode symbols. - */ - function decode(input) { - // Don't use UCS-2 - var output = [], - inputLength = input.length, - out, - i = 0, - n = initialN, - bias = initialBias, - basic, - j, - index, - oldi, - w, - k, - digit, - t, - /** Cached calculation results */ - baseMinusT; - - // Handle the basic code points: let `basic` be the number of input code - // points before the last delimiter, or `0` if there is none, then copy - // the first basic code points to the output. - - basic = input.lastIndexOf(delimiter); - if (basic < 0) { - basic = 0; - } - - for (j = 0; j < basic; ++j) { - // if it's not a basic code point - if (input.charCodeAt(j) >= 0x80) { - error('not-basic'); - } - output.push(input.charCodeAt(j)); - } - - // Main decoding loop: start just after the last delimiter if any basic code - // points were copied; start at the beginning otherwise. - - for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { - - // `index` is the index of the next character to be consumed. - // Decode a generalized variable-length integer into `delta`, - // which gets added to `i`. The overflow checking is easier - // if we increase `i` as we go, then subtract off its starting - // value at the end to obtain `delta`. - for (oldi = i, w = 1, k = base; /* no condition */; k += base) { - - if (index >= inputLength) { - error('invalid-input'); - } - - digit = basicToDigit(input.charCodeAt(index++)); - - if (digit >= base || digit > floor((maxInt - i) / w)) { - error('overflow'); - } - - i += digit * w; - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - - if (digit < t) { - break; - } - - baseMinusT = base - t; - if (w > floor(maxInt / baseMinusT)) { - error('overflow'); - } - - w *= baseMinusT; - - } - - out = output.length + 1; - bias = adapt(i - oldi, out, oldi == 0); - - // `i` was supposed to wrap around from `out` to `0`, - // incrementing `n` each time, so we'll fix that now: - if (floor(i / out) > maxInt - n) { - error('overflow'); - } - - n += floor(i / out); - i %= out; - - // Insert `n` at position `i` of the output - output.splice(i++, 0, n); - - } - - return ucs2encode(output); - } - - /** - * Converts a string of Unicode symbols (e.g. a domain name label) to a - * Punycode string of ASCII-only symbols. - * @memberOf punycode - * @param {String} input The string of Unicode symbols. - * @returns {String} The resulting Punycode string of ASCII-only symbols. - */ - function encode(input) { - var n, - delta, - handledCPCount, - basicLength, - bias, - j, - m, - q, - k, - t, - currentValue, - output = [], - /** `inputLength` will hold the number of code points in `input`. */ - inputLength, - /** Cached calculation results */ - handledCPCountPlusOne, - baseMinusT, - qMinusT; - - // Convert the input in UCS-2 to Unicode - input = ucs2decode(input); - - // Cache the length - inputLength = input.length; - - // Initialize the state - n = initialN; - delta = 0; - bias = initialBias; - - // Handle the basic code points - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue < 0x80) { - output.push(stringFromCharCode(currentValue)); - } - } - - handledCPCount = basicLength = output.length; - - // `handledCPCount` is the number of code points that have been handled; - // `basicLength` is the number of basic code points. - - // Finish the basic string - if it is not empty - with a delimiter - if (basicLength) { - output.push(delimiter); - } - - // Main encoding loop: - while (handledCPCount < inputLength) { - - // All non-basic code points < n have been handled already. Find the next - // larger one: - for (m = maxInt, j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue >= n && currentValue < m) { - m = currentValue; - } - } - - // Increase `delta` enough to advance the decoder's state to , - // but guard against overflow - handledCPCountPlusOne = handledCPCount + 1; - if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { - error('overflow'); - } - - delta += (m - n) * handledCPCountPlusOne; - n = m; - - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - - if (currentValue < n && ++delta > maxInt) { - error('overflow'); - } - - if (currentValue == n) { - // Represent delta as a generalized variable-length integer - for (q = delta, k = base; /* no condition */; k += base) { - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - if (q < t) { - break; - } - qMinusT = q - t; - baseMinusT = base - t; - output.push( - stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) - ); - q = floor(qMinusT / baseMinusT); - } - - output.push(stringFromCharCode(digitToBasic(q, 0))); - bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); - delta = 0; - ++handledCPCount; - } - } - - ++delta; - ++n; - - } - return output.join(''); - } - - /** - * Converts a Punycode string representing a domain name or an email address - * to Unicode. Only the Punycoded parts of the input will be converted, i.e. - * it doesn't matter if you call it on a string that has already been - * converted to Unicode. - * @memberOf punycode - * @param {String} input The Punycoded domain name or email address to - * convert to Unicode. - * @returns {String} The Unicode representation of the given Punycode - * string. - */ - function toUnicode(input) { - return mapDomain(input, function(string) { - return regexPunycode.test(string) - ? decode(string.slice(4).toLowerCase()) - : string; - }); - } - - /** - * Converts a Unicode string representing a domain name or an email address to - * Punycode. Only the non-ASCII parts of the domain name will be converted, - * i.e. it doesn't matter if you call it with a domain that's already in - * ASCII. - * @memberOf punycode - * @param {String} input The domain name or email address to convert, as a - * Unicode string. - * @returns {String} The Punycode representation of the given domain name or - * email address. - */ - function toASCII(input) { - return mapDomain(input, function(string) { - return regexNonASCII.test(string) - ? 'xn--' + encode(string) - : string; - }); - } - - /*--------------------------------------------------------------------------*/ - - /** Define the public API */ - punycode = { - /** - * A string representing the current Punycode.js version number. - * @memberOf punycode - * @type String - */ - 'version': '1.3.2', - /** - * An object of methods to convert from JavaScript's internal character - * representation (UCS-2) to Unicode code points, and back. - * @see - * @memberOf punycode - * @type Object - */ - 'ucs2': { - 'decode': ucs2decode, - 'encode': ucs2encode - }, - 'decode': decode, - 'encode': encode, - 'toASCII': toASCII, - 'toUnicode': toUnicode - }; - - /** Expose `punycode` */ - // Some AMD build optimizers, like r.js, check for specific condition patterns - // like the following: - if ( - typeof undefined == 'function' && - typeof undefined.amd == 'object' && - undefined.amd - ) { - undefined('punycode', function() { - return punycode; - }); - } else if (freeExports && freeModule) { - if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+ - freeModule.exports = punycode; - } else { // in Narwhal or RingoJS v0.7.0- - for (key in punycode) { - punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); - } - } - } else { // in Rhino or a web browser - root.punycode = punycode; - } - - }(commonjsGlobal)); - }); - - 'use strict'; - - var util = { - isString: function(arg) { - return typeof(arg) === 'string'; - }, - isObject: function(arg) { - return typeof(arg) === 'object' && arg !== null; - }, - isNull: function(arg) { - return arg === null; - }, - isNullOrUndefined: function(arg) { - return arg == null; - } - }; - - // Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - 'use strict'; - - // If obj.hasOwnProperty has been overridden, then calling - // obj.hasOwnProperty(prop) will break. - // See: https://github.com/joyent/node/issues/1707 - function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); - } - - var decode = function(qs, sep, eq, options) { - sep = sep || '&'; - eq = eq || '='; - var obj = {}; - - if (typeof qs !== 'string' || qs.length === 0) { - return obj; - } - - var regexp = /\+/g; - qs = qs.split(sep); - - var maxKeys = 1000; - if (options && typeof options.maxKeys === 'number') { - maxKeys = options.maxKeys; - } - - var len = qs.length; - // maxKeys <= 0 means that we should not limit keys count - if (maxKeys > 0 && len > maxKeys) { - len = maxKeys; - } - - for (var i = 0; i < len; ++i) { - var x = qs[i].replace(regexp, '%20'), - idx = x.indexOf(eq), - kstr, vstr, k, v; - - if (idx >= 0) { - kstr = x.substr(0, idx); - vstr = x.substr(idx + 1); - } else { - kstr = x; - vstr = ''; - } - - k = decodeURIComponent(kstr); - v = decodeURIComponent(vstr); - - if (!hasOwnProperty(obj, k)) { - obj[k] = v; - } else if (Array.isArray(obj[k])) { - obj[k].push(v); - } else { - obj[k] = [obj[k], v]; - } - } - - return obj; - }; - - // Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - 'use strict'; - - var stringifyPrimitive = function(v) { - switch (typeof v) { - case 'string': - return v; - - case 'boolean': - return v ? 'true' : 'false'; - - case 'number': - return isFinite(v) ? v : ''; - - default: - return ''; - } - }; - - var encode = function(obj, sep, eq, name) { - sep = sep || '&'; - eq = eq || '='; - if (obj === null) { - obj = undefined; - } - - if (typeof obj === 'object') { - return Object.keys(obj).map(function(k) { - var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; - if (Array.isArray(obj[k])) { - return obj[k].map(function(v) { - return ks + encodeURIComponent(stringifyPrimitive(v)); - }).join(sep); - } else { - return ks + encodeURIComponent(stringifyPrimitive(obj[k])); - } - }).join(sep); - - } - - if (!name) { return ''; } - return encodeURIComponent(stringifyPrimitive(name)) + eq + - encodeURIComponent(stringifyPrimitive(obj)); - }; - - var querystring = createCommonjsModule(function (module, exports) { - 'use strict'; - - exports.decode = exports.parse = decode; - exports.encode = exports.stringify = encode; - }); - - // Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - 'use strict'; - - - - - var parse = urlParse; - var resolve = urlResolve; - var resolveObject = urlResolveObject; - var format = urlFormat; - - var Url_1 = Url; - - function Url() { - this.protocol = null; - this.slashes = null; - this.auth = null; - this.host = null; - this.port = null; - this.hostname = null; - this.hash = null; - this.search = null; - this.query = null; - this.pathname = null; - this.path = null; - this.href = null; - } - - // Reference: RFC 3986, RFC 1808, RFC 2396 - - // define these here so at least they only have to be - // compiled once on the first module load. - var protocolPattern = /^([a-z0-9.+-]+:)/i, - portPattern = /:[0-9]*$/, - - // Special case for a simple path URL - simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, - - // RFC 2396: characters reserved for delimiting URLs. - // We actually just auto-escape these. - delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], - - // RFC 2396: characters not allowed for various reasons. - unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), - - // Allowed by RFCs, but cause of XSS attacks. Always escape these. - autoEscape = ['\''].concat(unwise), - // Characters that are never ever allowed in a hostname. - // Note that any invalid chars are also handled, but these - // are the ones that are *expected* to be seen, so we fast-path - // them. - nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), - hostEndingChars = ['/', '?', '#'], - hostnameMaxLen = 255, - hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, - hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, - // protocols that can allow "unsafe" and "unwise" chars. - unsafeProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that never have a hostname. - hostlessProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that always contain a // bit. - slashedProtocol = { - 'http': true, - 'https': true, - 'ftp': true, - 'gopher': true, - 'file': true, - 'http:': true, - 'https:': true, - 'ftp:': true, - 'gopher:': true, - 'file:': true - }; - - function urlParse(url, parseQueryString, slashesDenoteHost) { - if (url && util.isObject(url) && url instanceof Url) { return url; } - - var u = new Url; - u.parse(url, parseQueryString, slashesDenoteHost); - return u; - } - - Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { - if (!util.isString(url)) { - throw new TypeError("Parameter 'url' must be a string, not " + typeof url); - } - - // Copy chrome, IE, opera backslash-handling behavior. - // Back slashes before the query string get converted to forward slashes - // See: https://code.google.com/p/chromium/issues/detail?id=25916 - var queryIndex = url.indexOf('?'), - splitter = - (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', - uSplit = url.split(splitter), - slashRegex = /\\/g; - uSplit[0] = uSplit[0].replace(slashRegex, '/'); - url = uSplit.join(splitter); - - var rest = url; - - // trim before proceeding. - // This is to support parse stuff like " http://foo.com \n" - rest = rest.trim(); - - if (!slashesDenoteHost && url.split('#').length === 1) { - // Try fast path regexp - var simplePath = simplePathPattern.exec(rest); - if (simplePath) { - this.path = rest; - this.href = rest; - this.pathname = simplePath[1]; - if (simplePath[2]) { - this.search = simplePath[2]; - if (parseQueryString) { - this.query = querystring.parse(this.search.substr(1)); - } else { - this.query = this.search.substr(1); - } - } else if (parseQueryString) { - this.search = ''; - this.query = {}; - } - return this; - } - } - - var proto = protocolPattern.exec(rest); - if (proto) { - proto = proto[0]; - var lowerProto = proto.toLowerCase(); - this.protocol = lowerProto; - rest = rest.substr(proto.length); - } - - // figure out if it's got a host - // user@server is *always* interpreted as a hostname, and url - // resolution will treat //foo/bar as host=foo,path=bar because that's - // how the browser resolves relative URLs. - if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { - var slashes = rest.substr(0, 2) === '//'; - if (slashes && !(proto && hostlessProtocol[proto])) { - rest = rest.substr(2); - this.slashes = true; - } - } - - if (!hostlessProtocol[proto] && - (slashes || (proto && !slashedProtocol[proto]))) { - - // there's a hostname. - // the first instance of /, ?, ;, or # ends the host. - // - // If there is an @ in the hostname, then non-host chars *are* allowed - // to the left of the last @ sign, unless some host-ending character - // comes *before* the @-sign. - // URLs are obnoxious. - // - // ex: - // http://a@b@c/ => user:a@b host:c - // http://a@b?@c => user:a host:c path:/?@c - - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. - - // find the first instance of any hostEndingChars - var hostEnd = -1; - for (var i = 0; i < hostEndingChars.length; i++) { - var hec = rest.indexOf(hostEndingChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - { hostEnd = hec; } - } - - // at this point, either we have an explicit point where the - // auth portion cannot go past, or the last @ char is the decider. - var auth, atSign; - if (hostEnd === -1) { - // atSign can be anywhere. - atSign = rest.lastIndexOf('@'); - } else { - // atSign must be in auth portion. - // http://a@b/c@d => host:b auth:a path:/c@d - atSign = rest.lastIndexOf('@', hostEnd); - } - - // Now we have a portion which is definitely the auth. - // Pull that off. - if (atSign !== -1) { - auth = rest.slice(0, atSign); - rest = rest.slice(atSign + 1); - this.auth = decodeURIComponent(auth); - } - - // the host is the remaining to the left of the first non-host char - hostEnd = -1; - for (var i = 0; i < nonHostChars.length; i++) { - var hec = rest.indexOf(nonHostChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - { hostEnd = hec; } - } - // if we still have not hit it, then the entire thing is a host. - if (hostEnd === -1) - { hostEnd = rest.length; } - - this.host = rest.slice(0, hostEnd); - rest = rest.slice(hostEnd); - - // pull out port. - this.parseHost(); - - // we've indicated that there is a hostname, - // so even if it's empty, it has to be present. - this.hostname = this.hostname || ''; - - // if hostname begins with [ and ends with ] - // assume that it's an IPv6 address. - var ipv6Hostname = this.hostname[0] === '[' && - this.hostname[this.hostname.length - 1] === ']'; - - // validate a little. - if (!ipv6Hostname) { - var hostparts = this.hostname.split(/\./); - for (var i = 0, l = hostparts.length; i < l; i++) { - var part = hostparts[i]; - if (!part) { continue; } - if (!part.match(hostnamePartPattern)) { - var newpart = ''; - for (var j = 0, k = part.length; j < k; j++) { - if (part.charCodeAt(j) > 127) { - // we replace non-ASCII char with a temporary placeholder - // we need this to make sure size of hostname is not - // broken by replacing non-ASCII by nothing - newpart += 'x'; - } else { - newpart += part[j]; - } - } - // we test again with ASCII char only - if (!newpart.match(hostnamePartPattern)) { - var validParts = hostparts.slice(0, i); - var notHost = hostparts.slice(i + 1); - var bit = part.match(hostnamePartStart); - if (bit) { - validParts.push(bit[1]); - notHost.unshift(bit[2]); - } - if (notHost.length) { - rest = '/' + notHost.join('.') + rest; - } - this.hostname = validParts.join('.'); - break; - } - } - } - } - - if (this.hostname.length > hostnameMaxLen) { - this.hostname = ''; - } else { - // hostnames are always lower case. - this.hostname = this.hostname.toLowerCase(); - } - - if (!ipv6Hostname) { - // IDNA Support: Returns a punycoded representation of "domain". - // It only converts parts of the domain name that - // have non-ASCII characters, i.e. it doesn't matter if - // you call it with a domain that already is ASCII-only. - this.hostname = punycode.toASCII(this.hostname); - } - - var p = this.port ? ':' + this.port : ''; - var h = this.hostname || ''; - this.host = h + p; - this.href += this.host; - - // strip [ and ] from the hostname - // the host field still retains them, though - if (ipv6Hostname) { - this.hostname = this.hostname.substr(1, this.hostname.length - 2); - if (rest[0] !== '/') { - rest = '/' + rest; - } - } - } - - // now rest is set to the post-host stuff. - // chop off any delim chars. - if (!unsafeProtocol[lowerProto]) { - - // First, make 100% sure that any "autoEscape" chars get - // escaped, even if encodeURIComponent doesn't think they - // need to be. - for (var i = 0, l = autoEscape.length; i < l; i++) { - var ae = autoEscape[i]; - if (rest.indexOf(ae) === -1) - { continue; } - var esc = encodeURIComponent(ae); - if (esc === ae) { - esc = escape(ae); - } - rest = rest.split(ae).join(esc); - } - } - - - // chop off from the tail first. - var hash = rest.indexOf('#'); - if (hash !== -1) { - // got a fragment string. - this.hash = rest.substr(hash); - rest = rest.slice(0, hash); - } - var qm = rest.indexOf('?'); - if (qm !== -1) { - this.search = rest.substr(qm); - this.query = rest.substr(qm + 1); - if (parseQueryString) { - this.query = querystring.parse(this.query); - } - rest = rest.slice(0, qm); - } else if (parseQueryString) { - // no query string, but parseQueryString still requested - this.search = ''; - this.query = {}; - } - if (rest) { this.pathname = rest; } - if (slashedProtocol[lowerProto] && - this.hostname && !this.pathname) { - this.pathname = '/'; - } - - //to support http.request - if (this.pathname || this.search) { - var p = this.pathname || ''; - var s = this.search || ''; - this.path = p + s; - } - - // finally, reconstruct the href based on what has been validated. - this.href = this.format(); - return this; - }; - - // format a parsed object into a url string - function urlFormat(obj) { - // ensure it's an object, and not a string url. - // If it's an obj, this is a no-op. - // this way, you can call url_format() on strings - // to clean up potentially wonky urls. - if (util.isString(obj)) { obj = urlParse(obj); } - if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); } - return obj.format(); - } - - Url.prototype.format = function() { - var auth = this.auth || ''; - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ':'); - auth += '@'; - } - - var protocol = this.protocol || '', - pathname = this.pathname || '', - hash = this.hash || '', - host = false, - query = ''; - - if (this.host) { - host = auth + this.host; - } else if (this.hostname) { - host = auth + (this.hostname.indexOf(':') === -1 ? - this.hostname : - '[' + this.hostname + ']'); - if (this.port) { - host += ':' + this.port; - } - } - - if (this.query && - util.isObject(this.query) && - Object.keys(this.query).length) { - query = querystring.stringify(this.query); - } - - var search = this.search || (query && ('?' + query)) || ''; - - if (protocol && protocol.substr(-1) !== ':') { protocol += ':'; } - - // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. - // unless they had them to begin with. - if (this.slashes || - (!protocol || slashedProtocol[protocol]) && host !== false) { - host = '//' + (host || ''); - if (pathname && pathname.charAt(0) !== '/') { pathname = '/' + pathname; } - } else if (!host) { - host = ''; - } - - if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; } - if (search && search.charAt(0) !== '?') { search = '?' + search; } - - pathname = pathname.replace(/[?#]/g, function(match) { - return encodeURIComponent(match); - }); - search = search.replace('#', '%23'); - - return protocol + host + pathname + search + hash; - }; - - function urlResolve(source, relative) { - return urlParse(source, false, true).resolve(relative); - } - - Url.prototype.resolve = function(relative) { - return this.resolveObject(urlParse(relative, false, true)).format(); - }; - - function urlResolveObject(source, relative) { - if (!source) { return relative; } - return urlParse(source, false, true).resolveObject(relative); - } - - Url.prototype.resolveObject = function(relative) { - if (util.isString(relative)) { - var rel = new Url(); - rel.parse(relative, false, true); - relative = rel; - } - - var result = new Url(); - var tkeys = Object.keys(this); - for (var tk = 0; tk < tkeys.length; tk++) { - var tkey = tkeys[tk]; - result[tkey] = this[tkey]; - } - - // hash is always overridden, no matter what. - // even href="" will remove it. - result.hash = relative.hash; - - // if the relative url is empty, then there's nothing left to do here. - if (relative.href === '') { - result.href = result.format(); - return result; - } - - // hrefs like //foo/bar always cut to the protocol. - if (relative.slashes && !relative.protocol) { - // take everything except the protocol from relative - var rkeys = Object.keys(relative); - for (var rk = 0; rk < rkeys.length; rk++) { - var rkey = rkeys[rk]; - if (rkey !== 'protocol') - { result[rkey] = relative[rkey]; } - } - - //urlParse appends trailing / to urls like http://www.example.com - if (slashedProtocol[result.protocol] && - result.hostname && !result.pathname) { - result.path = result.pathname = '/'; - } - - result.href = result.format(); - return result; - } - - if (relative.protocol && relative.protocol !== result.protocol) { - // if it's a known url protocol, then changing - // the protocol does weird things - // first, if it's not file:, then we MUST have a host, - // and if there was a path - // to begin with, then we MUST have a path. - // if it is file:, then the host is dropped, - // because that's known to be hostless. - // anything else is assumed to be absolute. - if (!slashedProtocol[relative.protocol]) { - var keys = Object.keys(relative); - for (var v = 0; v < keys.length; v++) { - var k = keys[v]; - result[k] = relative[k]; - } - result.href = result.format(); - return result; - } - - result.protocol = relative.protocol; - if (!relative.host && !hostlessProtocol[relative.protocol]) { - var relPath = (relative.pathname || '').split('/'); - while (relPath.length && !(relative.host = relPath.shift())){ ; } - if (!relative.host) { relative.host = ''; } - if (!relative.hostname) { relative.hostname = ''; } - if (relPath[0] !== '') { relPath.unshift(''); } - if (relPath.length < 2) { relPath.unshift(''); } - result.pathname = relPath.join('/'); - } else { - result.pathname = relative.pathname; - } - result.search = relative.search; - result.query = relative.query; - result.host = relative.host || ''; - result.auth = relative.auth; - result.hostname = relative.hostname || relative.host; - result.port = relative.port; - // to support http.request - if (result.pathname || result.search) { - var p = result.pathname || ''; - var s = result.search || ''; - result.path = p + s; - } - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; - } - - var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), - isRelAbs = ( - relative.host || - relative.pathname && relative.pathname.charAt(0) === '/' - ), - mustEndAbs = (isRelAbs || isSourceAbs || - (result.host && relative.pathname)), - removeAllDots = mustEndAbs, - srcPath = result.pathname && result.pathname.split('/') || [], - relPath = relative.pathname && relative.pathname.split('/') || [], - psychotic = result.protocol && !slashedProtocol[result.protocol]; - - // if the url is a non-slashed url, then relative - // links like ../.. should be able - // to crawl up to the hostname, as well. This is strange. - // result.protocol has already been set by now. - // Later on, put the first path part into the host field. - if (psychotic) { - result.hostname = ''; - result.port = null; - if (result.host) { - if (srcPath[0] === '') { srcPath[0] = result.host; } - else { srcPath.unshift(result.host); } - } - result.host = ''; - if (relative.protocol) { - relative.hostname = null; - relative.port = null; - if (relative.host) { - if (relPath[0] === '') { relPath[0] = relative.host; } - else { relPath.unshift(relative.host); } - } - relative.host = null; - } - mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); - } - - if (isRelAbs) { - // it's absolute. - result.host = (relative.host || relative.host === '') ? - relative.host : result.host; - result.hostname = (relative.hostname || relative.hostname === '') ? - relative.hostname : result.hostname; - result.search = relative.search; - result.query = relative.query; - srcPath = relPath; - // fall through to the dot-handling below. - } else if (relPath.length) { - // it's relative - // throw away the existing file, and take the new path instead. - if (!srcPath) { srcPath = []; } - srcPath.pop(); - srcPath = srcPath.concat(relPath); - result.search = relative.search; - result.query = relative.query; - } else if (!util.isNullOrUndefined(relative.search)) { - // just pull out the search. - // like href='?foo'. - // Put this after the other two cases because it simplifies the booleans - if (psychotic) { - result.hostname = result.host = srcPath.shift(); - //occationaly the auth can get stuck only in host - //this especially happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - result.search = relative.search; - result.query = relative.query; - //to support http.request - if (!util.isNull(result.pathname) || !util.isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.href = result.format(); - return result; - } - - if (!srcPath.length) { - // no path at all. easy. - // we've already handled the other stuff above. - result.pathname = null; - //to support http.request - if (result.search) { - result.path = '/' + result.search; - } else { - result.path = null; - } - result.href = result.format(); - return result; - } - - // if a url ENDs in . or .., then it must get a trailing slash. - // however, if it ends in anything else non-slashy, - // then it must NOT get a trailing slash. - var last = srcPath.slice(-1)[0]; - var hasTrailingSlash = ( - (result.host || relative.host || srcPath.length > 1) && - (last === '.' || last === '..') || last === ''); - - // strip single dots, resolve double dots to parent dir - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = srcPath.length; i >= 0; i--) { - last = srcPath[i]; - if (last === '.') { - srcPath.splice(i, 1); - } else if (last === '..') { - srcPath.splice(i, 1); - up++; - } else if (up) { - srcPath.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift('..'); - } - } - - if (mustEndAbs && srcPath[0] !== '' && - (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { - srcPath.unshift(''); - } - - if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { - srcPath.push(''); - } - - var isAbsolute = srcPath[0] === '' || - (srcPath[0] && srcPath[0].charAt(0) === '/'); - - // put the host back - if (psychotic) { - result.hostname = result.host = isAbsolute ? '' : - srcPath.length ? srcPath.shift() : ''; - //occationaly the auth can get stuck only in host - //this especially happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - - mustEndAbs = mustEndAbs || (result.host && srcPath.length); - - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(''); - } - - if (!srcPath.length) { - result.pathname = null; - result.path = null; - } else { - result.pathname = srcPath.join('/'); - } - - //to support request.http - if (!util.isNull(result.pathname) || !util.isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.auth = relative.auth || result.auth; - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; - }; - - Url.prototype.parseHost = function() { - var host = this.host; - var port = portPattern.exec(host); - if (port) { - port = port[0]; - if (port !== ':') { - this.port = port.substr(1); - } - host = host.substr(0, host.length - port.length); - } - if (host) { this.hostname = host; } - }; - - var url$1 = { - parse: parse, - resolve: resolve, - resolveObject: resolveObject, - format: format, - Url: Url_1 - }; - - /*! - * @pixi/utils - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/utils is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * This file contains redeclared types for Node `url` and `querystring` modules. These modules - * don't provide their own typings but instead are a part of the full Node typings. The purpose of - * this file is to redeclare the required types to avoid having the whole Node types as a - * dependency. - */ - var url = { - parse: parse, - format: format, - resolve: resolve, - }; - - function assertPath(path) { - if (typeof path !== 'string') { - throw new TypeError("Path must be a string. Received " + JSON.stringify(path)); - } - } - function removeUrlParams(url) { - var re = url.split('?')[0]; - return re.split('#')[0]; - } - function escapeRegExp(string) { - return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string - } - function replaceAll(str, find, replace) { - return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); - } - // Resolves . and .. elements in a path with directory names - function normalizeStringPosix(path, allowAboveRoot) { - var res = ''; - var lastSegmentLength = 0; - var lastSlash = -1; - var dots = 0; - var code; - for (var i = 0; i <= path.length; ++i) { - if (i < path.length) { - code = path.charCodeAt(i); - } - else if (code === 47) { - break; - } - else { - code = 47; - } - if (code === 47) { - if (lastSlash === i - 1 || dots === 1) { ; } - else if (lastSlash !== i - 1 && dots === 2) { - if (res.length < 2 - || lastSegmentLength !== 2 - || res.charCodeAt(res.length - 1) !== 46 - || res.charCodeAt(res.length - 2) !== 46) { - if (res.length > 2) { - var lastSlashIndex = res.lastIndexOf('/'); - if (lastSlashIndex !== res.length - 1) { - if (lastSlashIndex === -1) { - res = ''; - lastSegmentLength = 0; - } - else { - res = res.slice(0, lastSlashIndex); - lastSegmentLength = res.length - 1 - res.lastIndexOf('/'); - } - lastSlash = i; - dots = 0; - continue; - } - } - else if (res.length === 2 || res.length === 1) { - res = ''; - lastSegmentLength = 0; - lastSlash = i; - dots = 0; - continue; - } - } - if (allowAboveRoot) { - if (res.length > 0) { - res += '/..'; - } - else { - res = '..'; - } - lastSegmentLength = 2; - } - } - else { - if (res.length > 0) { - res += "/" + path.slice(lastSlash + 1, i); - } - else { - res = path.slice(lastSlash + 1, i); - } - lastSegmentLength = i - lastSlash - 1; - } - lastSlash = i; - dots = 0; - } - else if (code === 46 && dots !== -1) { - ++dots; - } - else { - dots = -1; - } - } - return res; - } - var path = { - /** - * Converts a path to posix format. - * @param path - The path to convert to posix - */ - toPosix: function (path) { return replaceAll(path, '\\', '/'); }, - /** - * Checks if the path is a URL - * @param path - The path to check - */ - isUrl: function (path) { return (/^https?:/).test(this.toPosix(path)); }, - /** - * Checks if the path is a data URL - * @param path - The path to check - */ - isDataUrl: function (path) { - // eslint-disable-next-line max-len - return (/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i) - .test(path); - }, - /** - * Checks if the path has a protocol e.g. http:// - * This will return true for windows file paths - * @param path - The path to check - */ - hasProtocol: function (path) { return (/^[^/:]+:\//).test(this.toPosix(path)); }, - /** - * Returns the protocol of the path e.g. http://, C:/, file:/// - * @param path - The path to get the protocol from - */ - getProtocol: function (path) { - assertPath(path); - path = this.toPosix(path); - var protocol = ''; - var isFile = (/^file:\/\/\//).exec(path); - var isHttp = (/^[^/:]+:\/\//).exec(path); - var isWindows = (/^[^/:]+:\//).exec(path); - if (isFile || isHttp || isWindows) { - var arr = (isFile === null || isFile === void 0 ? void 0 : isFile[0]) || (isHttp === null || isHttp === void 0 ? void 0 : isHttp[0]) || (isWindows === null || isWindows === void 0 ? void 0 : isWindows[0]); - protocol = arr; - path = path.slice(arr.length); - } - return protocol; - }, - /** - * Converts URL to an absolute path. - * When loading from a Web Worker, we must use absolute paths. - * If the URL is already absolute we return it as is - * If it's not, we convert it - * @param url - The URL to test - * @param customBaseUrl - The base URL to use - * @param customRootUrl - The root URL to use - */ - toAbsolute: function (url, customBaseUrl, customRootUrl) { - if (this.isDataUrl(url)) - { return url; } - var baseUrl = removeUrlParams(this.toPosix(customBaseUrl !== null && customBaseUrl !== void 0 ? customBaseUrl : settings.ADAPTER.getBaseUrl())); - var rootUrl = removeUrlParams(this.toPosix(customRootUrl !== null && customRootUrl !== void 0 ? customRootUrl : this.rootname(baseUrl))); - assertPath(url); - url = this.toPosix(url); - // root relative url - if (url.startsWith('/')) { - return path.join(rootUrl, url.slice(1)); - } - var absolutePath = this.isAbsolute(url) ? url : this.join(baseUrl, url); - return absolutePath; - }, - /** - * Normalizes the given path, resolving '..' and '.' segments - * @param path - The path to normalize - */ - normalize: function (path) { - path = this.toPosix(path); - assertPath(path); - if (path.length === 0) - { return '.'; } - var protocol = ''; - var isAbsolute = path.startsWith('/'); - if (this.hasProtocol(path)) { - protocol = this.rootname(path); - path = path.slice(protocol.length); - } - var trailingSeparator = path.endsWith('/'); - // Normalize the path - path = normalizeStringPosix(path, false); - if (path.length > 0 && trailingSeparator) - { path += '/'; } - if (isAbsolute) - { return "/" + path; } - return protocol + path; - }, - /** - * Determines if path is an absolute path. - * Absolute paths can be urls, data urls, or paths on disk - * @param path - The path to test - */ - isAbsolute: function (path) { - assertPath(path); - path = this.toPosix(path); - if (this.hasProtocol(path)) - { return true; } - return path.startsWith('/'); - }, - /** - * Joins all given path segments together using the platform-specific separator as a delimiter, - * then normalizes the resulting path - * @param segments - The segments of the path to join - */ - join: function () { - var arguments$1 = arguments; - - var _a; - var segments = []; - for (var _i = 0; _i < arguments.length; _i++) { - segments[_i] = arguments$1[_i]; - } - if (segments.length === 0) { - return '.'; - } - var joined; - for (var i = 0; i < segments.length; ++i) { - var arg = segments[i]; - assertPath(arg); - if (arg.length > 0) { - if (joined === undefined) - { joined = arg; } - else { - var prevArg = (_a = segments[i - 1]) !== null && _a !== void 0 ? _a : ''; - if (this.extname(prevArg)) { - joined += "/../" + arg; - } - else { - joined += "/" + arg; - } - } - } - } - if (joined === undefined) { - return '.'; - } - return this.normalize(joined); - }, - /** - * Returns the directory name of a path - * @param path - The path to parse - */ - dirname: function (path) { - assertPath(path); - if (path.length === 0) - { return '.'; } - path = this.toPosix(path); - var code = path.charCodeAt(0); - var hasRoot = code === 47; - var end = -1; - var matchedSlash = true; - var proto = this.getProtocol(path); - var origpath = path; - path = path.slice(proto.length); - for (var i = path.length - 1; i >= 1; --i) { - code = path.charCodeAt(i); - if (code === 47) { - if (!matchedSlash) { - end = i; - break; - } - } - else { - // We saw the first non-path separator - matchedSlash = false; - } - } - // if end is -1 and its a url then we need to add the path back - // eslint-disable-next-line no-nested-ternary - if (end === -1) - { return hasRoot ? '/' : this.isUrl(origpath) ? proto + path : proto; } - if (hasRoot && end === 1) - { return '//'; } - return proto + path.slice(0, end); - }, - /** - * Returns the root of the path e.g. /, C:/, file:///, http://domain.com/ - * @param path - The path to parse - */ - rootname: function (path) { - assertPath(path); - path = this.toPosix(path); - var root = ''; - if (path.startsWith('/')) - { root = '/'; } - else { - root = this.getProtocol(path); - } - if (this.isUrl(path)) { - // need to find the first path separator - var index = path.indexOf('/', root.length); - if (index !== -1) { - root = path.slice(0, index); - } - else - { root = path; } - if (!root.endsWith('/')) - { root += '/'; } - } - return root; - }, - /** - * Returns the last portion of a path - * @param path - The path to test - * @param ext - Optional extension to remove - */ - basename: function (path, ext) { - assertPath(path); - if (ext) - { assertPath(ext); } - path = this.toPosix(path); - var start = 0; - var end = -1; - var matchedSlash = true; - var i; - if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { - if (ext.length === path.length && ext === path) - { return ''; } - var extIdx = ext.length - 1; - var firstNonSlashEnd = -1; - for (i = path.length - 1; i >= 0; --i) { - var code = path.charCodeAt(i); - if (code === 47) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - start = i + 1; - break; - } - } - else { - if (firstNonSlashEnd === -1) { - // We saw the first non-path separator, remember this index in case - // we need it if the extension ends up not matching - matchedSlash = false; - firstNonSlashEnd = i + 1; - } - if (extIdx >= 0) { - // Try to match the explicit extension - if (code === ext.charCodeAt(extIdx)) { - if (--extIdx === -1) { - // We matched the extension, so mark this as the end of our path - // component - end = i; - } - } - else { - // Extension does not match, so our result is the entire path - // component - extIdx = -1; - end = firstNonSlashEnd; - } - } - } - } - if (start === end) - { end = firstNonSlashEnd; } - else if (end === -1) - { end = path.length; } - return path.slice(start, end); - } - for (i = path.length - 1; i >= 0; --i) { - if (path.charCodeAt(i) === 47) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - start = i + 1; - break; - } - } - else if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // path component - matchedSlash = false; - end = i + 1; - } - } - if (end === -1) - { return ''; } - return path.slice(start, end); - }, - /** - * Returns the extension of the path, from the last occurrence of the . (period) character to end of string in the last - * portion of the path. If there is no . in the last portion of the path, or if there are no . characters other than - * the first character of the basename of path, an empty string is returned. - * @param path - The path to parse - */ - extname: function (path) { - assertPath(path); - path = this.toPosix(path); - var startDot = -1; - var startPart = 0; - var end = -1; - var matchedSlash = true; - // Track the state of characters (if any) we see before our first dot and - // after any path separator we find - var preDotState = 0; - for (var i = path.length - 1; i >= 0; --i) { - var code = path.charCodeAt(i); - if (code === 47) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // extension - matchedSlash = false; - end = i + 1; - } - if (code === 46) { - // If this is our first dot, mark it as the start of our extension - if (startDot === -1) - { startDot = i; } - else if (preDotState !== 1) - { preDotState = 1; } - } - else if (startDot !== -1) { - // We saw a non-dot and non-path separator before our dot, so we should - // have a good chance at having a non-empty extension - preDotState = -1; - } - } - if (startDot === -1 || end === -1 - // We saw a non-dot character immediately before the dot - || preDotState === 0 - // The (right-most) trimmed path component is exactly '..' - // eslint-disable-next-line no-mixed-operators - || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { - return ''; - } - return path.slice(startDot, end); - }, - /** - * Parses a path into an object containing the 'root', `dir`, `base`, `ext`, and `name` properties. - * @param path - The path to parse - */ - parse: function (path) { - assertPath(path); - var ret = { root: '', dir: '', base: '', ext: '', name: '' }; - if (path.length === 0) - { return ret; } - path = this.toPosix(path); - var code = path.charCodeAt(0); - var isAbsolute = this.isAbsolute(path); - var start; - ret.root = this.rootname(path); - if (isAbsolute || this.hasProtocol(path)) { - start = 1; - } - else { - start = 0; - } - var startDot = -1; - var startPart = 0; - var end = -1; - var matchedSlash = true; - var i = path.length - 1; - // Track the state of characters (if any) we see before our first dot and - // after any path separator we find - var preDotState = 0; - // Get non-dir info - for (; i >= start; --i) { - code = path.charCodeAt(i); - if (code === 47) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // extension - matchedSlash = false; - end = i + 1; - } - if (code === 46) { - // If this is our first dot, mark it as the start of our extension - if (startDot === -1) - { startDot = i; } - else if (preDotState !== 1) - { preDotState = 1; } - } - else if (startDot !== -1) { - // We saw a non-dot and non-path separator before our dot, so we should - // have a good chance at having a non-empty extension - preDotState = -1; - } - } - if (startDot === -1 || end === -1 - // We saw a non-dot character immediately before the dot - || preDotState === 0 - // The (right-most) trimmed path component is exactly '..' - // eslint-disable-next-line no-mixed-operators - || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { - if (end !== -1) { - if (startPart === 0 && isAbsolute) - { ret.base = ret.name = path.slice(1, end); } - else - { ret.base = ret.name = path.slice(startPart, end); } - } - } - else { - if (startPart === 0 && isAbsolute) { - ret.name = path.slice(1, startDot); - ret.base = path.slice(1, end); - } - else { - ret.name = path.slice(startPart, startDot); - ret.base = path.slice(startPart, end); - } - ret.ext = path.slice(startDot, end); - } - ret.dir = this.dirname(path); - return ret; - }, - sep: '/', - delimiter: ':' - }; - - /** - * The prefix that denotes a URL is for a retina asset. - * @static - * @name RETINA_PREFIX - * @memberof PIXI.settings - * @type {RegExp} - * @default /@([0-9\.]+)x/ - * @example `@2x` - */ - settings.RETINA_PREFIX = /@([0-9\.]+)x/; - /** - * Should the `failIfMajorPerformanceCaveat` flag be enabled as a context option used in the `isWebGLSupported` function. - * If set to true, a WebGL renderer can fail to be created if the browser thinks there could be performance issues when - * using WebGL. - * - * In PixiJS v6 this has changed from true to false by default, to allow WebGL to work in as many scenarios as possible. - * However, some users may have a poor experience, for example, if a user has a gpu or driver version blacklisted by the - * browser. - * - * If your application requires high performance rendering, you may wish to set this to false. - * We recommend one of two options if you decide to set this flag to false: - * - * 1: Use the `pixi.js-legacy` package, which includes a Canvas renderer as a fallback in case high performance WebGL is - * not supported. - * - * 2: Call `isWebGLSupported` (which if found in the PIXI.utils package) in your code before attempting to create a PixiJS - * renderer, and show an error message to the user if the function returns false, explaining that their device & browser - * combination does not support high performance WebGL. - * This is a much better strategy than trying to create a PixiJS renderer and finding it then fails. - * @static - * @name FAIL_IF_MAJOR_PERFORMANCE_CAVEAT - * @memberof PIXI.settings - * @type {boolean} - * @default false - */ - settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT = false; - - var saidHello = false; - var VERSION$1 = '6.5.10'; - /** - * Skips the hello message of renderers that are created after this is run. - * @function skipHello - * @memberof PIXI.utils - */ - function skipHello() { - saidHello = true; - } - /** - * Logs out the version and renderer information for this running instance of PIXI. - * If you don't want to see this message you can run `PIXI.utils.skipHello()` before - * creating your renderer. Keep in mind that doing that will forever make you a jerk face. - * @static - * @function sayHello - * @memberof PIXI.utils - * @param {string} type - The string renderer type to log. - */ - function sayHello(type) { - var _a; - if (saidHello) { - return; - } - if (settings.ADAPTER.getNavigator().userAgent.toLowerCase().indexOf('chrome') > -1) { - var args = [ - "\n %c %c %c PixiJS " + VERSION$1 + " - \u2730 " + type + " \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n", - 'background: #ff66a5; padding:5px 0;', - 'background: #ff66a5; padding:5px 0;', - 'color: #ff66a5; background: #030307; padding:5px 0;', - 'background: #ff66a5; padding:5px 0;', - 'background: #ffc3dc; padding:5px 0;', - 'background: #ff66a5; padding:5px 0;', - 'color: #ff2424; background: #fff; padding:5px 0;', - 'color: #ff2424; background: #fff; padding:5px 0;', - 'color: #ff2424; background: #fff; padding:5px 0;' ]; - (_a = globalThis.console).log.apply(_a, args); - } - else if (globalThis.console) { - globalThis.console.log("PixiJS " + VERSION$1 + " - " + type + " - http://www.pixijs.com/"); - } - saidHello = true; - } - - var supported; - /** - * Helper for checking for WebGL support. - * @memberof PIXI.utils - * @function isWebGLSupported - * @returns {boolean} Is WebGL supported. - */ - function isWebGLSupported() { - if (typeof supported === 'undefined') { - supported = (function supported() { - var contextOptions = { - stencil: true, - failIfMajorPerformanceCaveat: settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT, - }; - try { - if (!settings.ADAPTER.getWebGLRenderingContext()) { - return false; - } - var canvas = settings.ADAPTER.createCanvas(); - var gl = (canvas.getContext('webgl', contextOptions) - || canvas.getContext('experimental-webgl', contextOptions)); - var success = !!(gl && gl.getContextAttributes().stencil); - if (gl) { - var loseContext = gl.getExtension('WEBGL_lose_context'); - if (loseContext) { - loseContext.loseContext(); - } - } - gl = null; - return success; - } - catch (e) { - return false; - } - })(); - } - return supported; - } - - var aliceblue = "#f0f8ff"; - var antiquewhite = "#faebd7"; - var aqua = "#00ffff"; - var aquamarine = "#7fffd4"; - var azure = "#f0ffff"; - var beige = "#f5f5dc"; - var bisque = "#ffe4c4"; - var black = "#000000"; - var blanchedalmond = "#ffebcd"; - var blue = "#0000ff"; - var blueviolet = "#8a2be2"; - var brown = "#a52a2a"; - var burlywood = "#deb887"; - var cadetblue = "#5f9ea0"; - var chartreuse = "#7fff00"; - var chocolate = "#d2691e"; - var coral = "#ff7f50"; - var cornflowerblue = "#6495ed"; - var cornsilk = "#fff8dc"; - var crimson = "#dc143c"; - var cyan = "#00ffff"; - var darkblue = "#00008b"; - var darkcyan = "#008b8b"; - var darkgoldenrod = "#b8860b"; - var darkgray = "#a9a9a9"; - var darkgreen = "#006400"; - var darkgrey = "#a9a9a9"; - var darkkhaki = "#bdb76b"; - var darkmagenta = "#8b008b"; - var darkolivegreen = "#556b2f"; - var darkorange = "#ff8c00"; - var darkorchid = "#9932cc"; - var darkred = "#8b0000"; - var darksalmon = "#e9967a"; - var darkseagreen = "#8fbc8f"; - var darkslateblue = "#483d8b"; - var darkslategray = "#2f4f4f"; - var darkslategrey = "#2f4f4f"; - var darkturquoise = "#00ced1"; - var darkviolet = "#9400d3"; - var deeppink = "#ff1493"; - var deepskyblue = "#00bfff"; - var dimgray = "#696969"; - var dimgrey = "#696969"; - var dodgerblue = "#1e90ff"; - var firebrick = "#b22222"; - var floralwhite = "#fffaf0"; - var forestgreen = "#228b22"; - var fuchsia = "#ff00ff"; - var gainsboro = "#dcdcdc"; - var ghostwhite = "#f8f8ff"; - var goldenrod = "#daa520"; - var gold = "#ffd700"; - var gray = "#808080"; - var green = "#008000"; - var greenyellow = "#adff2f"; - var grey = "#808080"; - var honeydew = "#f0fff0"; - var hotpink = "#ff69b4"; - var indianred = "#cd5c5c"; - var indigo = "#4b0082"; - var ivory = "#fffff0"; - var khaki = "#f0e68c"; - var lavenderblush = "#fff0f5"; - var lavender = "#e6e6fa"; - var lawngreen = "#7cfc00"; - var lemonchiffon = "#fffacd"; - var lightblue = "#add8e6"; - var lightcoral = "#f08080"; - var lightcyan = "#e0ffff"; - var lightgoldenrodyellow = "#fafad2"; - var lightgray = "#d3d3d3"; - var lightgreen = "#90ee90"; - var lightgrey = "#d3d3d3"; - var lightpink = "#ffb6c1"; - var lightsalmon = "#ffa07a"; - var lightseagreen = "#20b2aa"; - var lightskyblue = "#87cefa"; - var lightslategray = "#778899"; - var lightslategrey = "#778899"; - var lightsteelblue = "#b0c4de"; - var lightyellow = "#ffffe0"; - var lime = "#00ff00"; - var limegreen = "#32cd32"; - var linen = "#faf0e6"; - var magenta = "#ff00ff"; - var maroon = "#800000"; - var mediumaquamarine = "#66cdaa"; - var mediumblue = "#0000cd"; - var mediumorchid = "#ba55d3"; - var mediumpurple = "#9370db"; - var mediumseagreen = "#3cb371"; - var mediumslateblue = "#7b68ee"; - var mediumspringgreen = "#00fa9a"; - var mediumturquoise = "#48d1cc"; - var mediumvioletred = "#c71585"; - var midnightblue = "#191970"; - var mintcream = "#f5fffa"; - var mistyrose = "#ffe4e1"; - var moccasin = "#ffe4b5"; - var navajowhite = "#ffdead"; - var navy = "#000080"; - var oldlace = "#fdf5e6"; - var olive = "#808000"; - var olivedrab = "#6b8e23"; - var orange = "#ffa500"; - var orangered = "#ff4500"; - var orchid = "#da70d6"; - var palegoldenrod = "#eee8aa"; - var palegreen = "#98fb98"; - var paleturquoise = "#afeeee"; - var palevioletred = "#db7093"; - var papayawhip = "#ffefd5"; - var peachpuff = "#ffdab9"; - var peru = "#cd853f"; - var pink = "#ffc0cb"; - var plum = "#dda0dd"; - var powderblue = "#b0e0e6"; - var purple = "#800080"; - var rebeccapurple = "#663399"; - var red = "#ff0000"; - var rosybrown = "#bc8f8f"; - var royalblue = "#4169e1"; - var saddlebrown = "#8b4513"; - var salmon = "#fa8072"; - var sandybrown = "#f4a460"; - var seagreen = "#2e8b57"; - var seashell = "#fff5ee"; - var sienna = "#a0522d"; - var silver = "#c0c0c0"; - var skyblue = "#87ceeb"; - var slateblue = "#6a5acd"; - var slategray = "#708090"; - var slategrey = "#708090"; - var snow = "#fffafa"; - var springgreen = "#00ff7f"; - var steelblue = "#4682b4"; - var tan = "#d2b48c"; - var teal = "#008080"; - var thistle = "#d8bfd8"; - var tomato = "#ff6347"; - var turquoise = "#40e0d0"; - var violet = "#ee82ee"; - var wheat = "#f5deb3"; - var white = "#ffffff"; - var whitesmoke = "#f5f5f5"; - var yellow = "#ffff00"; - var yellowgreen = "#9acd32"; - var cssColorNames = { - aliceblue: aliceblue, - antiquewhite: antiquewhite, - aqua: aqua, - aquamarine: aquamarine, - azure: azure, - beige: beige, - bisque: bisque, - black: black, - blanchedalmond: blanchedalmond, - blue: blue, - blueviolet: blueviolet, - brown: brown, - burlywood: burlywood, - cadetblue: cadetblue, - chartreuse: chartreuse, - chocolate: chocolate, - coral: coral, - cornflowerblue: cornflowerblue, - cornsilk: cornsilk, - crimson: crimson, - cyan: cyan, - darkblue: darkblue, - darkcyan: darkcyan, - darkgoldenrod: darkgoldenrod, - darkgray: darkgray, - darkgreen: darkgreen, - darkgrey: darkgrey, - darkkhaki: darkkhaki, - darkmagenta: darkmagenta, - darkolivegreen: darkolivegreen, - darkorange: darkorange, - darkorchid: darkorchid, - darkred: darkred, - darksalmon: darksalmon, - darkseagreen: darkseagreen, - darkslateblue: darkslateblue, - darkslategray: darkslategray, - darkslategrey: darkslategrey, - darkturquoise: darkturquoise, - darkviolet: darkviolet, - deeppink: deeppink, - deepskyblue: deepskyblue, - dimgray: dimgray, - dimgrey: dimgrey, - dodgerblue: dodgerblue, - firebrick: firebrick, - floralwhite: floralwhite, - forestgreen: forestgreen, - fuchsia: fuchsia, - gainsboro: gainsboro, - ghostwhite: ghostwhite, - goldenrod: goldenrod, - gold: gold, - gray: gray, - green: green, - greenyellow: greenyellow, - grey: grey, - honeydew: honeydew, - hotpink: hotpink, - indianred: indianred, - indigo: indigo, - ivory: ivory, - khaki: khaki, - lavenderblush: lavenderblush, - lavender: lavender, - lawngreen: lawngreen, - lemonchiffon: lemonchiffon, - lightblue: lightblue, - lightcoral: lightcoral, - lightcyan: lightcyan, - lightgoldenrodyellow: lightgoldenrodyellow, - lightgray: lightgray, - lightgreen: lightgreen, - lightgrey: lightgrey, - lightpink: lightpink, - lightsalmon: lightsalmon, - lightseagreen: lightseagreen, - lightskyblue: lightskyblue, - lightslategray: lightslategray, - lightslategrey: lightslategrey, - lightsteelblue: lightsteelblue, - lightyellow: lightyellow, - lime: lime, - limegreen: limegreen, - linen: linen, - magenta: magenta, - maroon: maroon, - mediumaquamarine: mediumaquamarine, - mediumblue: mediumblue, - mediumorchid: mediumorchid, - mediumpurple: mediumpurple, - mediumseagreen: mediumseagreen, - mediumslateblue: mediumslateblue, - mediumspringgreen: mediumspringgreen, - mediumturquoise: mediumturquoise, - mediumvioletred: mediumvioletred, - midnightblue: midnightblue, - mintcream: mintcream, - mistyrose: mistyrose, - moccasin: moccasin, - navajowhite: navajowhite, - navy: navy, - oldlace: oldlace, - olive: olive, - olivedrab: olivedrab, - orange: orange, - orangered: orangered, - orchid: orchid, - palegoldenrod: palegoldenrod, - palegreen: palegreen, - paleturquoise: paleturquoise, - palevioletred: palevioletred, - papayawhip: papayawhip, - peachpuff: peachpuff, - peru: peru, - pink: pink, - plum: plum, - powderblue: powderblue, - purple: purple, - rebeccapurple: rebeccapurple, - red: red, - rosybrown: rosybrown, - royalblue: royalblue, - saddlebrown: saddlebrown, - salmon: salmon, - sandybrown: sandybrown, - seagreen: seagreen, - seashell: seashell, - sienna: sienna, - silver: silver, - skyblue: skyblue, - slateblue: slateblue, - slategray: slategray, - slategrey: slategrey, - snow: snow, - springgreen: springgreen, - steelblue: steelblue, - tan: tan, - teal: teal, - thistle: thistle, - tomato: tomato, - turquoise: turquoise, - violet: violet, - wheat: wheat, - white: white, - whitesmoke: whitesmoke, - yellow: yellow, - yellowgreen: yellowgreen - }; - - /** - * Converts a hexadecimal color number to an [R, G, B] array of normalized floats (numbers from 0.0 to 1.0). - * @example - * PIXI.utils.hex2rgb(0xffffff); // returns [1, 1, 1] - * @memberof PIXI.utils - * @function hex2rgb - * @param {number} hex - The hexadecimal number to convert - * @param {number[]} [out=[]] - If supplied, this array will be used rather than returning a new one - * @returns {number[]} An array representing the [R, G, B] of the color where all values are floats. - */ - function hex2rgb(hex, out) { - if (out === void 0) { out = []; } - out[0] = ((hex >> 16) & 0xFF) / 255; - out[1] = ((hex >> 8) & 0xFF) / 255; - out[2] = (hex & 0xFF) / 255; - return out; - } - /** - * Converts a hexadecimal color number to a string. - * @example - * PIXI.utils.hex2string(0xffffff); // returns "#ffffff" - * @memberof PIXI.utils - * @function hex2string - * @param {number} hex - Number in hex (e.g., `0xffffff`) - * @returns {string} The string color (e.g., `"#ffffff"`). - */ - function hex2string(hex) { - var hexString = hex.toString(16); - hexString = '000000'.substring(0, 6 - hexString.length) + hexString; - return "#" + hexString; - } - /** - * Converts a string to a hexadecimal color number. - * It can handle: - * hex strings starting with #: "#ffffff" - * hex strings starting with 0x: "0xffffff" - * hex strings without prefix: "ffffff" - * css colors: "black" - * @example - * PIXI.utils.string2hex("#ffffff"); // returns 0xffffff, which is 16777215 as an integer - * @memberof PIXI.utils - * @function string2hex - * @param {string} string - The string color (e.g., `"#ffffff"`) - * @returns {number} Number in hexadecimal. - */ - function string2hex(string) { - if (typeof string === 'string') { - string = cssColorNames[string.toLowerCase()] || string; - if (string[0] === '#') { - string = string.slice(1); - } - } - return parseInt(string, 16); - } - /** - * Converts a color as an [R, G, B] array of normalized floats to a hexadecimal number. - * @example - * PIXI.utils.rgb2hex([1, 1, 1]); // returns 0xffffff, which is 16777215 as an integer - * @memberof PIXI.utils - * @function rgb2hex - * @param {number[]} rgb - Array of numbers where all values are normalized floats from 0.0 to 1.0. - * @returns {number} Number in hexadecimal. - */ - function rgb2hex(rgb) { - return (((rgb[0] * 255) << 16) + ((rgb[1] * 255) << 8) + (rgb[2] * 255 | 0)); - } - - /** - * Corrects PixiJS blend, takes premultiplied alpha into account - * @memberof PIXI.utils - * @function mapPremultipliedBlendModes - * @private - * @returns {Array} Mapped modes. - */ - function mapPremultipliedBlendModes() { - var pm = []; - var npm = []; - for (var i = 0; i < 32; i++) { - pm[i] = i; - npm[i] = i; - } - pm[exports.BLEND_MODES.NORMAL_NPM] = exports.BLEND_MODES.NORMAL; - pm[exports.BLEND_MODES.ADD_NPM] = exports.BLEND_MODES.ADD; - pm[exports.BLEND_MODES.SCREEN_NPM] = exports.BLEND_MODES.SCREEN; - npm[exports.BLEND_MODES.NORMAL] = exports.BLEND_MODES.NORMAL_NPM; - npm[exports.BLEND_MODES.ADD] = exports.BLEND_MODES.ADD_NPM; - npm[exports.BLEND_MODES.SCREEN] = exports.BLEND_MODES.SCREEN_NPM; - var array = []; - array.push(npm); - array.push(pm); - return array; - } - /** - * maps premultiply flag and blendMode to adjusted blendMode - * @memberof PIXI.utils - * @constant premultiplyBlendMode - * @type {Array} - */ - var premultiplyBlendMode = mapPremultipliedBlendModes(); - /** - * changes blendMode according to texture format - * @memberof PIXI.utils - * @function correctBlendMode - * @param {number} blendMode - supposed blend mode - * @param {boolean} premultiplied - whether source is premultiplied - * @returns {number} true blend mode for this texture - */ - function correctBlendMode(blendMode, premultiplied) { - return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode]; - } - /** - * combines rgb and alpha to out array - * @memberof PIXI.utils - * @function premultiplyRgba - * @param {Float32Array|number[]} rgb - input rgb - * @param {number} alpha - alpha param - * @param {Float32Array} [out] - output - * @param {boolean} [premultiply=true] - do premultiply it - * @returns {Float32Array} vec4 rgba - */ - function premultiplyRgba(rgb, alpha, out, premultiply) { - out = out || new Float32Array(4); - if (premultiply || premultiply === undefined) { - out[0] = rgb[0] * alpha; - out[1] = rgb[1] * alpha; - out[2] = rgb[2] * alpha; - } - else { - out[0] = rgb[0]; - out[1] = rgb[1]; - out[2] = rgb[2]; - } - out[3] = alpha; - return out; - } - /** - * premultiplies tint - * @memberof PIXI.utils - * @function premultiplyTint - * @param {number} tint - integer RGB - * @param {number} alpha - floating point alpha (0.0-1.0) - * @returns {number} tint multiplied by alpha - */ - function premultiplyTint(tint, alpha) { - if (alpha === 1.0) { - return (alpha * 255 << 24) + tint; - } - if (alpha === 0.0) { - return 0; - } - var R = ((tint >> 16) & 0xFF); - var G = ((tint >> 8) & 0xFF); - var B = (tint & 0xFF); - R = ((R * alpha) + 0.5) | 0; - G = ((G * alpha) + 0.5) | 0; - B = ((B * alpha) + 0.5) | 0; - return (alpha * 255 << 24) + (R << 16) + (G << 8) + B; - } - /** - * converts integer tint and float alpha to vec4 form, premultiplies by default - * @memberof PIXI.utils - * @function premultiplyTintToRgba - * @param {number} tint - input tint - * @param {number} alpha - alpha param - * @param {Float32Array} [out] - output - * @param {boolean} [premultiply=true] - do premultiply it - * @returns {Float32Array} vec4 rgba - */ - function premultiplyTintToRgba(tint, alpha, out, premultiply) { - out = out || new Float32Array(4); - out[0] = ((tint >> 16) & 0xFF) / 255.0; - out[1] = ((tint >> 8) & 0xFF) / 255.0; - out[2] = (tint & 0xFF) / 255.0; - if (premultiply || premultiply === undefined) { - out[0] *= alpha; - out[1] *= alpha; - out[2] *= alpha; - } - out[3] = alpha; - return out; - } - - /** - * Generic Mask Stack data structure - * @memberof PIXI.utils - * @function createIndicesForQuads - * @param {number} size - Number of quads - * @param {Uint16Array|Uint32Array} [outBuffer] - Buffer for output, length has to be `6 * size` - * @returns {Uint16Array|Uint32Array} - Resulting index buffer - */ - function createIndicesForQuads(size, outBuffer) { - if (outBuffer === void 0) { outBuffer = null; } - // the total number of indices in our array, there are 6 points per quad. - var totalIndices = size * 6; - outBuffer = outBuffer || new Uint16Array(totalIndices); - if (outBuffer.length !== totalIndices) { - throw new Error("Out buffer length is incorrect, got " + outBuffer.length + " and expected " + totalIndices); - } - // fill the indices with the quads to draw - for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { - outBuffer[i + 0] = j + 0; - outBuffer[i + 1] = j + 1; - outBuffer[i + 2] = j + 2; - outBuffer[i + 3] = j + 0; - outBuffer[i + 4] = j + 2; - outBuffer[i + 5] = j + 3; - } - return outBuffer; - } - - function getBufferType(array) { - if (array.BYTES_PER_ELEMENT === 4) { - if (array instanceof Float32Array) { - return 'Float32Array'; - } - else if (array instanceof Uint32Array) { - return 'Uint32Array'; - } - return 'Int32Array'; - } - else if (array.BYTES_PER_ELEMENT === 2) { - if (array instanceof Uint16Array) { - return 'Uint16Array'; - } - } - else if (array.BYTES_PER_ELEMENT === 1) { - if (array instanceof Uint8Array) { - return 'Uint8Array'; - } - } - // TODO map out the rest of the array elements! - return null; - } - - /* eslint-disable object-shorthand */ - var map$2 = { Float32Array: Float32Array, Uint32Array: Uint32Array, Int32Array: Int32Array, Uint8Array: Uint8Array }; - function interleaveTypedArrays$1(arrays, sizes) { - var outSize = 0; - var stride = 0; - var views = {}; - for (var i = 0; i < arrays.length; i++) { - stride += sizes[i]; - outSize += arrays[i].length; - } - var buffer = new ArrayBuffer(outSize * 4); - var out = null; - var littleOffset = 0; - for (var i = 0; i < arrays.length; i++) { - var size = sizes[i]; - var array = arrays[i]; - /* - @todo This is unsafe casting but consistent with how the code worked previously. Should it stay this way - or should and `getBufferTypeUnsafe` function be exposed that throws an Error if unsupported type is passed? - */ - var type = getBufferType(array); - if (!views[type]) { - views[type] = new map$2[type](buffer); - } - out = views[type]; - for (var j = 0; j < array.length; j++) { - var indexStart = ((j / size | 0) * stride) + littleOffset; - var index = j % size; - out[indexStart + index] = array[j]; - } - littleOffset += size; - } - return new Float32Array(buffer); - } - - // Taken from the bit-twiddle package - /** - * Rounds to next power of two. - * @function nextPow2 - * @memberof PIXI.utils - * @param {number} v - input value - * @returns {number} - next rounded power of two - */ - function nextPow2(v) { - v += v === 0 ? 1 : 0; - --v; - v |= v >>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v + 1; - } - /** - * Checks if a number is a power of two. - * @function isPow2 - * @memberof PIXI.utils - * @param {number} v - input value - * @returns {boolean} `true` if value is power of two - */ - function isPow2(v) { - return !(v & (v - 1)) && (!!v); - } - /** - * Computes ceil of log base 2 - * @function log2 - * @memberof PIXI.utils - * @param {number} v - input value - * @returns {number} logarithm base 2 - */ - function log2(v) { - var r = (v > 0xFFFF ? 1 : 0) << 4; - v >>>= r; - var shift = (v > 0xFF ? 1 : 0) << 3; - v >>>= shift; - r |= shift; - shift = (v > 0xF ? 1 : 0) << 2; - v >>>= shift; - r |= shift; - shift = (v > 0x3 ? 1 : 0) << 1; - v >>>= shift; - r |= shift; - return r | (v >> 1); - } - - /** - * Remove items from a javascript array without generating garbage - * @function removeItems - * @memberof PIXI.utils - * @param {Array} arr - Array to remove elements from - * @param {number} startIdx - starting index - * @param {number} removeCount - how many to remove - */ - function removeItems(arr, startIdx, removeCount) { - var length = arr.length; - var i; - if (startIdx >= length || removeCount === 0) { - return; - } - removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount); - var len = length - removeCount; - for (i = startIdx; i < len; ++i) { - arr[i] = arr[i + removeCount]; - } - arr.length = len; - } - - /** - * Returns sign of number - * @memberof PIXI.utils - * @function sign - * @param {number} n - the number to check the sign of - * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive - */ - function sign(n) { - if (n === 0) - { return 0; } - return n < 0 ? -1 : 1; - } - - var nextUid = 0; - /** - * Gets the next unique identifier - * @memberof PIXI.utils - * @function uid - * @returns {number} The next unique identifier to use. - */ - function uid() { - return ++nextUid; - } - - // A map of warning messages already fired - var warnings = {}; - /** - * Helper for warning developers about deprecated features & settings. - * A stack track for warnings is given; useful for tracking-down where - * deprecated methods/properties/classes are being used within the code. - * @memberof PIXI.utils - * @function deprecation - * @param {string} version - The version where the feature became deprecated - * @param {string} message - Message should include what is deprecated, where, and the new solution - * @param {number} [ignoreDepth=3] - The number of steps to ignore at the top of the error stack - * this is mostly to ignore internal deprecation calls. - */ - function deprecation(version, message, ignoreDepth) { - if (ignoreDepth === void 0) { ignoreDepth = 3; } - // Ignore duplicat - if (warnings[message]) { - return; - } - /* eslint-disable no-console */ - var stack = new Error().stack; - // Handle IE < 10 and Safari < 6 - if (typeof stack === 'undefined') { - console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version); - } - else { - // chop off the stack trace which includes PixiJS internal calls - stack = stack.split('\n').splice(ignoreDepth).join('\n'); - if (console.groupCollapsed) { - console.groupCollapsed('%cPixiJS Deprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', message + "\nDeprecated since v" + version); - console.warn(stack); - console.groupEnd(); - } - else { - console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version); - console.warn(stack); - } - } - /* eslint-enable no-console */ - warnings[message] = true; - } - - /** - * @todo Describe property usage - * @static - * @name ProgramCache - * @memberof PIXI.utils - * @type {object} - */ - var ProgramCache = {}; - /** - * @todo Describe property usage - * @static - * @name TextureCache - * @memberof PIXI.utils - * @type {object} - */ - var TextureCache = Object.create(null); - /** - * @todo Describe property usage - * @static - * @name BaseTextureCache - * @memberof PIXI.utils - * @type {object} - */ - var BaseTextureCache = Object.create(null); - /** - * Destroys all texture in the cache - * @memberof PIXI.utils - * @function destroyTextureCache - */ - function destroyTextureCache() { - var key; - for (key in TextureCache) { - TextureCache[key].destroy(); - } - for (key in BaseTextureCache) { - BaseTextureCache[key].destroy(); - } - } - /** - * Removes all textures from cache, but does not destroy them - * @memberof PIXI.utils - * @function clearTextureCache - */ - function clearTextureCache() { - var key; - for (key in TextureCache) { - delete TextureCache[key]; - } - for (key in BaseTextureCache) { - delete BaseTextureCache[key]; - } - } - - /** - * Creates a Canvas element of the given size to be used as a target for rendering to. - * @class - * @memberof PIXI.utils - */ - var CanvasRenderTarget = /** @class */ (function () { - /** - * @param width - the width for the newly created canvas - * @param height - the height for the newly created canvas - * @param {number} [resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the canvas - */ - function CanvasRenderTarget(width, height, resolution) { - this.canvas = settings.ADAPTER.createCanvas(); - this.context = this.canvas.getContext('2d'); - this.resolution = resolution || settings.RESOLUTION; - this.resize(width, height); - } - /** - * Clears the canvas that was created by the CanvasRenderTarget class. - * @private - */ - CanvasRenderTarget.prototype.clear = function () { - this.context.setTransform(1, 0, 0, 1, 0, 0); - this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); - }; - /** - * Resizes the canvas to the specified width and height. - * @param desiredWidth - the desired width of the canvas - * @param desiredHeight - the desired height of the canvas - */ - CanvasRenderTarget.prototype.resize = function (desiredWidth, desiredHeight) { - this.canvas.width = Math.round(desiredWidth * this.resolution); - this.canvas.height = Math.round(desiredHeight * this.resolution); - }; - /** Destroys this canvas. */ - CanvasRenderTarget.prototype.destroy = function () { - this.context = null; - this.canvas = null; - }; - Object.defineProperty(CanvasRenderTarget.prototype, "width", { - /** - * The width of the canvas buffer in pixels. - * @member {number} - */ - get: function () { - return this.canvas.width; - }, - set: function (val) { - this.canvas.width = Math.round(val); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CanvasRenderTarget.prototype, "height", { - /** - * The height of the canvas buffer in pixels. - * @member {number} - */ - get: function () { - return this.canvas.height; - }, - set: function (val) { - this.canvas.height = Math.round(val); - }, - enumerable: false, - configurable: true - }); - return CanvasRenderTarget; - }()); - - /** - * Trim transparent borders from a canvas - * @memberof PIXI.utils - * @function trimCanvas - * @param {HTMLCanvasElement} canvas - the canvas to trim - * @returns {object} Trim data - */ - function trimCanvas(canvas) { - // https://gist.github.com/remy/784508 - var width = canvas.width; - var height = canvas.height; - var context = canvas.getContext('2d', { - willReadFrequently: true, - }); - var imageData = context.getImageData(0, 0, width, height); - var pixels = imageData.data; - var len = pixels.length; - var bound = { - top: null, - left: null, - right: null, - bottom: null, - }; - var data = null; - var i; - var x; - var y; - for (i = 0; i < len; i += 4) { - if (pixels[i + 3] !== 0) { - x = (i / 4) % width; - y = ~~((i / 4) / width); - if (bound.top === null) { - bound.top = y; - } - if (bound.left === null) { - bound.left = x; - } - else if (x < bound.left) { - bound.left = x; - } - if (bound.right === null) { - bound.right = x + 1; - } - else if (bound.right < x) { - bound.right = x + 1; - } - if (bound.bottom === null) { - bound.bottom = y; - } - else if (bound.bottom < y) { - bound.bottom = y; - } - } - } - if (bound.top !== null) { - width = bound.right - bound.left; - height = bound.bottom - bound.top + 1; - data = context.getImageData(bound.left, bound.top, width, height); - } - return { - height: height, - width: width, - data: data, - }; - } - - /** - * Regexp for data URI. - * Based on: {@link https://github.com/ragingwind/data-uri-regex} - * @static - * @constant {RegExp|string} DATA_URI - * @memberof PIXI - * @example data:image/png;base64 - */ - var DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i; - - /** - * @memberof PIXI.utils - * @interface DecomposedDataUri - */ - /** - * type, eg. `image` - * @memberof PIXI.utils.DecomposedDataUri# - * @member {string} mediaType - */ - /** - * Sub type, eg. `png` - * @memberof PIXI.utils.DecomposedDataUri# - * @member {string} subType - */ - /** - * @memberof PIXI.utils.DecomposedDataUri# - * @member {string} charset - */ - /** - * Data encoding, eg. `base64` - * @memberof PIXI.utils.DecomposedDataUri# - * @member {string} encoding - */ - /** - * The actual data - * @memberof PIXI.utils.DecomposedDataUri# - * @member {string} data - */ - /** - * Split a data URI into components. Returns undefined if - * parameter `dataUri` is not a valid data URI. - * @memberof PIXI.utils - * @function decomposeDataUri - * @param {string} dataUri - the data URI to check - * @returns {PIXI.utils.DecomposedDataUri|undefined} The decomposed data uri or undefined - */ - function decomposeDataUri(dataUri) { - var dataUriMatch = DATA_URI.exec(dataUri); - if (dataUriMatch) { - return { - mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, - subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, - charset: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, - encoding: dataUriMatch[4] ? dataUriMatch[4].toLowerCase() : undefined, - data: dataUriMatch[5], - }; - } - return undefined; - } - - var tempAnchor$1; - /** - * Sets the `crossOrigin` property for this resource based on if the url - * for this resource is cross-origin. If crossOrigin was manually set, this - * function does nothing. - * Nipped from the resource loader! - * @ignore - * @param {string} url - The url to test. - * @param {object} [loc=window.location] - The location object to test against. - * @returns {string} The crossOrigin value to use (or empty string for none). - */ - function determineCrossOrigin(url$1, loc) { - if (loc === void 0) { loc = globalThis.location; } - // data: and javascript: urls are considered same-origin - if (url$1.indexOf('data:') === 0) { - return ''; - } - // default is window.location - loc = loc || globalThis.location; - if (!tempAnchor$1) { - tempAnchor$1 = document.createElement('a'); - } - // let the browser determine the full href for the url of this resource and then - // parse with the node url lib, we can't use the properties of the anchor element - // because they don't work in IE9 :( - tempAnchor$1.href = url$1; - var parsedUrl = url.parse(tempAnchor$1.href); - var samePort = (!parsedUrl.port && loc.port === '') || (parsedUrl.port === loc.port); - // if cross origin - if (parsedUrl.hostname !== loc.hostname || !samePort || parsedUrl.protocol !== loc.protocol) { - return 'anonymous'; - } - return ''; - } - - /** - * get the resolution / device pixel ratio of an asset by looking for the prefix - * used by spritesheets and image urls - * @memberof PIXI.utils - * @function getResolutionOfUrl - * @param {string} url - the image path - * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. - * @returns {number} resolution / device pixel ratio of an asset - */ - function getResolutionOfUrl(url, defaultValue) { - var resolution = settings.RETINA_PREFIX.exec(url); - if (resolution) { - return parseFloat(resolution[1]); - } - return defaultValue !== undefined ? defaultValue : 1; - } - - var utils = { - __proto__: null, - BaseTextureCache: BaseTextureCache, - CanvasRenderTarget: CanvasRenderTarget, - DATA_URI: DATA_URI, - ProgramCache: ProgramCache, - TextureCache: TextureCache, - clearTextureCache: clearTextureCache, - correctBlendMode: correctBlendMode, - createIndicesForQuads: createIndicesForQuads, - decomposeDataUri: decomposeDataUri, - deprecation: deprecation, - destroyTextureCache: destroyTextureCache, - determineCrossOrigin: determineCrossOrigin, - getBufferType: getBufferType, - getResolutionOfUrl: getResolutionOfUrl, - hex2rgb: hex2rgb, - hex2string: hex2string, - interleaveTypedArrays: interleaveTypedArrays$1, - isPow2: isPow2, - isWebGLSupported: isWebGLSupported, - log2: log2, - nextPow2: nextPow2, - path: path, - premultiplyBlendMode: premultiplyBlendMode, - premultiplyRgba: premultiplyRgba, - premultiplyTint: premultiplyTint, - premultiplyTintToRgba: premultiplyTintToRgba, - removeItems: removeItems, - rgb2hex: rgb2hex, - sayHello: sayHello, - sign: sign, - skipHello: skipHello, - string2hex: string2hex, - trimCanvas: trimCanvas, - uid: uid, - url: url, - isMobile: isMobile, - EventEmitter: eventemitter3, - earcut: earcut_1 - }; - - /*! - * @pixi/math - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/math is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - /** - * Two Pi. - * @static - * @member {number} - * @memberof PIXI - */ - var PI_2 = Math.PI * 2; - /** - * Conversion factor for converting radians to degrees. - * @static - * @member {number} RAD_TO_DEG - * @memberof PIXI - */ - var RAD_TO_DEG = 180 / Math.PI; - /** - * Conversion factor for converting degrees to radians. - * @static - * @member {number} - * @memberof PIXI - */ - var DEG_TO_RAD = Math.PI / 180; - /** - * Constants that identify shapes, mainly to prevent `instanceof` calls. - * @static - * @memberof PIXI - * @enum {number} - * @property {number} POLY Polygon - * @property {number} RECT Rectangle - * @property {number} CIRC Circle - * @property {number} ELIP Ellipse - * @property {number} RREC Rounded Rectangle - */ - exports.SHAPES = void 0; - (function (SHAPES) { - SHAPES[SHAPES["POLY"] = 0] = "POLY"; - SHAPES[SHAPES["RECT"] = 1] = "RECT"; - SHAPES[SHAPES["CIRC"] = 2] = "CIRC"; - SHAPES[SHAPES["ELIP"] = 3] = "ELIP"; - SHAPES[SHAPES["RREC"] = 4] = "RREC"; - })(exports.SHAPES || (exports.SHAPES = {})); - - /** - * The Point object represents a location in a two-dimensional coordinate system, where `x` represents - * the position on the horizontal axis and `y` represents the position on the vertical axis - * @class - * @memberof PIXI - * @implements {IPoint} - */ - var Point = /** @class */ (function () { - /** - * Creates a new `Point` - * @param {number} [x=0] - position of the point on the x axis - * @param {number} [y=0] - position of the point on the y axis - */ - function Point(x, y) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - /** Position of the point on the x axis */ - this.x = 0; - /** Position of the point on the y axis */ - this.y = 0; - this.x = x; - this.y = y; - } - /** - * Creates a clone of this point - * @returns A clone of this point - */ - Point.prototype.clone = function () { - return new Point(this.x, this.y); - }; - /** - * Copies `x` and `y` from the given point into this point - * @param p - The point to copy from - * @returns The point instance itself - */ - Point.prototype.copyFrom = function (p) { - this.set(p.x, p.y); - return this; - }; - /** - * Copies this point's x and y into the given point (`p`). - * @param p - The point to copy to. Can be any of type that is or extends `IPointData` - * @returns The point (`p`) with values updated - */ - Point.prototype.copyTo = function (p) { - p.set(this.x, this.y); - return p; - }; - /** - * Accepts another point (`p`) and returns `true` if the given point is equal to this point - * @param p - The point to check - * @returns Returns `true` if both `x` and `y` are equal - */ - Point.prototype.equals = function (p) { - return (p.x === this.x) && (p.y === this.y); - }; - /** - * Sets the point to a new `x` and `y` position. - * If `y` is omitted, both `x` and `y` will be set to `x`. - * @param {number} [x=0] - position of the point on the `x` axis - * @param {number} [y=x] - position of the point on the `y` axis - * @returns The point instance itself - */ - Point.prototype.set = function (x, y) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = x; } - this.x = x; - this.y = y; - return this; - }; - Point.prototype.toString = function () { - return "[@pixi/math:Point x=" + this.x + " y=" + this.y + "]"; - }; - return Point; - }()); - - var tempPoints$1 = [new Point(), new Point(), new Point(), new Point()]; - /** - * Size object, contains width and height - * @memberof PIXI - * @typedef {object} ISize - * @property {number} width - Width component - * @property {number} height - Height component - */ - /** - * Rectangle object is an area defined by its position, as indicated by its top-left corner - * point (x, y) and by its width and its height. - * @memberof PIXI - */ - var Rectangle = /** @class */ (function () { - /** - * @param x - The X coordinate of the upper-left corner of the rectangle - * @param y - The Y coordinate of the upper-left corner of the rectangle - * @param width - The overall width of the rectangle - * @param height - The overall height of the rectangle - */ - function Rectangle(x, y, width, height) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - if (width === void 0) { width = 0; } - if (height === void 0) { height = 0; } - this.x = Number(x); - this.y = Number(y); - this.width = Number(width); - this.height = Number(height); - this.type = exports.SHAPES.RECT; - } - Object.defineProperty(Rectangle.prototype, "left", { - /** Returns the left edge of the rectangle. */ - get: function () { - return this.x; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "right", { - /** Returns the right edge of the rectangle. */ - get: function () { - return this.x + this.width; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "top", { - /** Returns the top edge of the rectangle. */ - get: function () { - return this.y; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "bottom", { - /** Returns the bottom edge of the rectangle. */ - get: function () { - return this.y + this.height; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Rectangle, "EMPTY", { - /** A constant empty rectangle. */ - get: function () { - return new Rectangle(0, 0, 0, 0); - }, - enumerable: false, - configurable: true - }); - /** - * Creates a clone of this Rectangle - * @returns a copy of the rectangle - */ - Rectangle.prototype.clone = function () { - return new Rectangle(this.x, this.y, this.width, this.height); - }; - /** - * Copies another rectangle to this one. - * @param rectangle - The rectangle to copy from. - * @returns Returns itself. - */ - Rectangle.prototype.copyFrom = function (rectangle) { - this.x = rectangle.x; - this.y = rectangle.y; - this.width = rectangle.width; - this.height = rectangle.height; - return this; - }; - /** - * Copies this rectangle to another one. - * @param rectangle - The rectangle to copy to. - * @returns Returns given parameter. - */ - Rectangle.prototype.copyTo = function (rectangle) { - rectangle.x = this.x; - rectangle.y = this.y; - rectangle.width = this.width; - rectangle.height = this.height; - return rectangle; - }; - /** - * Checks whether the x and y coordinates given are contained within this Rectangle - * @param x - The X coordinate of the point to test - * @param y - The Y coordinate of the point to test - * @returns Whether the x/y coordinates are within this Rectangle - */ - Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { - return false; - } - if (x >= this.x && x < this.x + this.width) { - if (y >= this.y && y < this.y + this.height) { - return true; - } - } - return false; - }; - /** - * Determines whether the `other` Rectangle transformed by `transform` intersects with `this` Rectangle object. - * Returns true only if the area of the intersection is >0, this means that Rectangles - * sharing a side are not overlapping. Another side effect is that an arealess rectangle - * (width or height equal to zero) can't intersect any other rectangle. - * @param {Rectangle} other - The Rectangle to intersect with `this`. - * @param {Matrix} transform - The transformation matrix of `other`. - * @returns {boolean} A value of `true` if the transformed `other` Rectangle intersects with `this`; otherwise `false`. - */ - Rectangle.prototype.intersects = function (other, transform) { - if (!transform) { - var x0_1 = this.x < other.x ? other.x : this.x; - var x1_1 = this.right > other.right ? other.right : this.right; - if (x1_1 <= x0_1) { - return false; - } - var y0_1 = this.y < other.y ? other.y : this.y; - var y1_1 = this.bottom > other.bottom ? other.bottom : this.bottom; - return y1_1 > y0_1; - } - var x0 = this.left; - var x1 = this.right; - var y0 = this.top; - var y1 = this.bottom; - if (x1 <= x0 || y1 <= y0) { - return false; - } - var lt = tempPoints$1[0].set(other.left, other.top); - var lb = tempPoints$1[1].set(other.left, other.bottom); - var rt = tempPoints$1[2].set(other.right, other.top); - var rb = tempPoints$1[3].set(other.right, other.bottom); - if (rt.x <= lt.x || lb.y <= lt.y) { - return false; - } - var s = Math.sign((transform.a * transform.d) - (transform.b * transform.c)); - if (s === 0) { - return false; - } - transform.apply(lt, lt); - transform.apply(lb, lb); - transform.apply(rt, rt); - transform.apply(rb, rb); - if (Math.max(lt.x, lb.x, rt.x, rb.x) <= x0 - || Math.min(lt.x, lb.x, rt.x, rb.x) >= x1 - || Math.max(lt.y, lb.y, rt.y, rb.y) <= y0 - || Math.min(lt.y, lb.y, rt.y, rb.y) >= y1) { - return false; - } - var nx = s * (lb.y - lt.y); - var ny = s * (lt.x - lb.x); - var n00 = (nx * x0) + (ny * y0); - var n10 = (nx * x1) + (ny * y0); - var n01 = (nx * x0) + (ny * y1); - var n11 = (nx * x1) + (ny * y1); - if (Math.max(n00, n10, n01, n11) <= (nx * lt.x) + (ny * lt.y) - || Math.min(n00, n10, n01, n11) >= (nx * rb.x) + (ny * rb.y)) { - return false; - } - var mx = s * (lt.y - rt.y); - var my = s * (rt.x - lt.x); - var m00 = (mx * x0) + (my * y0); - var m10 = (mx * x1) + (my * y0); - var m01 = (mx * x0) + (my * y1); - var m11 = (mx * x1) + (my * y1); - if (Math.max(m00, m10, m01, m11) <= (mx * lt.x) + (my * lt.y) - || Math.min(m00, m10, m01, m11) >= (mx * rb.x) + (my * rb.y)) { - return false; - } - return true; - }; - /** - * Pads the rectangle making it grow in all directions. - * If paddingY is omitted, both paddingX and paddingY will be set to paddingX. - * @param paddingX - The horizontal padding amount. - * @param paddingY - The vertical padding amount. - * @returns Returns itself. - */ - Rectangle.prototype.pad = function (paddingX, paddingY) { - if (paddingX === void 0) { paddingX = 0; } - if (paddingY === void 0) { paddingY = paddingX; } - this.x -= paddingX; - this.y -= paddingY; - this.width += paddingX * 2; - this.height += paddingY * 2; - return this; - }; - /** - * Fits this rectangle around the passed one. - * @param rectangle - The rectangle to fit. - * @returns Returns itself. - */ - Rectangle.prototype.fit = function (rectangle) { - var x1 = Math.max(this.x, rectangle.x); - var x2 = Math.min(this.x + this.width, rectangle.x + rectangle.width); - var y1 = Math.max(this.y, rectangle.y); - var y2 = Math.min(this.y + this.height, rectangle.y + rectangle.height); - this.x = x1; - this.width = Math.max(x2 - x1, 0); - this.y = y1; - this.height = Math.max(y2 - y1, 0); - return this; - }; - /** - * Enlarges rectangle that way its corners lie on grid - * @param resolution - resolution - * @param eps - precision - * @returns Returns itself. - */ - Rectangle.prototype.ceil = function (resolution, eps) { - if (resolution === void 0) { resolution = 1; } - if (eps === void 0) { eps = 0.001; } - var x2 = Math.ceil((this.x + this.width - eps) * resolution) / resolution; - var y2 = Math.ceil((this.y + this.height - eps) * resolution) / resolution; - this.x = Math.floor((this.x + eps) * resolution) / resolution; - this.y = Math.floor((this.y + eps) * resolution) / resolution; - this.width = x2 - this.x; - this.height = y2 - this.y; - return this; - }; - /** - * Enlarges this rectangle to include the passed rectangle. - * @param rectangle - The rectangle to include. - * @returns Returns itself. - */ - Rectangle.prototype.enlarge = function (rectangle) { - var x1 = Math.min(this.x, rectangle.x); - var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); - var y1 = Math.min(this.y, rectangle.y); - var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); - this.x = x1; - this.width = x2 - x1; - this.y = y1; - this.height = y2 - y1; - return this; - }; - Rectangle.prototype.toString = function () { - return "[@pixi/math:Rectangle x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + "]"; - }; - return Rectangle; - }()); - - /** - * The Circle object is used to help draw graphics and can also be used to specify a hit area for displayObjects. - * @memberof PIXI - */ - var Circle = /** @class */ (function () { - /** - * @param x - The X coordinate of the center of this circle - * @param y - The Y coordinate of the center of this circle - * @param radius - The radius of the circle - */ - function Circle(x, y, radius) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - if (radius === void 0) { radius = 0; } - this.x = x; - this.y = y; - this.radius = radius; - this.type = exports.SHAPES.CIRC; - } - /** - * Creates a clone of this Circle instance - * @returns A copy of the Circle - */ - Circle.prototype.clone = function () { - return new Circle(this.x, this.y, this.radius); - }; - /** - * Checks whether the x and y coordinates given are contained within this circle - * @param x - The X coordinate of the point to test - * @param y - The Y coordinate of the point to test - * @returns Whether the x/y coordinates are within this Circle - */ - Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { - return false; - } - var r2 = this.radius * this.radius; - var dx = (this.x - x); - var dy = (this.y - y); - dx *= dx; - dy *= dy; - return (dx + dy <= r2); - }; - /** - * Returns the framing rectangle of the circle as a Rectangle object - * @returns The framing rectangle - */ - Circle.prototype.getBounds = function () { - return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); - }; - Circle.prototype.toString = function () { - return "[@pixi/math:Circle x=" + this.x + " y=" + this.y + " radius=" + this.radius + "]"; - }; - return Circle; - }()); - - /** - * The Ellipse object is used to help draw graphics and can also be used to specify a hit area for displayObjects. - * @memberof PIXI - */ - var Ellipse = /** @class */ (function () { - /** - * @param x - The X coordinate of the center of this ellipse - * @param y - The Y coordinate of the center of this ellipse - * @param halfWidth - The half width of this ellipse - * @param halfHeight - The half height of this ellipse - */ - function Ellipse(x, y, halfWidth, halfHeight) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - if (halfWidth === void 0) { halfWidth = 0; } - if (halfHeight === void 0) { halfHeight = 0; } - this.x = x; - this.y = y; - this.width = halfWidth; - this.height = halfHeight; - this.type = exports.SHAPES.ELIP; - } - /** - * Creates a clone of this Ellipse instance - * @returns {PIXI.Ellipse} A copy of the ellipse - */ - Ellipse.prototype.clone = function () { - return new Ellipse(this.x, this.y, this.width, this.height); - }; - /** - * Checks whether the x and y coordinates given are contained within this ellipse - * @param x - The X coordinate of the point to test - * @param y - The Y coordinate of the point to test - * @returns Whether the x/y coords are within this ellipse - */ - Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { - return false; - } - // normalize the coords to an ellipse with center 0,0 - var normx = ((x - this.x) / this.width); - var normy = ((y - this.y) / this.height); - normx *= normx; - normy *= normy; - return (normx + normy <= 1); - }; - /** - * Returns the framing rectangle of the ellipse as a Rectangle object - * @returns The framing rectangle - */ - Ellipse.prototype.getBounds = function () { - return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); - }; - Ellipse.prototype.toString = function () { - return "[@pixi/math:Ellipse x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + "]"; - }; - return Ellipse; - }()); - - /** - * A class to define a shape via user defined coordinates. - * @memberof PIXI - */ - var Polygon = /** @class */ (function () { - /** - * @param {PIXI.IPointData[]|number[]} points - This can be an array of Points - * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or - * the arguments passed can be all the points of the polygon e.g. - * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat - * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. - */ - function Polygon() { - var arguments$1 = arguments; - - var points = []; - for (var _i = 0; _i < arguments.length; _i++) { - points[_i] = arguments$1[_i]; - } - var flat = Array.isArray(points[0]) ? points[0] : points; - // if this is an array of points, convert it to a flat array of numbers - if (typeof flat[0] !== 'number') { - var p = []; - for (var i = 0, il = flat.length; i < il; i++) { - p.push(flat[i].x, flat[i].y); - } - flat = p; - } - this.points = flat; - this.type = exports.SHAPES.POLY; - this.closeStroke = true; - } - /** - * Creates a clone of this polygon. - * @returns - A copy of the polygon. - */ - Polygon.prototype.clone = function () { - var points = this.points.slice(); - var polygon = new Polygon(points); - polygon.closeStroke = this.closeStroke; - return polygon; - }; - /** - * Checks whether the x and y coordinates passed to this function are contained within this polygon. - * @param x - The X coordinate of the point to test. - * @param y - The Y coordinate of the point to test. - * @returns - Whether the x/y coordinates are within this polygon. - */ - Polygon.prototype.contains = function (x, y) { - var inside = false; - // use some raycasting to test hits - // https://github.com/substack/point-in-polygon/blob/master/index.js - var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { - var xi = this.points[i * 2]; - var yi = this.points[(i * 2) + 1]; - var xj = this.points[j * 2]; - var yj = this.points[(j * 2) + 1]; - var intersect = ((yi > y) !== (yj > y)) && (x < ((xj - xi) * ((y - yi) / (yj - yi))) + xi); - if (intersect) { - inside = !inside; - } - } - return inside; - }; - Polygon.prototype.toString = function () { - return "[@pixi/math:Polygon" - + ("closeStroke=" + this.closeStroke) - + ("points=" + this.points.reduce(function (pointsDesc, currentPoint) { return pointsDesc + ", " + currentPoint; }, '') + "]"); - }; - return Polygon; - }()); - - /** - * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its - * top-left corner point (x, y) and by its width and its height and its radius. - * @memberof PIXI - */ - var RoundedRectangle = /** @class */ (function () { - /** - * @param x - The X coordinate of the upper-left corner of the rounded rectangle - * @param y - The Y coordinate of the upper-left corner of the rounded rectangle - * @param width - The overall width of this rounded rectangle - * @param height - The overall height of this rounded rectangle - * @param radius - Controls the radius of the rounded corners - */ - function RoundedRectangle(x, y, width, height, radius) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - if (width === void 0) { width = 0; } - if (height === void 0) { height = 0; } - if (radius === void 0) { radius = 20; } - this.x = x; - this.y = y; - this.width = width; - this.height = height; - this.radius = radius; - this.type = exports.SHAPES.RREC; - } - /** - * Creates a clone of this Rounded Rectangle. - * @returns - A copy of the rounded rectangle. - */ - RoundedRectangle.prototype.clone = function () { - return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); - }; - /** - * Checks whether the x and y coordinates given are contained within this Rounded Rectangle - * @param x - The X coordinate of the point to test. - * @param y - The Y coordinate of the point to test. - * @returns - Whether the x/y coordinates are within this Rounded Rectangle. - */ - RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { - return false; - } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { - var radius = Math.max(0, Math.min(this.radius, Math.min(this.width, this.height) / 2)); - if ((y >= this.y + radius && y <= this.y + this.height - radius) - || (x >= this.x + radius && x <= this.x + this.width - radius)) { - return true; - } - var dx = x - (this.x + radius); - var dy = y - (this.y + radius); - var radius2 = radius * radius; - if ((dx * dx) + (dy * dy) <= radius2) { - return true; - } - dx = x - (this.x + this.width - radius); - if ((dx * dx) + (dy * dy) <= radius2) { - return true; - } - dy = y - (this.y + this.height - radius); - if ((dx * dx) + (dy * dy) <= radius2) { - return true; - } - dx = x - (this.x + radius); - if ((dx * dx) + (dy * dy) <= radius2) { - return true; - } - } - } - return false; - }; - RoundedRectangle.prototype.toString = function () { - return "[@pixi/math:RoundedRectangle x=" + this.x + " y=" + this.y - + ("width=" + this.width + " height=" + this.height + " radius=" + this.radius + "]"); - }; - return RoundedRectangle; - }()); - - /** - * The ObservablePoint object represents a location in a two-dimensional coordinate system, where `x` represents - * the position on the horizontal axis and `y` represents the position on the vertical axis. - * - * An `ObservablePoint` is a point that triggers a callback when the point's position is changed. - * @memberof PIXI - */ - var ObservablePoint = /** @class */ (function () { - /** - * Creates a new `ObservablePoint` - * @param cb - callback function triggered when `x` and/or `y` are changed - * @param scope - owner of callback - * @param {number} [x=0] - position of the point on the x axis - * @param {number} [y=0] - position of the point on the y axis - */ - function ObservablePoint(cb, scope, x, y) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - this._x = x; - this._y = y; - this.cb = cb; - this.scope = scope; - } - /** - * Creates a clone of this point. - * The callback and scope params can be overridden otherwise they will default - * to the clone object's values. - * @override - * @param cb - The callback function triggered when `x` and/or `y` are changed - * @param scope - The owner of the callback - * @returns a copy of this observable point - */ - ObservablePoint.prototype.clone = function (cb, scope) { - if (cb === void 0) { cb = this.cb; } - if (scope === void 0) { scope = this.scope; } - return new ObservablePoint(cb, scope, this._x, this._y); - }; - /** - * Sets the point to a new `x` and `y` position. - * If `y` is omitted, both `x` and `y` will be set to `x`. - * @param {number} [x=0] - position of the point on the x axis - * @param {number} [y=x] - position of the point on the y axis - * @returns The observable point instance itself - */ - ObservablePoint.prototype.set = function (x, y) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = x; } - if (this._x !== x || this._y !== y) { - this._x = x; - this._y = y; - this.cb.call(this.scope); - } - return this; - }; - /** - * Copies x and y from the given point (`p`) - * @param p - The point to copy from. Can be any of type that is or extends `IPointData` - * @returns The observable point instance itself - */ - ObservablePoint.prototype.copyFrom = function (p) { - if (this._x !== p.x || this._y !== p.y) { - this._x = p.x; - this._y = p.y; - this.cb.call(this.scope); - } - return this; - }; - /** - * Copies this point's x and y into that of the given point (`p`) - * @param p - The point to copy to. Can be any of type that is or extends `IPointData` - * @returns The point (`p`) with values updated - */ - ObservablePoint.prototype.copyTo = function (p) { - p.set(this._x, this._y); - return p; - }; - /** - * Accepts another point (`p`) and returns `true` if the given point is equal to this point - * @param p - The point to check - * @returns Returns `true` if both `x` and `y` are equal - */ - ObservablePoint.prototype.equals = function (p) { - return (p.x === this._x) && (p.y === this._y); - }; - ObservablePoint.prototype.toString = function () { - return "[@pixi/math:ObservablePoint x=" + 0 + " y=" + 0 + " scope=" + this.scope + "]"; - }; - Object.defineProperty(ObservablePoint.prototype, "x", { - /** Position of the observable point on the x axis. */ - get: function () { - return this._x; - }, - set: function (value) { - if (this._x !== value) { - this._x = value; - this.cb.call(this.scope); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ObservablePoint.prototype, "y", { - /** Position of the observable point on the y axis. */ - get: function () { - return this._y; - }, - set: function (value) { - if (this._y !== value) { - this._y = value; - this.cb.call(this.scope); - } - }, - enumerable: false, - configurable: true - }); - return ObservablePoint; - }()); - - /** - * The PixiJS Matrix as a class makes it a lot faster. - * - * Here is a representation of it: - * ```js - * | a | c | tx| - * | b | d | ty| - * | 0 | 0 | 1 | - * ``` - * @memberof PIXI - */ - var Matrix = /** @class */ (function () { - /** - * @param a - x scale - * @param b - y skew - * @param c - x skew - * @param d - y scale - * @param tx - x translation - * @param ty - y translation - */ - function Matrix(a, b, c, d, tx, ty) { - if (a === void 0) { a = 1; } - if (b === void 0) { b = 0; } - if (c === void 0) { c = 0; } - if (d === void 0) { d = 1; } - if (tx === void 0) { tx = 0; } - if (ty === void 0) { ty = 0; } - this.array = null; - this.a = a; - this.b = b; - this.c = c; - this.d = d; - this.tx = tx; - this.ty = ty; - } - /** - * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: - * - * a = array[0] - * b = array[1] - * c = array[3] - * d = array[4] - * tx = array[2] - * ty = array[5] - * @param array - The array that the matrix will be populated from. - */ - Matrix.prototype.fromArray = function (array) { - this.a = array[0]; - this.b = array[1]; - this.c = array[3]; - this.d = array[4]; - this.tx = array[2]; - this.ty = array[5]; - }; - /** - * Sets the matrix properties. - * @param a - Matrix component - * @param b - Matrix component - * @param c - Matrix component - * @param d - Matrix component - * @param tx - Matrix component - * @param ty - Matrix component - * @returns This matrix. Good for chaining method calls. - */ - Matrix.prototype.set = function (a, b, c, d, tx, ty) { - this.a = a; - this.b = b; - this.c = c; - this.d = d; - this.tx = tx; - this.ty = ty; - return this; - }; - /** - * Creates an array from the current Matrix object. - * @param transpose - Whether we need to transpose the matrix or not - * @param [out=new Float32Array(9)] - If provided the array will be assigned to out - * @returns The newly created array which contains the matrix - */ - Matrix.prototype.toArray = function (transpose, out) { - if (!this.array) { - this.array = new Float32Array(9); - } - var array = out || this.array; - if (transpose) { - array[0] = this.a; - array[1] = this.b; - array[2] = 0; - array[3] = this.c; - array[4] = this.d; - array[5] = 0; - array[6] = this.tx; - array[7] = this.ty; - array[8] = 1; - } - else { - array[0] = this.a; - array[1] = this.c; - array[2] = this.tx; - array[3] = this.b; - array[4] = this.d; - array[5] = this.ty; - array[6] = 0; - array[7] = 0; - array[8] = 1; - } - return array; - }; - /** - * Get a new position with the current transformation applied. - * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) - * @param pos - The origin - * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) - * @returns {PIXI.Point} The new point, transformed through this matrix - */ - Matrix.prototype.apply = function (pos, newPos) { - newPos = (newPos || new Point()); - var x = pos.x; - var y = pos.y; - newPos.x = (this.a * x) + (this.c * y) + this.tx; - newPos.y = (this.b * x) + (this.d * y) + this.ty; - return newPos; - }; - /** - * Get a new position with the inverse of the current transformation applied. - * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) - * @param pos - The origin - * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) - * @returns {PIXI.Point} The new point, inverse-transformed through this matrix - */ - Matrix.prototype.applyInverse = function (pos, newPos) { - newPos = (newPos || new Point()); - var id = 1 / ((this.a * this.d) + (this.c * -this.b)); - var x = pos.x; - var y = pos.y; - newPos.x = (this.d * id * x) + (-this.c * id * y) + (((this.ty * this.c) - (this.tx * this.d)) * id); - newPos.y = (this.a * id * y) + (-this.b * id * x) + (((-this.ty * this.a) + (this.tx * this.b)) * id); - return newPos; - }; - /** - * Translates the matrix on the x and y. - * @param x - How much to translate x by - * @param y - How much to translate y by - * @returns This matrix. Good for chaining method calls. - */ - Matrix.prototype.translate = function (x, y) { - this.tx += x; - this.ty += y; - return this; - }; - /** - * Applies a scale transformation to the matrix. - * @param x - The amount to scale horizontally - * @param y - The amount to scale vertically - * @returns This matrix. Good for chaining method calls. - */ - Matrix.prototype.scale = function (x, y) { - this.a *= x; - this.d *= y; - this.c *= x; - this.b *= y; - this.tx *= x; - this.ty *= y; - return this; - }; - /** - * Applies a rotation transformation to the matrix. - * @param angle - The angle in radians. - * @returns This matrix. Good for chaining method calls. - */ - Matrix.prototype.rotate = function (angle) { - var cos = Math.cos(angle); - var sin = Math.sin(angle); - var a1 = this.a; - var c1 = this.c; - var tx1 = this.tx; - this.a = (a1 * cos) - (this.b * sin); - this.b = (a1 * sin) + (this.b * cos); - this.c = (c1 * cos) - (this.d * sin); - this.d = (c1 * sin) + (this.d * cos); - this.tx = (tx1 * cos) - (this.ty * sin); - this.ty = (tx1 * sin) + (this.ty * cos); - return this; - }; - /** - * Appends the given Matrix to this Matrix. - * @param matrix - The matrix to append. - * @returns This matrix. Good for chaining method calls. - */ - Matrix.prototype.append = function (matrix) { - var a1 = this.a; - var b1 = this.b; - var c1 = this.c; - var d1 = this.d; - this.a = (matrix.a * a1) + (matrix.b * c1); - this.b = (matrix.a * b1) + (matrix.b * d1); - this.c = (matrix.c * a1) + (matrix.d * c1); - this.d = (matrix.c * b1) + (matrix.d * d1); - this.tx = (matrix.tx * a1) + (matrix.ty * c1) + this.tx; - this.ty = (matrix.tx * b1) + (matrix.ty * d1) + this.ty; - return this; - }; - /** - * Sets the matrix based on all the available properties - * @param x - Position on the x axis - * @param y - Position on the y axis - * @param pivotX - Pivot on the x axis - * @param pivotY - Pivot on the y axis - * @param scaleX - Scale on the x axis - * @param scaleY - Scale on the y axis - * @param rotation - Rotation in radians - * @param skewX - Skew on the x axis - * @param skewY - Skew on the y axis - * @returns This matrix. Good for chaining method calls. - */ - Matrix.prototype.setTransform = function (x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { - this.a = Math.cos(rotation + skewY) * scaleX; - this.b = Math.sin(rotation + skewY) * scaleX; - this.c = -Math.sin(rotation - skewX) * scaleY; - this.d = Math.cos(rotation - skewX) * scaleY; - this.tx = x - ((pivotX * this.a) + (pivotY * this.c)); - this.ty = y - ((pivotX * this.b) + (pivotY * this.d)); - return this; - }; - /** - * Prepends the given Matrix to this Matrix. - * @param matrix - The matrix to prepend - * @returns This matrix. Good for chaining method calls. - */ - Matrix.prototype.prepend = function (matrix) { - var tx1 = this.tx; - if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { - var a1 = this.a; - var c1 = this.c; - this.a = (a1 * matrix.a) + (this.b * matrix.c); - this.b = (a1 * matrix.b) + (this.b * matrix.d); - this.c = (c1 * matrix.a) + (this.d * matrix.c); - this.d = (c1 * matrix.b) + (this.d * matrix.d); - } - this.tx = (tx1 * matrix.a) + (this.ty * matrix.c) + matrix.tx; - this.ty = (tx1 * matrix.b) + (this.ty * matrix.d) + matrix.ty; - return this; - }; - /** - * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. - * @param transform - The transform to apply the properties to. - * @returns The transform with the newly applied properties - */ - Matrix.prototype.decompose = function (transform) { - // sort out rotation / skew.. - var a = this.a; - var b = this.b; - var c = this.c; - var d = this.d; - var pivot = transform.pivot; - var skewX = -Math.atan2(-c, d); - var skewY = Math.atan2(b, a); - var delta = Math.abs(skewX + skewY); - if (delta < 0.00001 || Math.abs(PI_2 - delta) < 0.00001) { - transform.rotation = skewY; - transform.skew.x = transform.skew.y = 0; - } - else { - transform.rotation = 0; - transform.skew.x = skewX; - transform.skew.y = skewY; - } - // next set scale - transform.scale.x = Math.sqrt((a * a) + (b * b)); - transform.scale.y = Math.sqrt((c * c) + (d * d)); - // next set position - transform.position.x = this.tx + ((pivot.x * a) + (pivot.y * c)); - transform.position.y = this.ty + ((pivot.x * b) + (pivot.y * d)); - return transform; - }; - /** - * Inverts this matrix - * @returns This matrix. Good for chaining method calls. - */ - Matrix.prototype.invert = function () { - var a1 = this.a; - var b1 = this.b; - var c1 = this.c; - var d1 = this.d; - var tx1 = this.tx; - var n = (a1 * d1) - (b1 * c1); - this.a = d1 / n; - this.b = -b1 / n; - this.c = -c1 / n; - this.d = a1 / n; - this.tx = ((c1 * this.ty) - (d1 * tx1)) / n; - this.ty = -((a1 * this.ty) - (b1 * tx1)) / n; - return this; - }; - /** - * Resets this Matrix to an identity (default) matrix. - * @returns This matrix. Good for chaining method calls. - */ - Matrix.prototype.identity = function () { - this.a = 1; - this.b = 0; - this.c = 0; - this.d = 1; - this.tx = 0; - this.ty = 0; - return this; - }; - /** - * Creates a new Matrix object with the same values as this one. - * @returns A copy of this matrix. Good for chaining method calls. - */ - Matrix.prototype.clone = function () { - var matrix = new Matrix(); - matrix.a = this.a; - matrix.b = this.b; - matrix.c = this.c; - matrix.d = this.d; - matrix.tx = this.tx; - matrix.ty = this.ty; - return matrix; - }; - /** - * Changes the values of the given matrix to be the same as the ones in this matrix - * @param matrix - The matrix to copy to. - * @returns The matrix given in parameter with its values updated. - */ - Matrix.prototype.copyTo = function (matrix) { - matrix.a = this.a; - matrix.b = this.b; - matrix.c = this.c; - matrix.d = this.d; - matrix.tx = this.tx; - matrix.ty = this.ty; - return matrix; - }; - /** - * Changes the values of the matrix to be the same as the ones in given matrix - * @param {PIXI.Matrix} matrix - The matrix to copy from. - * @returns {PIXI.Matrix} this - */ - Matrix.prototype.copyFrom = function (matrix) { - this.a = matrix.a; - this.b = matrix.b; - this.c = matrix.c; - this.d = matrix.d; - this.tx = matrix.tx; - this.ty = matrix.ty; - return this; - }; - Matrix.prototype.toString = function () { - return "[@pixi/math:Matrix a=" + this.a + " b=" + this.b + " c=" + this.c + " d=" + this.d + " tx=" + this.tx + " ty=" + this.ty + "]"; - }; - Object.defineProperty(Matrix, "IDENTITY", { - /** - * A default (identity) matrix - * @readonly - */ - get: function () { - return new Matrix(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Matrix, "TEMP_MATRIX", { - /** - * A temp matrix - * @readonly - */ - get: function () { - return new Matrix(); - }, - enumerable: false, - configurable: true - }); - return Matrix; - }()); - - // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group - /* - * Transform matrix for operation n is: - * | ux | vx | - * | uy | vy | - */ - var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; - var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; - var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; - var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; - /** - * [Cayley Table]{@link https://en.wikipedia.org/wiki/Cayley_table} - * for the composition of each rotation in the dihederal group D8. - * @type {number[][]} - * @private - */ - var rotationCayley = []; - /** - * Matrices for each `GD8Symmetry` rotation. - * @type {PIXI.Matrix[]} - * @private - */ - var rotationMatrices = []; - /* - * Alias for {@code Math.sign}. - */ - var signum = Math.sign; - /* - * Initializes `rotationCayley` and `rotationMatrices`. It is called - * only once below. - */ - function init() { - for (var i = 0; i < 16; i++) { - var row = []; - rotationCayley.push(row); - for (var j = 0; j < 16; j++) { - /* Multiplies rotation matrices i and j. */ - var _ux = signum((ux[i] * ux[j]) + (vx[i] * uy[j])); - var _uy = signum((uy[i] * ux[j]) + (vy[i] * uy[j])); - var _vx = signum((ux[i] * vx[j]) + (vx[i] * vy[j])); - var _vy = signum((uy[i] * vx[j]) + (vy[i] * vy[j])); - /* Finds rotation matrix matching the product and pushes it. */ - for (var k = 0; k < 16; k++) { - if (ux[k] === _ux && uy[k] === _uy - && vx[k] === _vx && vy[k] === _vy) { - row.push(k); - break; - } - } - } - } - for (var i = 0; i < 16; i++) { - var mat = new Matrix(); - mat.set(ux[i], uy[i], vx[i], vy[i], 0, 0); - rotationMatrices.push(mat); - } - } - init(); - /** - * @memberof PIXI - * @typedef {number} GD8Symmetry - * @see PIXI.groupD8 - */ - /** - * Implements the dihedral group D8, which is similar to - * [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}; - * D8 is the same but with diagonals, and it is used for texture - * rotations. - * - * The directions the U- and V- axes after rotation - * of an angle of `a: GD8Constant` are the vectors `(uX(a), uY(a))` - * and `(vX(a), vY(a))`. These aren't necessarily unit vectors. - * - * **Origin:**
- * This is the small part of gameofbombs.com portal system. It works. - * @see PIXI.groupD8.E - * @see PIXI.groupD8.SE - * @see PIXI.groupD8.S - * @see PIXI.groupD8.SW - * @see PIXI.groupD8.W - * @see PIXI.groupD8.NW - * @see PIXI.groupD8.N - * @see PIXI.groupD8.NE - * @author Ivan @ivanpopelyshev - * @namespace PIXI.groupD8 - * @memberof PIXI - */ - var groupD8 = { - /** - * | Rotation | Direction | - * |----------|-----------| - * | 0° | East | - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - E: 0, - /** - * | Rotation | Direction | - * |----------|-----------| - * | 45°↻ | Southeast | - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - SE: 1, - /** - * | Rotation | Direction | - * |----------|-----------| - * | 90°↻ | South | - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - S: 2, - /** - * | Rotation | Direction | - * |----------|-----------| - * | 135°↻ | Southwest | - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - SW: 3, - /** - * | Rotation | Direction | - * |----------|-----------| - * | 180° | West | - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - W: 4, - /** - * | Rotation | Direction | - * |-------------|--------------| - * | -135°/225°↻ | Northwest | - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - NW: 5, - /** - * | Rotation | Direction | - * |-------------|--------------| - * | -90°/270°↻ | North | - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - N: 6, - /** - * | Rotation | Direction | - * |-------------|--------------| - * | -45°/315°↻ | Northeast | - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - NE: 7, - /** - * Reflection about Y-axis. - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - MIRROR_VERTICAL: 8, - /** - * Reflection about the main diagonal. - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - MAIN_DIAGONAL: 10, - /** - * Reflection about X-axis. - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - MIRROR_HORIZONTAL: 12, - /** - * Reflection about reverse diagonal. - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - REVERSE_DIAGONAL: 14, - /** - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. - * @returns {PIXI.GD8Symmetry} The X-component of the U-axis - * after rotating the axes. - */ - uX: function (ind) { return ux[ind]; }, - /** - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. - * @returns {PIXI.GD8Symmetry} The Y-component of the U-axis - * after rotating the axes. - */ - uY: function (ind) { return uy[ind]; }, - /** - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. - * @returns {PIXI.GD8Symmetry} The X-component of the V-axis - * after rotating the axes. - */ - vX: function (ind) { return vx[ind]; }, - /** - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. - * @returns {PIXI.GD8Symmetry} The Y-component of the V-axis - * after rotating the axes. - */ - vY: function (ind) { return vy[ind]; }, - /** - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} rotation - symmetry whose opposite - * is needed. Only rotations have opposite symmetries while - * reflections don't. - * @returns {PIXI.GD8Symmetry} The opposite symmetry of `rotation` - */ - inv: function (rotation) { - if (rotation & 8) // true only if between 8 & 15 (reflections) - { - return rotation & 15; // or rotation % 16 - } - return (-rotation) & 7; // or (8 - rotation) % 8 - }, - /** - * Composes the two D8 operations. - * - * Taking `^` as reflection: - * - * | | E=0 | S=2 | W=4 | N=6 | E^=8 | S^=10 | W^=12 | N^=14 | - * |-------|-----|-----|-----|-----|------|-------|-------|-------| - * | E=0 | E | S | W | N | E^ | S^ | W^ | N^ | - * | S=2 | S | W | N | E | S^ | W^ | N^ | E^ | - * | W=4 | W | N | E | S | W^ | N^ | E^ | S^ | - * | N=6 | N | E | S | W | N^ | E^ | S^ | W^ | - * | E^=8 | E^ | N^ | W^ | S^ | E | N | W | S | - * | S^=10 | S^ | E^ | N^ | W^ | S | E | N | W | - * | W^=12 | W^ | S^ | E^ | N^ | W | S | E | N | - * | N^=14 | N^ | W^ | S^ | E^ | N | W | S | E | - * - * [This is a Cayley table]{@link https://en.wikipedia.org/wiki/Cayley_table} - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} rotationSecond - Second operation, which - * is the row in the above cayley table. - * @param {PIXI.GD8Symmetry} rotationFirst - First operation, which - * is the column in the above cayley table. - * @returns {PIXI.GD8Symmetry} Composed operation - */ - add: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][rotationFirst]); }, - /** - * Reverse of `add`. - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} rotationSecond - Second operation - * @param {PIXI.GD8Symmetry} rotationFirst - First operation - * @returns {PIXI.GD8Symmetry} Result - */ - sub: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][groupD8.inv(rotationFirst)]); }, - /** - * Adds 180 degrees to rotation, which is a commutative - * operation. - * @memberof PIXI.groupD8 - * @param {number} rotation - The number to rotate. - * @returns {number} Rotated number - */ - rotate180: function (rotation) { return rotation ^ 4; }, - /** - * Checks if the rotation angle is vertical, i.e. south - * or north. It doesn't work for reflections. - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} rotation - The number to check. - * @returns {boolean} Whether or not the direction is vertical - */ - isVertical: function (rotation) { return (rotation & 3) === 2; }, - /** - * Approximates the vector `V(dx,dy)` into one of the - * eight directions provided by `groupD8`. - * @memberof PIXI.groupD8 - * @param {number} dx - X-component of the vector - * @param {number} dy - Y-component of the vector - * @returns {PIXI.GD8Symmetry} Approximation of the vector into - * one of the eight symmetries. - */ - byDirection: function (dx, dy) { - if (Math.abs(dx) * 2 <= Math.abs(dy)) { - if (dy >= 0) { - return groupD8.S; - } - return groupD8.N; - } - else if (Math.abs(dy) * 2 <= Math.abs(dx)) { - if (dx > 0) { - return groupD8.E; - } - return groupD8.W; - } - else if (dy > 0) { - if (dx > 0) { - return groupD8.SE; - } - return groupD8.SW; - } - else if (dx > 0) { - return groupD8.NE; - } - return groupD8.NW; - }, - /** - * Helps sprite to compensate texture packer rotation. - * @memberof PIXI.groupD8 - * @param {PIXI.Matrix} matrix - sprite world matrix - * @param {PIXI.GD8Symmetry} rotation - The rotation factor to use. - * @param {number} tx - sprite anchoring - * @param {number} ty - sprite anchoring - */ - matrixAppendRotationInv: function (matrix, rotation, tx, ty) { - if (tx === void 0) { tx = 0; } - if (ty === void 0) { ty = 0; } - // Packer used "rotation", we use "inv(rotation)" - var mat = rotationMatrices[groupD8.inv(rotation)]; - mat.tx = tx; - mat.ty = ty; - matrix.append(mat); - }, - }; - - /** - * Transform that takes care about its versions. - * @memberof PIXI - */ - var Transform = /** @class */ (function () { - function Transform() { - this.worldTransform = new Matrix(); - this.localTransform = new Matrix(); - this.position = new ObservablePoint(this.onChange, this, 0, 0); - this.scale = new ObservablePoint(this.onChange, this, 1, 1); - this.pivot = new ObservablePoint(this.onChange, this, 0, 0); - this.skew = new ObservablePoint(this.updateSkew, this, 0, 0); - this._rotation = 0; - this._cx = 1; - this._sx = 0; - this._cy = 0; - this._sy = 1; - this._localID = 0; - this._currentLocalID = 0; - this._worldID = 0; - this._parentID = 0; - } - /** Called when a value changes. */ - Transform.prototype.onChange = function () { - this._localID++; - }; - /** Called when the skew or the rotation changes. */ - Transform.prototype.updateSkew = function () { - this._cx = Math.cos(this._rotation + this.skew.y); - this._sx = Math.sin(this._rotation + this.skew.y); - this._cy = -Math.sin(this._rotation - this.skew.x); // cos, added PI/2 - this._sy = Math.cos(this._rotation - this.skew.x); // sin, added PI/2 - this._localID++; - }; - Transform.prototype.toString = function () { - return "[@pixi/math:Transform " - + ("position=(" + this.position.x + ", " + this.position.y + ") ") - + ("rotation=" + this.rotation + " ") - + ("scale=(" + this.scale.x + ", " + this.scale.y + ") ") - + ("skew=(" + this.skew.x + ", " + this.skew.y + ") ") - + "]"; - }; - /** Updates the local transformation matrix. */ - Transform.prototype.updateLocalTransform = function () { - var lt = this.localTransform; - if (this._localID !== this._currentLocalID) { - // get the matrix values of the displayobject based on its transform properties.. - lt.a = this._cx * this.scale.x; - lt.b = this._sx * this.scale.x; - lt.c = this._cy * this.scale.y; - lt.d = this._sy * this.scale.y; - lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c)); - lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d)); - this._currentLocalID = this._localID; - // force an update.. - this._parentID = -1; - } - }; - /** - * Updates the local and the world transformation matrices. - * @param parentTransform - The parent transform - */ - Transform.prototype.updateTransform = function (parentTransform) { - var lt = this.localTransform; - if (this._localID !== this._currentLocalID) { - // get the matrix values of the displayobject based on its transform properties.. - lt.a = this._cx * this.scale.x; - lt.b = this._sx * this.scale.x; - lt.c = this._cy * this.scale.y; - lt.d = this._sy * this.scale.y; - lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c)); - lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d)); - this._currentLocalID = this._localID; - // force an update.. - this._parentID = -1; - } - if (this._parentID !== parentTransform._worldID) { - // concat the parent matrix with the objects transform. - var pt = parentTransform.worldTransform; - var wt = this.worldTransform; - wt.a = (lt.a * pt.a) + (lt.b * pt.c); - wt.b = (lt.a * pt.b) + (lt.b * pt.d); - wt.c = (lt.c * pt.a) + (lt.d * pt.c); - wt.d = (lt.c * pt.b) + (lt.d * pt.d); - wt.tx = (lt.tx * pt.a) + (lt.ty * pt.c) + pt.tx; - wt.ty = (lt.tx * pt.b) + (lt.ty * pt.d) + pt.ty; - this._parentID = parentTransform._worldID; - // update the id of the transform.. - this._worldID++; - } - }; - /** - * Decomposes a matrix and sets the transforms properties based on it. - * @param matrix - The matrix to decompose - */ - Transform.prototype.setFromMatrix = function (matrix) { - matrix.decompose(this); - this._localID++; - }; - Object.defineProperty(Transform.prototype, "rotation", { - /** The rotation of the object in radians. */ - get: function () { - return this._rotation; - }, - set: function (value) { - if (this._rotation !== value) { - this._rotation = value; - this.updateSkew(); - } - }, - enumerable: false, - configurable: true - }); - /** A default (identity) transform. */ - Transform.IDENTITY = new Transform(); - return Transform; - }()); - - /*! - * @pixi/display - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/display is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Sets the default value for the container property 'sortableChildren'. - * If set to true, the container will sort its children by zIndex value - * when updateTransform() is called, or manually if sortChildren() is called. - * - * This actually changes the order of elements in the array, so should be treated - * as a basic solution that is not performant compared to other solutions, - * such as @link https://github.com/pixijs/pixi-display - * - * Also be aware of that this may not work nicely with the addChildAt() function, - * as the zIndex sorting may cause the child to automatically sorted to another position. - * @static - * @constant - * @name SORTABLE_CHILDREN - * @memberof PIXI.settings - * @type {boolean} - * @default false - */ - settings.SORTABLE_CHILDREN = false; - - /** - * 'Builder' pattern for bounds rectangles. - * - * This could be called an Axis-Aligned Bounding Box. - * It is not an actual shape. It is a mutable thing; no 'EMPTY' or those kind of problems. - * @memberof PIXI - */ - var Bounds = /** @class */ (function () { - function Bounds() { - this.minX = Infinity; - this.minY = Infinity; - this.maxX = -Infinity; - this.maxY = -Infinity; - this.rect = null; - this.updateID = -1; - } - /** - * Checks if bounds are empty. - * @returns - True if empty. - */ - Bounds.prototype.isEmpty = function () { - return this.minX > this.maxX || this.minY > this.maxY; - }; - /** Clears the bounds and resets. */ - Bounds.prototype.clear = function () { - this.minX = Infinity; - this.minY = Infinity; - this.maxX = -Infinity; - this.maxY = -Infinity; - }; - /** - * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle - * It is not guaranteed that it will return tempRect - * @param rect - Temporary object will be used if AABB is not empty - * @returns - A rectangle of the bounds - */ - Bounds.prototype.getRectangle = function (rect) { - if (this.minX > this.maxX || this.minY > this.maxY) { - return Rectangle.EMPTY; - } - rect = rect || new Rectangle(0, 0, 1, 1); - rect.x = this.minX; - rect.y = this.minY; - rect.width = this.maxX - this.minX; - rect.height = this.maxY - this.minY; - return rect; - }; - /** - * This function should be inlined when its possible. - * @param point - The point to add. - */ - Bounds.prototype.addPoint = function (point) { - this.minX = Math.min(this.minX, point.x); - this.maxX = Math.max(this.maxX, point.x); - this.minY = Math.min(this.minY, point.y); - this.maxY = Math.max(this.maxY, point.y); - }; - /** - * Adds a point, after transformed. This should be inlined when its possible. - * @param matrix - * @param point - */ - Bounds.prototype.addPointMatrix = function (matrix, point) { - var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d, tx = matrix.tx, ty = matrix.ty; - var x = (a * point.x) + (c * point.y) + tx; - var y = (b * point.x) + (d * point.y) + ty; - this.minX = Math.min(this.minX, x); - this.maxX = Math.max(this.maxX, x); - this.minY = Math.min(this.minY, y); - this.maxY = Math.max(this.maxY, y); - }; - /** - * Adds a quad, not transformed - * @param vertices - The verts to add. - */ - Bounds.prototype.addQuad = function (vertices) { - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - var x = vertices[0]; - var y = vertices[1]; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - x = vertices[2]; - y = vertices[3]; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - x = vertices[4]; - y = vertices[5]; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - x = vertices[6]; - y = vertices[7]; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - this.minX = minX; - this.minY = minY; - this.maxX = maxX; - this.maxY = maxY; - }; - /** - * Adds sprite frame, transformed. - * @param transform - transform to apply - * @param x0 - left X of frame - * @param y0 - top Y of frame - * @param x1 - right X of frame - * @param y1 - bottom Y of frame - */ - Bounds.prototype.addFrame = function (transform, x0, y0, x1, y1) { - this.addFrameMatrix(transform.worldTransform, x0, y0, x1, y1); - }; - /** - * Adds sprite frame, multiplied by matrix - * @param matrix - matrix to apply - * @param x0 - left X of frame - * @param y0 - top Y of frame - * @param x1 - right X of frame - * @param y1 - bottom Y of frame - */ - Bounds.prototype.addFrameMatrix = function (matrix, x0, y0, x1, y1) { - var a = matrix.a; - var b = matrix.b; - var c = matrix.c; - var d = matrix.d; - var tx = matrix.tx; - var ty = matrix.ty; - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - var x = (a * x0) + (c * y0) + tx; - var y = (b * x0) + (d * y0) + ty; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - x = (a * x1) + (c * y0) + tx; - y = (b * x1) + (d * y0) + ty; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - x = (a * x0) + (c * y1) + tx; - y = (b * x0) + (d * y1) + ty; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - x = (a * x1) + (c * y1) + tx; - y = (b * x1) + (d * y1) + ty; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - this.minX = minX; - this.minY = minY; - this.maxX = maxX; - this.maxY = maxY; - }; - /** - * Adds screen vertices from array - * @param vertexData - calculated vertices - * @param beginOffset - begin offset - * @param endOffset - end offset, excluded - */ - Bounds.prototype.addVertexData = function (vertexData, beginOffset, endOffset) { - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - for (var i = beginOffset; i < endOffset; i += 2) { - var x = vertexData[i]; - var y = vertexData[i + 1]; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - } - this.minX = minX; - this.minY = minY; - this.maxX = maxX; - this.maxY = maxY; - }; - /** - * Add an array of mesh vertices - * @param transform - mesh transform - * @param vertices - mesh coordinates in array - * @param beginOffset - begin offset - * @param endOffset - end offset, excluded - */ - Bounds.prototype.addVertices = function (transform, vertices, beginOffset, endOffset) { - this.addVerticesMatrix(transform.worldTransform, vertices, beginOffset, endOffset); - }; - /** - * Add an array of mesh vertices. - * @param matrix - mesh matrix - * @param vertices - mesh coordinates in array - * @param beginOffset - begin offset - * @param endOffset - end offset, excluded - * @param padX - x padding - * @param padY - y padding - */ - Bounds.prototype.addVerticesMatrix = function (matrix, vertices, beginOffset, endOffset, padX, padY) { - if (padX === void 0) { padX = 0; } - if (padY === void 0) { padY = padX; } - var a = matrix.a; - var b = matrix.b; - var c = matrix.c; - var d = matrix.d; - var tx = matrix.tx; - var ty = matrix.ty; - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - for (var i = beginOffset; i < endOffset; i += 2) { - var rawX = vertices[i]; - var rawY = vertices[i + 1]; - var x = (a * rawX) + (c * rawY) + tx; - var y = (d * rawY) + (b * rawX) + ty; - minX = Math.min(minX, x - padX); - maxX = Math.max(maxX, x + padX); - minY = Math.min(minY, y - padY); - maxY = Math.max(maxY, y + padY); - } - this.minX = minX; - this.minY = minY; - this.maxX = maxX; - this.maxY = maxY; - }; - /** - * Adds other {@link Bounds}. - * @param bounds - The Bounds to be added - */ - Bounds.prototype.addBounds = function (bounds) { - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - this.minX = bounds.minX < minX ? bounds.minX : minX; - this.minY = bounds.minY < minY ? bounds.minY : minY; - this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; - this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; - }; - /** - * Adds other Bounds, masked with Bounds. - * @param bounds - The Bounds to be added. - * @param mask - TODO - */ - Bounds.prototype.addBoundsMask = function (bounds, mask) { - var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; - var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; - var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; - var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; - if (_minX <= _maxX && _minY <= _maxY) { - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - this.minX = _minX < minX ? _minX : minX; - this.minY = _minY < minY ? _minY : minY; - this.maxX = _maxX > maxX ? _maxX : maxX; - this.maxY = _maxY > maxY ? _maxY : maxY; - } - }; - /** - * Adds other Bounds, multiplied by matrix. Bounds shouldn't be empty. - * @param bounds - other bounds - * @param matrix - multiplicator - */ - Bounds.prototype.addBoundsMatrix = function (bounds, matrix) { - this.addFrameMatrix(matrix, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY); - }; - /** - * Adds other Bounds, masked with Rectangle. - * @param bounds - TODO - * @param area - TODO - */ - Bounds.prototype.addBoundsArea = function (bounds, area) { - var _minX = bounds.minX > area.x ? bounds.minX : area.x; - var _minY = bounds.minY > area.y ? bounds.minY : area.y; - var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : (area.x + area.width); - var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : (area.y + area.height); - if (_minX <= _maxX && _minY <= _maxY) { - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - this.minX = _minX < minX ? _minX : minX; - this.minY = _minY < minY ? _minY : minY; - this.maxX = _maxX > maxX ? _maxX : maxX; - this.maxY = _maxY > maxY ? _maxY : maxY; - } - }; - /** - * Pads bounds object, making it grow in all directions. - * If paddingY is omitted, both paddingX and paddingY will be set to paddingX. - * @param paddingX - The horizontal padding amount. - * @param paddingY - The vertical padding amount. - */ - Bounds.prototype.pad = function (paddingX, paddingY) { - if (paddingX === void 0) { paddingX = 0; } - if (paddingY === void 0) { paddingY = paddingX; } - if (!this.isEmpty()) { - this.minX -= paddingX; - this.maxX += paddingX; - this.minY -= paddingY; - this.maxY += paddingY; - } - }; - /** - * Adds padded frame. (x0, y0) should be strictly less than (x1, y1) - * @param x0 - left X of frame - * @param y0 - top Y of frame - * @param x1 - right X of frame - * @param y1 - bottom Y of frame - * @param padX - padding X - * @param padY - padding Y - */ - Bounds.prototype.addFramePad = function (x0, y0, x1, y1, padX, padY) { - x0 -= padX; - y0 -= padY; - x1 += padX; - y1 += padY; - this.minX = this.minX < x0 ? this.minX : x0; - this.maxX = this.maxX > x1 ? this.maxX : x1; - this.minY = this.minY < y0 ? this.minY : y0; - this.maxY = this.maxY > y1 ? this.maxY : y1; - }; - return Bounds; - }()); - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$j = function(d, b) { - extendStatics$j = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$j(d, b); - }; - - function __extends$j(d, b) { - extendStatics$j(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** - * The base class for all objects that are rendered on the screen. - * - * This is an abstract class and can not be used on its own; rather it should be extended. - * - * ## Display objects implemented in PixiJS - * - * | Display Object | Description | - * | ------------------------------- | --------------------------------------------------------------------- | - * | {@link PIXI.Container} | Adds support for `children` to DisplayObject | - * | {@link PIXI.Graphics} | Shape-drawing display object similar to the Canvas API | - * | {@link PIXI.Sprite} | Draws textures (i.e. images) | - * | {@link PIXI.Text} | Draws text using the Canvas API internally | - * | {@link PIXI.BitmapText} | More scaleable solution for text rendering, reusing glyph textures | - * | {@link PIXI.TilingSprite} | Draws textures/images in a tiled fashion | - * | {@link PIXI.AnimatedSprite} | Draws an animation of multiple images | - * | {@link PIXI.Mesh} | Provides a lower-level API for drawing meshes with custom data | - * | {@link PIXI.NineSlicePlane} | Mesh-related | - * | {@link PIXI.SimpleMesh} | v4-compatible mesh | - * | {@link PIXI.SimplePlane} | Mesh-related | - * | {@link PIXI.SimpleRope} | Mesh-related | - * - * ## Transforms - * - * The [transform]{@link DisplayObject#transform} of a display object describes the projection from its - * local coordinate space to its parent's local coordinate space. The following properties are derived - * from the transform: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
PropertyDescription
[pivot]{@link PIXI.DisplayObject#pivot} - * Invariant under rotation, scaling, and skewing. The projection of into the parent's space of the pivot - * is equal to position, regardless of the other three transformations. In other words, It is the center of - * rotation, scaling, and skewing. - *
[position]{@link PIXI.DisplayObject#position} - * Translation. This is the position of the [pivot]{@link PIXI.DisplayObject#pivot} in the parent's local - * space. The default value of the pivot is the origin (0,0). If the top-left corner of your display object - * is (0,0) in its local space, then the position will be its top-left corner in the parent's local space. - *
[scale]{@link PIXI.DisplayObject#scale} - * Scaling. This will stretch (or compress) the display object's projection. The scale factors are along the - * local coordinate axes. In other words, the display object is scaled before rotated or skewed. The center - * of scaling is the [pivot]{@link PIXI.DisplayObject#pivot}. - *
[rotation]{@link PIXI.DisplayObject#rotation} - * Rotation. This will rotate the display object's projection by this angle (in radians). - *
[skew]{@link PIXI.DisplayObject#skew} - *

Skewing. This can be used to deform a rectangular display object into a parallelogram.

- *

- * In PixiJS, skew has a slightly different behaviour than the conventional meaning. It can be - * thought of the net rotation applied to the coordinate axes (separately). For example, if "skew.x" is - * ⍺ and "skew.y" is β, then the line x = 0 will be rotated by ⍺ (y = -x*cot⍺) and the line y = 0 will be - * rotated by β (y = x*tanβ). A line y = x*tanϴ (i.e. a line at angle ϴ to the x-axis in local-space) will - * be rotated by an angle between ⍺ and β. - *

- *

- * It can be observed that if skew is applied equally to both axes, then it will be equivalent to applying - * a rotation. Indeed, if "skew.x" = -ϴ and "skew.y" = ϴ, it will produce an equivalent of "rotation" = ϴ. - *

- *

- * Another quite interesting observation is that "skew.x", "skew.y", rotation are communtative operations. Indeed, - * because rotation is essentially a careful combination of the two. - *

- *
angleRotation. This is an alias for [rotation]{@link PIXI.DisplayObject#rotation}, but in degrees.
xTranslation. This is an alias for position.x!
yTranslation. This is an alias for position.y!
width - * Implemented in [Container]{@link PIXI.Container}. Scaling. The width property calculates scale.x by dividing - * the "requested" width by the local bounding box width. It is indirectly an abstraction over scale.x, and there - * is no concept of user-defined width. - *
height - * Implemented in [Container]{@link PIXI.Container}. Scaling. The height property calculates scale.y by dividing - * the "requested" height by the local bounding box height. It is indirectly an abstraction over scale.y, and there - * is no concept of user-defined height. - *
- * - * ## Bounds - * - * The bounds of a display object is defined by the minimum axis-aligned rectangle in world space that can fit - * around it. The abstract `calculateBounds` method is responsible for providing it (and it should use the - * `worldTransform` to calculate in world space). - * - * There are a few additional types of bounding boxes: - * - * | Bounds | Description | - * | --------------------- | ---------------------------------------------------------------------------------------- | - * | World Bounds | This is synonymous is the regular bounds described above. See `getBounds()`. | - * | Local Bounds | This the axis-aligned bounding box in the parent's local space. See `getLocalBounds()`. | - * | Render Bounds | The bounds, but including extra rendering effects like filter padding. | - * | Projected Bounds | The bounds of the projected display object onto the screen. Usually equals world bounds. | - * | Relative Bounds | The bounds of a display object when projected onto a ancestor's (or parent's) space. | - * | Natural Bounds | The bounds of an object in its own local space (not parent's space, like in local bounds)| - * | Content Bounds | The natural bounds when excluding all children of a `Container`. | - * - * ### calculateBounds - * - * [Container]{@link Container} already implements `calculateBounds` in a manner that includes children. - * - * But for a non-Container display object, the `calculateBounds` method must be overridden in order for `getBounds` and - * `getLocalBounds` to work. This method must write the bounds into `this._bounds`. - * - * Generally, the following technique works for most simple cases: take the list of points - * forming the "hull" of the object (i.e. outline of the object's shape), and then add them - * using {@link PIXI.Bounds#addPointMatrix}. - * - * ```js - * calculateBounds(): void - * { - * const points = [...]; - * - * for (let i = 0, j = points.length; i < j; i++) - * { - * this._bounds.addPointMatrix(this.worldTransform, points[i]); - * } - * } - * ``` - * - * You can optimize this for a large number of points by using {@link PIXI.Bounds#addVerticesMatrix} to pass them - * in one array together. - * - * ## Alpha - * - * This alpha sets a display object's **relative opacity** w.r.t its parent. For example, if the alpha of a display - * object is 0.5 and its parent's alpha is 0.5, then it will be rendered with 25% opacity (assuming alpha is not - * applied on any ancestor further up the chain). - * - * The alpha with which the display object will be rendered is called the [worldAlpha]{@link PIXI.DisplayObject#worldAlpha}. - * - * ## Renderable vs Visible - * - * The `renderable` and `visible` properties can be used to prevent a display object from being rendered to the - * screen. However, there is a subtle difference between the two. When using `renderable`, the transforms of the display - * object (and its children subtree) will continue to be calculated. When using `visible`, the transforms will not - * be calculated. - * - * It is recommended that applications use the `renderable` property for culling. See - * [@pixi-essentials/cull]{@link https://www.npmjs.com/package/@pixi-essentials/cull} or - * [pixi-cull]{@link https://www.npmjs.com/package/pixi-cull} for more details. - * - * Otherwise, to prevent an object from rendering in the general-purpose sense - `visible` is the property to use. This - * one is also better in terms of performance. - * @memberof PIXI - */ - var DisplayObject = /** @class */ (function (_super) { - __extends$j(DisplayObject, _super); - function DisplayObject() { - var _this = _super.call(this) || this; - _this.tempDisplayObjectParent = null; - // TODO: need to create Transform from factory - _this.transform = new Transform(); - _this.alpha = 1; - _this.visible = true; - _this.renderable = true; - _this.cullable = false; - _this.cullArea = null; - _this.parent = null; - _this.worldAlpha = 1; - _this._lastSortedIndex = 0; - _this._zIndex = 0; - _this.filterArea = null; - _this.filters = null; - _this._enabledFilters = null; - _this._bounds = new Bounds(); - _this._localBounds = null; - _this._boundsID = 0; - _this._boundsRect = null; - _this._localBoundsRect = null; - _this._mask = null; - _this._maskRefCount = 0; - _this._destroyed = false; - _this.isSprite = false; - _this.isMask = false; - return _this; - } - /** - * Mixes all enumerable properties and methods from a source object to DisplayObject. - * @param source - The source of properties and methods to mix in. - */ - DisplayObject.mixin = function (source) { - // in ES8/ES2017, this would be really easy: - // Object.defineProperties(DisplayObject.prototype, Object.getOwnPropertyDescriptors(source)); - // get all the enumerable property keys - var keys = Object.keys(source); - // loop through properties - for (var i = 0; i < keys.length; ++i) { - var propertyName = keys[i]; - // Set the property using the property descriptor - this works for accessors and normal value properties - Object.defineProperty(DisplayObject.prototype, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); - } - }; - Object.defineProperty(DisplayObject.prototype, "destroyed", { - /** - * Fired when this DisplayObject is added to a Container. - * @instance - * @event added - * @param {PIXI.Container} container - The container added to. - */ - /** - * Fired when this DisplayObject is removed from a Container. - * @instance - * @event removed - * @param {PIXI.Container} container - The container removed from. - */ - /** - * Fired when this DisplayObject is destroyed. This event is emitted once - * destroy is finished. - * @instance - * @event destroyed - */ - /** Readonly flag for destroyed display objects. */ - get: function () { - return this._destroyed; - }, - enumerable: false, - configurable: true - }); - /** Recursively updates transform of all objects from the root to this one internal function for toLocal() */ - DisplayObject.prototype._recursivePostUpdateTransform = function () { - if (this.parent) { - this.parent._recursivePostUpdateTransform(); - this.transform.updateTransform(this.parent.transform); - } - else { - this.transform.updateTransform(this._tempDisplayObjectParent.transform); - } - }; - /** Updates the object transform for rendering. TODO - Optimization pass! */ - DisplayObject.prototype.updateTransform = function () { - this._boundsID++; - this.transform.updateTransform(this.parent.transform); - // multiply the alphas.. - this.worldAlpha = this.alpha * this.parent.worldAlpha; - }; - /** - * Calculates and returns the (world) bounds of the display object as a [Rectangle]{@link PIXI.Rectangle}. - * - * This method is expensive on containers with a large subtree (like the stage). This is because the bounds - * of a container depend on its children's bounds, which recursively causes all bounds in the subtree to - * be recalculated. The upside, however, is that calling `getBounds` once on a container will indeed update - * the bounds of all children (the whole subtree, in fact). This side effect should be exploited by using - * `displayObject._bounds.getRectangle()` when traversing through all the bounds in a scene graph. Otherwise, - * calling `getBounds` on each object in a subtree will cause the total cost to increase quadratically as - * its height increases. - * - * The transforms of all objects in a container's **subtree** and of all **ancestors** are updated. - * The world bounds of all display objects in a container's **subtree** will also be recalculated. - * - * The `_bounds` object stores the last calculation of the bounds. You can use to entirely skip bounds - * calculation if needed. - * - * ```js - * const lastCalculatedBounds = displayObject._bounds.getRectangle(optionalRect); - * ``` - * - * Do know that usage of `getLocalBounds` can corrupt the `_bounds` of children (the whole subtree, actually). This - * is a known issue that has not been solved. See [getLocalBounds]{@link PIXI.DisplayObject#getLocalBounds} for more - * details. - * - * `getBounds` should be called with `skipUpdate` equal to `true` in a render() call. This is because the transforms - * are guaranteed to be update-to-date. In fact, recalculating inside a render() call may cause corruption in certain - * cases. - * @param skipUpdate - Setting to `true` will stop the transforms of the scene graph from - * being updated. This means the calculation returned MAY be out of date BUT will give you a - * nice performance boost. - * @param rect - Optional rectangle to store the result of the bounds calculation. - * @returns - The minimum axis-aligned rectangle in world space that fits around this object. - */ - DisplayObject.prototype.getBounds = function (skipUpdate, rect) { - if (!skipUpdate) { - if (!this.parent) { - this.parent = this._tempDisplayObjectParent; - this.updateTransform(); - this.parent = null; - } - else { - this._recursivePostUpdateTransform(); - this.updateTransform(); - } - } - if (this._bounds.updateID !== this._boundsID) { - this.calculateBounds(); - this._bounds.updateID = this._boundsID; - } - if (!rect) { - if (!this._boundsRect) { - this._boundsRect = new Rectangle(); - } - rect = this._boundsRect; - } - return this._bounds.getRectangle(rect); - }; - /** - * Retrieves the local bounds of the displayObject as a rectangle object. - * @param rect - Optional rectangle to store the result of the bounds calculation. - * @returns - The rectangular bounding area. - */ - DisplayObject.prototype.getLocalBounds = function (rect) { - if (!rect) { - if (!this._localBoundsRect) { - this._localBoundsRect = new Rectangle(); - } - rect = this._localBoundsRect; - } - if (!this._localBounds) { - this._localBounds = new Bounds(); - } - var transformRef = this.transform; - var parentRef = this.parent; - this.parent = null; - this.transform = this._tempDisplayObjectParent.transform; - var worldBounds = this._bounds; - var worldBoundsID = this._boundsID; - this._bounds = this._localBounds; - var bounds = this.getBounds(false, rect); - this.parent = parentRef; - this.transform = transformRef; - this._bounds = worldBounds; - this._bounds.updateID += this._boundsID - worldBoundsID; // reflect side-effects - return bounds; - }; - /** - * Calculates the global position of the display object. - * @param position - The world origin to calculate from. - * @param point - A Point object in which to store the value, optional - * (otherwise will create a new Point). - * @param skipUpdate - Should we skip the update transform. - * @returns - A point object representing the position of this object. - */ - DisplayObject.prototype.toGlobal = function (position, point, skipUpdate) { - if (skipUpdate === void 0) { skipUpdate = false; } - if (!skipUpdate) { - this._recursivePostUpdateTransform(); - // this parent check is for just in case the item is a root object. - // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly - // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) - if (!this.parent) { - this.parent = this._tempDisplayObjectParent; - this.displayObjectUpdateTransform(); - this.parent = null; - } - else { - this.displayObjectUpdateTransform(); - } - } - // don't need to update the lot - return this.worldTransform.apply(position, point); - }; - /** - * Calculates the local position of the display object relative to another point. - * @param position - The world origin to calculate from. - * @param from - The DisplayObject to calculate the global position from. - * @param point - A Point object in which to store the value, optional - * (otherwise will create a new Point). - * @param skipUpdate - Should we skip the update transform - * @returns - A point object representing the position of this object - */ - DisplayObject.prototype.toLocal = function (position, from, point, skipUpdate) { - if (from) { - position = from.toGlobal(position, point, skipUpdate); - } - if (!skipUpdate) { - this._recursivePostUpdateTransform(); - // this parent check is for just in case the item is a root object. - // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly - // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) - if (!this.parent) { - this.parent = this._tempDisplayObjectParent; - this.displayObjectUpdateTransform(); - this.parent = null; - } - else { - this.displayObjectUpdateTransform(); - } - } - // simply apply the matrix.. - return this.worldTransform.applyInverse(position, point); - }; - /** - * Set the parent Container of this DisplayObject. - * @param container - The Container to add this DisplayObject to. - * @returns - The Container that this DisplayObject was added to. - */ - DisplayObject.prototype.setParent = function (container) { - if (!container || !container.addChild) { - throw new Error('setParent: Argument must be a Container'); - } - container.addChild(this); - return container; - }; - /** - * Convenience function to set the position, scale, skew and pivot at once. - * @param x - The X position - * @param y - The Y position - * @param scaleX - The X scale value - * @param scaleY - The Y scale value - * @param rotation - The rotation - * @param skewX - The X skew value - * @param skewY - The Y skew value - * @param pivotX - The X pivot value - * @param pivotY - The Y pivot value - * @returns - The DisplayObject instance - */ - DisplayObject.prototype.setTransform = function (x, y, scaleX, scaleY, rotation, skewX, skewY, pivotX, pivotY) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - if (scaleX === void 0) { scaleX = 1; } - if (scaleY === void 0) { scaleY = 1; } - if (rotation === void 0) { rotation = 0; } - if (skewX === void 0) { skewX = 0; } - if (skewY === void 0) { skewY = 0; } - if (pivotX === void 0) { pivotX = 0; } - if (pivotY === void 0) { pivotY = 0; } - this.position.x = x; - this.position.y = y; - this.scale.x = !scaleX ? 1 : scaleX; - this.scale.y = !scaleY ? 1 : scaleY; - this.rotation = rotation; - this.skew.x = skewX; - this.skew.y = skewY; - this.pivot.x = pivotX; - this.pivot.y = pivotY; - return this; - }; - /** - * Base destroy method for generic display objects. This will automatically - * remove the display object from its parent Container as well as remove - * all current event listeners and internal references. Do not use a DisplayObject - * after calling `destroy()`. - * @param _options - */ - DisplayObject.prototype.destroy = function (_options) { - if (this.parent) { - this.parent.removeChild(this); - } - this._destroyed = true; - this.transform = null; - this.parent = null; - this._bounds = null; - this.mask = null; - this.cullArea = null; - this.filters = null; - this.filterArea = null; - this.hitArea = null; - this.interactive = false; - this.interactiveChildren = false; - this.emit('destroyed'); - this.removeAllListeners(); - }; - Object.defineProperty(DisplayObject.prototype, "_tempDisplayObjectParent", { - /** - * @protected - * @member {PIXI.Container} - */ - get: function () { - if (this.tempDisplayObjectParent === null) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - this.tempDisplayObjectParent = new TemporaryDisplayObject(); - } - return this.tempDisplayObjectParent; - }, - enumerable: false, - configurable: true - }); - /** - * Used in Renderer, cacheAsBitmap and other places where you call an `updateTransform` on root - * - * ``` - * const cacheParent = elem.enableTempParent(); - * elem.updateTransform(); - * elem.disableTempParent(cacheParent); - * ``` - * @returns - current parent - */ - DisplayObject.prototype.enableTempParent = function () { - var myParent = this.parent; - this.parent = this._tempDisplayObjectParent; - return myParent; - }; - /** - * Pair method for `enableTempParent` - * @param cacheParent - Actual parent of element - */ - DisplayObject.prototype.disableTempParent = function (cacheParent) { - this.parent = cacheParent; - }; - Object.defineProperty(DisplayObject.prototype, "x", { - /** - * The position of the displayObject on the x axis relative to the local coordinates of the parent. - * An alias to position.x - */ - get: function () { - return this.position.x; - }, - set: function (value) { - this.transform.position.x = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "y", { - /** - * The position of the displayObject on the y axis relative to the local coordinates of the parent. - * An alias to position.y - */ - get: function () { - return this.position.y; - }, - set: function (value) { - this.transform.position.y = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "worldTransform", { - /** - * Current transform of the object based on world (parent) factors. - * @readonly - */ - get: function () { - return this.transform.worldTransform; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "localTransform", { - /** - * Current transform of the object based on local factors: position, scale, other stuff. - * @readonly - */ - get: function () { - return this.transform.localTransform; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "position", { - /** - * The coordinate of the object relative to the local coordinates of the parent. - * @since 4.0.0 - */ - get: function () { - return this.transform.position; - }, - set: function (value) { - this.transform.position.copyFrom(value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "scale", { - /** - * The scale factors of this object along the local coordinate axes. - * - * The default scale is (1, 1). - * @since 4.0.0 - */ - get: function () { - return this.transform.scale; - }, - set: function (value) { - this.transform.scale.copyFrom(value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "pivot", { - /** - * The center of rotation, scaling, and skewing for this display object in its local space. The `position` - * is the projection of `pivot` in the parent's local space. - * - * By default, the pivot is the origin (0, 0). - * @since 4.0.0 - */ - get: function () { - return this.transform.pivot; - }, - set: function (value) { - this.transform.pivot.copyFrom(value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "skew", { - /** - * The skew factor for the object in radians. - * @since 4.0.0 - */ - get: function () { - return this.transform.skew; - }, - set: function (value) { - this.transform.skew.copyFrom(value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "rotation", { - /** - * The rotation of the object in radians. - * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees. - */ - get: function () { - return this.transform.rotation; - }, - set: function (value) { - this.transform.rotation = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "angle", { - /** - * The angle of the object in degrees. - * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees. - */ - get: function () { - return this.transform.rotation * RAD_TO_DEG; - }, - set: function (value) { - this.transform.rotation = value * DEG_TO_RAD; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "zIndex", { - /** - * The zIndex of the displayObject. - * - * If a container has the sortableChildren property set to true, children will be automatically - * sorted by zIndex value; a higher value will mean it will be moved towards the end of the array, - * and thus rendered on top of other display objects within the same container. - * @see PIXI.Container#sortableChildren - */ - get: function () { - return this._zIndex; - }, - set: function (value) { - this._zIndex = value; - if (this.parent) { - this.parent.sortDirty = true; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "worldVisible", { - /** - * Indicates if the object is globally visible. - * @readonly - */ - get: function () { - var item = this; - do { - if (!item.visible) { - return false; - } - item = item.parent; - } while (item); - return true; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "mask", { - /** - * Sets a mask for the displayObject. A mask is an object that limits the visibility of an - * object to the shape of the mask applied to it. In PixiJS a regular mask must be a - * {@link PIXI.Graphics} or a {@link PIXI.Sprite} object. This allows for much faster masking in canvas as it - * utilities shape clipping. Furthermore, a mask of an object must be in the subtree of its parent. - * Otherwise, `getLocalBounds` may calculate incorrect bounds, which makes the container's width and height wrong. - * To remove a mask, set this property to `null`. - * - * For sprite mask both alpha and red channel are used. Black mask is the same as transparent mask. - * @example - * const graphics = new PIXI.Graphics(); - * graphics.beginFill(0xFF3300); - * graphics.drawRect(50, 250, 100, 100); - * graphics.endFill(); - * - * const sprite = new PIXI.Sprite(texture); - * sprite.mask = graphics; - * @todo At the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. - */ - get: function () { - return this._mask; - }, - set: function (value) { - if (this._mask === value) { - return; - } - if (this._mask) { - var maskObject = (this._mask.isMaskData - ? this._mask.maskObject : this._mask); - if (maskObject) { - maskObject._maskRefCount--; - if (maskObject._maskRefCount === 0) { - maskObject.renderable = true; - maskObject.isMask = false; - } - } - } - this._mask = value; - if (this._mask) { - var maskObject = (this._mask.isMaskData - ? this._mask.maskObject : this._mask); - if (maskObject) { - if (maskObject._maskRefCount === 0) { - maskObject.renderable = false; - maskObject.isMask = true; - } - maskObject._maskRefCount++; - } - } - }, - enumerable: false, - configurable: true - }); - return DisplayObject; - }(eventemitter3)); - /** - * @private - */ - var TemporaryDisplayObject = /** @class */ (function (_super) { - __extends$j(TemporaryDisplayObject, _super); - function TemporaryDisplayObject() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.sortDirty = null; - return _this; - } - return TemporaryDisplayObject; - }(DisplayObject)); - /** - * DisplayObject default updateTransform, does not update children of container. - * Will crash if there's no parent element. - * @memberof PIXI.DisplayObject# - * @method displayObjectUpdateTransform - */ - DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; - - function sortChildren(a, b) { - if (a.zIndex === b.zIndex) { - return a._lastSortedIndex - b._lastSortedIndex; - } - return a.zIndex - b.zIndex; - } - /** - * Container is a general-purpose display object that holds children. It also adds built-in support for advanced - * rendering features like masking and filtering. - * - * It is the base class of all display objects that act as a container for other objects, including Graphics - * and Sprite. - * - * ```js - * import { BlurFilter } from '@pixi/filter-blur'; - * import { Container } from '@pixi/display'; - * import { Graphics } from '@pixi/graphics'; - * import { Sprite } from '@pixi/sprite'; - * - * let container = new Container(); - * let sprite = Sprite.from("https://s3-us-west-2.amazonaws.com/s.cdpn.io/693612/IaUrttj.png"); - * - * sprite.width = 512; - * sprite.height = 512; - * - * // Adds a sprite as a child to this container. As a result, the sprite will be rendered whenever the container - * // is rendered. - * container.addChild(sprite); - * - * // Blurs whatever is rendered by the container - * container.filters = [new BlurFilter()]; - * - * // Only the contents within a circle at the center should be rendered onto the screen. - * container.mask = new Graphics() - * .beginFill(0xffffff) - * .drawCircle(sprite.width / 2, sprite.height / 2, Math.min(sprite.width, sprite.height) / 2) - * .endFill(); - * ``` - * @memberof PIXI - */ - var Container = /** @class */ (function (_super) { - __extends$j(Container, _super); - function Container() { - var _this = _super.call(this) || this; - _this.children = []; - _this.sortableChildren = settings.SORTABLE_CHILDREN; - _this.sortDirty = false; - return _this; - /** - * Fired when a DisplayObject is added to this Container. - * @event PIXI.Container#childAdded - * @param {PIXI.DisplayObject} child - The child added to the Container. - * @param {PIXI.Container} container - The container that added the child. - * @param {number} index - The children's index of the added child. - */ - /** - * Fired when a DisplayObject is removed from this Container. - * @event PIXI.DisplayObject#childRemoved - * @param {PIXI.DisplayObject} child - The child removed from the Container. - * @param {PIXI.Container} container - The container that removed the child. - * @param {number} index - The former children's index of the removed child - */ - } - /** - * Overridable method that can be used by Container subclasses whenever the children array is modified. - * @param _length - */ - Container.prototype.onChildrenChange = function (_length) { - /* empty */ - }; - /** - * Adds one or more children to the container. - * - * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` - * @param {...PIXI.DisplayObject} children - The DisplayObject(s) to add to the container - * @returns {PIXI.DisplayObject} - The first child that was added. - */ - Container.prototype.addChild = function () { - var arguments$1 = arguments; - - var children = []; - for (var _i = 0; _i < arguments.length; _i++) { - children[_i] = arguments$1[_i]; - } - // if there is only one argument we can bypass looping through the them - if (children.length > 1) { - // loop through the array and add all children - for (var i = 0; i < children.length; i++) { - // eslint-disable-next-line prefer-rest-params - this.addChild(children[i]); - } - } - else { - var child = children[0]; - // if the child has a parent then lets remove it as PixiJS objects can only exist in one place - if (child.parent) { - child.parent.removeChild(child); - } - child.parent = this; - this.sortDirty = true; - // ensure child transform will be recalculated - child.transform._parentID = -1; - this.children.push(child); - // ensure bounds will be recalculated - this._boundsID++; - // TODO - lets either do all callbacks or all events.. not both! - this.onChildrenChange(this.children.length - 1); - this.emit('childAdded', child, this, this.children.length - 1); - child.emit('added', this); - } - return children[0]; - }; - /** - * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown - * @param {PIXI.DisplayObject} child - The child to add - * @param {number} index - The index to place the child in - * @returns {PIXI.DisplayObject} The child that was added. - */ - Container.prototype.addChildAt = function (child, index) { - if (index < 0 || index > this.children.length) { - throw new Error(child + "addChildAt: The index " + index + " supplied is out of bounds " + this.children.length); - } - if (child.parent) { - child.parent.removeChild(child); - } - child.parent = this; - this.sortDirty = true; - // ensure child transform will be recalculated - child.transform._parentID = -1; - this.children.splice(index, 0, child); - // ensure bounds will be recalculated - this._boundsID++; - // TODO - lets either do all callbacks or all events.. not both! - this.onChildrenChange(index); - child.emit('added', this); - this.emit('childAdded', child, this, index); - return child; - }; - /** - * Swaps the position of 2 Display Objects within this container. - * @param child - First display object to swap - * @param child2 - Second display object to swap - */ - Container.prototype.swapChildren = function (child, child2) { - if (child === child2) { - return; - } - var index1 = this.getChildIndex(child); - var index2 = this.getChildIndex(child2); - this.children[index1] = child2; - this.children[index2] = child; - this.onChildrenChange(index1 < index2 ? index1 : index2); - }; - /** - * Returns the index position of a child DisplayObject instance - * @param child - The DisplayObject instance to identify - * @returns - The index position of the child display object to identify - */ - Container.prototype.getChildIndex = function (child) { - var index = this.children.indexOf(child); - if (index === -1) { - throw new Error('The supplied DisplayObject must be a child of the caller'); - } - return index; - }; - /** - * Changes the position of an existing child in the display object container - * @param child - The child DisplayObject instance for which you want to change the index number - * @param index - The resulting index number for the child display object - */ - Container.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { - throw new Error("The index " + index + " supplied is out of bounds " + this.children.length); - } - var currentIndex = this.getChildIndex(child); - removeItems(this.children, currentIndex, 1); // remove from old position - this.children.splice(index, 0, child); // add at new position - this.onChildrenChange(index); - }; - /** - * Returns the child at the specified index - * @param index - The index to get the child at - * @returns - The child at the given index, if any. - */ - Container.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { - throw new Error("getChildAt: Index (" + index + ") does not exist."); - } - return this.children[index]; - }; - /** - * Removes one or more children from the container. - * @param {...PIXI.DisplayObject} children - The DisplayObject(s) to remove - * @returns {PIXI.DisplayObject} The first child that was removed. - */ - Container.prototype.removeChild = function () { - var arguments$1 = arguments; - - var children = []; - for (var _i = 0; _i < arguments.length; _i++) { - children[_i] = arguments$1[_i]; - } - // if there is only one argument we can bypass looping through the them - if (children.length > 1) { - // loop through the arguments property and remove all children - for (var i = 0; i < children.length; i++) { - this.removeChild(children[i]); - } - } - else { - var child = children[0]; - var index = this.children.indexOf(child); - if (index === -1) - { return null; } - child.parent = null; - // ensure child transform will be recalculated - child.transform._parentID = -1; - removeItems(this.children, index, 1); - // ensure bounds will be recalculated - this._boundsID++; - // TODO - lets either do all callbacks or all events.. not both! - this.onChildrenChange(index); - child.emit('removed', this); - this.emit('childRemoved', child, this, index); - } - return children[0]; - }; - /** - * Removes a child from the specified index position. - * @param index - The index to get the child from - * @returns The child that was removed. - */ - Container.prototype.removeChildAt = function (index) { - var child = this.getChildAt(index); - // ensure child transform will be recalculated.. - child.parent = null; - child.transform._parentID = -1; - removeItems(this.children, index, 1); - // ensure bounds will be recalculated - this._boundsID++; - // TODO - lets either do all callbacks or all events.. not both! - this.onChildrenChange(index); - child.emit('removed', this); - this.emit('childRemoved', child, this, index); - return child; - }; - /** - * Removes all children from this container that are within the begin and end indexes. - * @param beginIndex - The beginning position. - * @param endIndex - The ending position. Default value is size of the container. - * @returns - List of removed children - */ - Container.prototype.removeChildren = function (beginIndex, endIndex) { - if (beginIndex === void 0) { beginIndex = 0; } - if (endIndex === void 0) { endIndex = this.children.length; } - var begin = beginIndex; - var end = endIndex; - var range = end - begin; - var removed; - if (range > 0 && range <= end) { - removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { - removed[i].parent = null; - if (removed[i].transform) { - removed[i].transform._parentID = -1; - } - } - this._boundsID++; - this.onChildrenChange(beginIndex); - for (var i = 0; i < removed.length; ++i) { - removed[i].emit('removed', this); - this.emit('childRemoved', removed[i], this, i); - } - return removed; - } - else if (range === 0 && this.children.length === 0) { - return []; - } - throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); - }; - /** Sorts children by zIndex. Previous order is maintained for 2 children with the same zIndex. */ - Container.prototype.sortChildren = function () { - var sortRequired = false; - for (var i = 0, j = this.children.length; i < j; ++i) { - var child = this.children[i]; - child._lastSortedIndex = i; - if (!sortRequired && child.zIndex !== 0) { - sortRequired = true; - } - } - if (sortRequired && this.children.length > 1) { - this.children.sort(sortChildren); - } - this.sortDirty = false; - }; - /** Updates the transform on all children of this container for rendering. */ - Container.prototype.updateTransform = function () { - if (this.sortableChildren && this.sortDirty) { - this.sortChildren(); - } - this._boundsID++; - this.transform.updateTransform(this.parent.transform); - // TODO: check render flags, how to process stuff here - this.worldAlpha = this.alpha * this.parent.worldAlpha; - for (var i = 0, j = this.children.length; i < j; ++i) { - var child = this.children[i]; - if (child.visible) { - child.updateTransform(); - } - } - }; - /** - * Recalculates the bounds of the container. - * - * This implementation will automatically fit the children's bounds into the calculation. Each child's bounds - * is limited to its mask's bounds or filterArea, if any is applied. - */ - Container.prototype.calculateBounds = function () { - this._bounds.clear(); - this._calculateBounds(); - for (var i = 0; i < this.children.length; i++) { - var child = this.children[i]; - if (!child.visible || !child.renderable) { - continue; - } - child.calculateBounds(); - // TODO: filter+mask, need to mask both somehow - if (child._mask) { - var maskObject = (child._mask.isMaskData - ? child._mask.maskObject : child._mask); - if (maskObject) { - maskObject.calculateBounds(); - this._bounds.addBoundsMask(child._bounds, maskObject._bounds); - } - else { - this._bounds.addBounds(child._bounds); - } - } - else if (child.filterArea) { - this._bounds.addBoundsArea(child._bounds, child.filterArea); - } - else { - this._bounds.addBounds(child._bounds); - } - } - this._bounds.updateID = this._boundsID; - }; - /** - * Retrieves the local bounds of the displayObject as a rectangle object. - * - * Calling `getLocalBounds` may invalidate the `_bounds` of the whole subtree below. If using it inside a render() - * call, it is advised to call `getBounds()` immediately after to recalculate the world bounds of the subtree. - * @param rect - Optional rectangle to store the result of the bounds calculation. - * @param skipChildrenUpdate - Setting to `true` will stop re-calculation of children transforms, - * it was default behaviour of pixi 4.0-5.2 and caused many problems to users. - * @returns - The rectangular bounding area. - */ - Container.prototype.getLocalBounds = function (rect, skipChildrenUpdate) { - if (skipChildrenUpdate === void 0) { skipChildrenUpdate = false; } - var result = _super.prototype.getLocalBounds.call(this, rect); - if (!skipChildrenUpdate) { - for (var i = 0, j = this.children.length; i < j; ++i) { - var child = this.children[i]; - if (child.visible) { - child.updateTransform(); - } - } - } - return result; - }; - /** - * Recalculates the content bounds of this object. This should be overriden to - * calculate the bounds of this specific object (not including children). - * @protected - */ - Container.prototype._calculateBounds = function () { - // FILL IN// - }; - /** - * Renders this object and its children with culling. - * @protected - * @param {PIXI.Renderer} renderer - The renderer - */ - Container.prototype._renderWithCulling = function (renderer) { - var sourceFrame = renderer.renderTexture.sourceFrame; - // If the source frame is empty, stop rendering. - if (!(sourceFrame.width > 0 && sourceFrame.height > 0)) { - return; - } - // Render the content of the container only if its bounds intersect with the source frame. - // All filters are on the stack at this point, and the filter source frame is bound: - // therefore, even if the bounds to non intersect the filter frame, the filter - // is still applied and any filter padding that is in the frame is rendered correctly. - var bounds; - var transform; - // If cullArea is set, we use this rectangle instead of the bounds of the object. The cullArea - // rectangle must completely contain the container and its children including filter padding. - if (this.cullArea) { - bounds = this.cullArea; - transform = this.worldTransform; - } - // If the container doesn't override _render, we can skip the bounds calculation and intersection test. - else if (this._render !== Container.prototype._render) { - bounds = this.getBounds(true); - } - // Render the container if the source frame intersects the bounds. - if (bounds && sourceFrame.intersects(bounds, transform)) { - this._render(renderer); - } - // If the bounds are defined by cullArea and do not intersect with the source frame, stop rendering. - else if (this.cullArea) { - return; - } - // Unless cullArea is set, we cannot skip the children if the bounds of the container do not intersect - // the source frame, because the children might have filters with nonzero padding, which may intersect - // with the source frame while the bounds do not: filter padding is not included in the bounds. - // If cullArea is not set, render the children with culling temporarily enabled so that they are not rendered - // if they are out of frame; otherwise, render the children normally. - for (var i = 0, j = this.children.length; i < j; ++i) { - var child = this.children[i]; - var childCullable = child.cullable; - child.cullable = childCullable || !this.cullArea; - child.render(renderer); - child.cullable = childCullable; - } - }; - /** - * Renders the object using the WebGL renderer. - * - * The [_render]{@link PIXI.Container#_render} method is be overriden for rendering the contents of the - * container itself. This `render` method will invoke it, and also invoke the `render` methods of all - * children afterward. - * - * If `renderable` or `visible` is false or if `worldAlpha` is not positive or if `cullable` is true and - * the bounds of this object are out of frame, this implementation will entirely skip rendering. - * See {@link PIXI.DisplayObject} for choosing between `renderable` or `visible`. Generally, - * setting alpha to zero is not recommended for purely skipping rendering. - * - * When your scene becomes large (especially when it is larger than can be viewed in a single screen), it is - * advised to employ **culling** to automatically skip rendering objects outside of the current screen. - * See [cullable]{@link PIXI.DisplayObject#cullable} and [cullArea]{@link PIXI.DisplayObject#cullArea}. - * Other culling methods might be better suited for a large number static objects; see - * [@pixi-essentials/cull]{@link https://www.npmjs.com/package/@pixi-essentials/cull} and - * [pixi-cull]{@link https://www.npmjs.com/package/pixi-cull}. - * - * The [renderAdvanced]{@link PIXI.Container#renderAdvanced} method is internally used when when masking or - * filtering is applied on a container. This does, however, break batching and can affect performance when - * masking and filtering is applied extensively throughout the scene graph. - * @param renderer - The renderer - */ - Container.prototype.render = function (renderer) { - // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { - return; - } - // do a quick check to see if this element has a mask or a filter. - if (this._mask || (this.filters && this.filters.length)) { - this.renderAdvanced(renderer); - } - else if (this.cullable) { - this._renderWithCulling(renderer); - } - else { - this._render(renderer); - for (var i = 0, j = this.children.length; i < j; ++i) { - this.children[i].render(renderer); - } - } - }; - /** - * Render the object using the WebGL renderer and advanced features. - * @param renderer - The renderer - */ - Container.prototype.renderAdvanced = function (renderer) { - var filters = this.filters; - var mask = this._mask; - // push filter first as we need to ensure the stencil buffer is correct for any masking - if (filters) { - if (!this._enabledFilters) { - this._enabledFilters = []; - } - this._enabledFilters.length = 0; - for (var i = 0; i < filters.length; i++) { - if (filters[i].enabled) { - this._enabledFilters.push(filters[i]); - } - } - } - var flush = (filters && this._enabledFilters && this._enabledFilters.length) - || (mask && (!mask.isMaskData - || (mask.enabled && (mask.autoDetect || mask.type !== exports.MASK_TYPES.NONE)))); - if (flush) { - renderer.batch.flush(); - } - if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filter.push(this, this._enabledFilters); - } - if (mask) { - renderer.mask.push(this, this._mask); - } - if (this.cullable) { - this._renderWithCulling(renderer); - } - else { - this._render(renderer); - for (var i = 0, j = this.children.length; i < j; ++i) { - this.children[i].render(renderer); - } - } - if (flush) { - renderer.batch.flush(); - } - if (mask) { - renderer.mask.pop(this); - } - if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filter.pop(); - } - }; - /** - * To be overridden by the subclasses. - * @param _renderer - The renderer - */ - Container.prototype._render = function (_renderer) { - // this is where content itself gets rendered... - }; - /** - * Removes all internal references and listeners as well as removes children from the display list. - * Do not use a Container after calling `destroy`. - * @param options - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy - * method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the texture of the child sprite - * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the base texture of the child sprite - */ - Container.prototype.destroy = function (options) { - _super.prototype.destroy.call(this); - this.sortDirty = false; - var destroyChildren = typeof options === 'boolean' ? options : options && options.children; - var oldChildren = this.removeChildren(0, this.children.length); - if (destroyChildren) { - for (var i = 0; i < oldChildren.length; ++i) { - oldChildren[i].destroy(options); - } - } - }; - Object.defineProperty(Container.prototype, "width", { - /** The width of the Container, setting this will actually modify the scale to achieve the value set. */ - get: function () { - return this.scale.x * this.getLocalBounds().width; - }, - set: function (value) { - var width = this.getLocalBounds().width; - if (width !== 0) { - this.scale.x = value / width; - } - else { - this.scale.x = 1; - } - this._width = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Container.prototype, "height", { - /** The height of the Container, setting this will actually modify the scale to achieve the value set. */ - get: function () { - return this.scale.y * this.getLocalBounds().height; - }, - set: function (value) { - var height = this.getLocalBounds().height; - if (height !== 0) { - this.scale.y = value / height; - } - else { - this.scale.y = 1; - } - this._height = value; - }, - enumerable: false, - configurable: true - }); - return Container; - }(DisplayObject)); - /** - * Container default updateTransform, does update children of container. - * Will crash if there's no parent element. - * @memberof PIXI.Container# - * @method containerUpdateTransform - */ - Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; - - /*! - * @pixi/extensions - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/extensions is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - - var __assign$1 = function() { - __assign$1 = Object.assign || function __assign(t) { - var arguments$1 = arguments; - - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments$1[i]; - for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p)) { t[p] = s[p]; } } - } - return t; - }; - return __assign$1.apply(this, arguments); - }; - - /** - * Collection of valid extension types. - * @memberof PIXI - * @property {string} Application - Application plugins - * @property {string} RendererPlugin - Plugins for Renderer - * @property {string} CanvasRendererPlugin - Plugins for CanvasRenderer - * @property {string} Loader - Plugins to use with Loader - * @property {string} LoadParser - Parsers for Assets loader. - * @property {string} ResolveParser - Parsers for Assets resolvers. - * @property {string} CacheParser - Parsers for Assets cache. - */ - exports.ExtensionType = void 0; - (function (ExtensionType) { - ExtensionType["Application"] = "application"; - ExtensionType["RendererPlugin"] = "renderer-webgl-plugin"; - ExtensionType["CanvasRendererPlugin"] = "renderer-canvas-plugin"; - ExtensionType["Loader"] = "loader"; - ExtensionType["LoadParser"] = "load-parser"; - ExtensionType["ResolveParser"] = "resolve-parser"; - ExtensionType["CacheParser"] = "cache-parser"; - ExtensionType["DetectionParser"] = "detection-parser"; - })(exports.ExtensionType || (exports.ExtensionType = {})); - /** - * Convert input into extension format data. - * @ignore - */ - var normalizeExtension = function (ext) { - // Class/Object submission, use extension object - if (typeof ext === 'function' || (typeof ext === 'object' && ext.extension)) { - if (!ext.extension) { - throw new Error('Extension class must have an extension object'); - } - var metadata = (typeof ext.extension !== 'object') - ? { type: ext.extension } - : ext.extension; - ext = __assign$1(__assign$1({}, metadata), { ref: ext }); - } - if (typeof ext === 'object') { - ext = __assign$1({}, ext); - } - else { - throw new Error('Invalid extension type'); - } - if (typeof ext.type === 'string') { - ext.type = [ext.type]; - } - return ext; - }; - /** - * Global registration of all PixiJS extensions. One-stop-shop for extensibility. - * @memberof PIXI - * @namespace extensions - */ - var extensions = { - /** @ignore */ - _addHandlers: null, - /** @ignore */ - _removeHandlers: null, - /** @ignore */ - _queue: {}, - /** - * Remove extensions from PixiJS. - * @param extensions - Extensions to be removed. - * @returns {PIXI.extensions} For chaining. - */ - remove: function () { - var arguments$1 = arguments; - - var _this = this; - var extensions = []; - for (var _i = 0; _i < arguments.length; _i++) { - extensions[_i] = arguments$1[_i]; - } - extensions.map(normalizeExtension).forEach(function (ext) { - ext.type.forEach(function (type) { var _a, _b; return (_b = (_a = _this._removeHandlers)[type]) === null || _b === void 0 ? void 0 : _b.call(_a, ext); }); - }); - return this; - }, - /** - * Register new extensions with PixiJS. - * @param extensions - The spread of extensions to add to PixiJS. - * @returns {PIXI.extensions} For chaining. - */ - add: function () { - var arguments$1 = arguments; - - var _this = this; - var extensions = []; - for (var _i = 0; _i < arguments.length; _i++) { - extensions[_i] = arguments$1[_i]; - } - // Handle any extensions either passed as class w/ data or as data - extensions.map(normalizeExtension).forEach(function (ext) { - ext.type.forEach(function (type) { - var handlers = _this._addHandlers; - var queue = _this._queue; - if (!handlers[type]) { - queue[type] = queue[type] || []; - queue[type].push(ext); - } - else { - handlers[type](ext); - } - }); - }); - return this; - }, - /** - * Internal method to handle extensions by name. - * @param type - The extension type. - * @param onAdd - Function for handling when extensions are added/registered passes {@link PIXI.ExtensionFormat}. - * @param onRemove - Function for handling when extensions are removed/unregistered passes {@link PIXI.ExtensionFormat}. - * @returns {PIXI.extensions} For chaining. - */ - handle: function (type, onAdd, onRemove) { - var addHandlers = this._addHandlers = this._addHandlers || {}; - var removeHandlers = this._removeHandlers = this._removeHandlers || {}; - if (addHandlers[type] || removeHandlers[type]) { - throw new Error("Extension type " + type + " already has a handler"); - } - addHandlers[type] = onAdd; - removeHandlers[type] = onRemove; - // Process the queue - var queue = this._queue; - // Process any plugins that have been registered before the handler - if (queue[type]) { - queue[type].forEach(function (ext) { return onAdd(ext); }); - delete queue[type]; - } - return this; - }, - /** - * Handle a type, but using a map by `name` property. - * @param type - Type of extension to handle. - * @param map - The object map of named extensions. - * @returns {PIXI.extensions} For chaining. - */ - handleByMap: function (type, map) { - return this.handle(type, function (extension) { - map[extension.name] = extension.ref; - }, function (extension) { - delete map[extension.name]; - }); - }, - /** - * Handle a type, but using a list of extensions. - * @param type - Type of extension to handle. - * @param list - The list of extensions. - * @returns {PIXI.extensions} For chaining. - */ - handleByList: function (type, list) { - return this.handle(type, function (extension) { - var _a, _b; - if (list.includes(extension.ref)) { - return; - } - list.push(extension.ref); - // TODO: remove me later, only added for @pixi/loaders - if (type === exports.ExtensionType.Loader) { - (_b = (_a = extension.ref).add) === null || _b === void 0 ? void 0 : _b.call(_a); - } - }, function (extension) { - var index = list.indexOf(extension.ref); - if (index !== -1) { - list.splice(index, 1); - } - }); - }, - }; - - /*! - * @pixi/runner - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/runner is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - /** - * A Runner is a highly performant and simple alternative to signals. Best used in situations - * where events are dispatched to many objects at high frequency (say every frame!) - * - * - * like a signal.. - * ``` - * import { Runner } from '@pixi/runner'; - * - * const myObject = { - * loaded: new Runner('loaded') - * } - * - * const listener = { - * loaded: function(){ - * // thin - * } - * } - * - * myObject.loaded.add(listener); - * - * myObject.loaded.emit(); - * ``` - * - * Or for handling calling the same function on many items - * ``` - * import { Runner } from '@pixi/runner'; - * - * const myGame = { - * update: new Runner('update') - * } - * - * const gameObject = { - * update: function(time){ - * // update my gamey state - * } - * } - * - * myGame.update.add(gameObject); - * - * myGame.update.emit(time); - * ``` - * @memberof PIXI - */ - var Runner = /** @class */ (function () { - /** - * @param name - The function name that will be executed on the listeners added to this Runner. - */ - function Runner(name) { - this.items = []; - this._name = name; - this._aliasCount = 0; - } - /* eslint-disable jsdoc/require-param, jsdoc/check-param-names */ - /** - * Dispatch/Broadcast Runner to all listeners added to the queue. - * @param {...any} params - (optional) parameters to pass to each listener - */ - /* eslint-enable jsdoc/require-param, jsdoc/check-param-names */ - Runner.prototype.emit = function (a0, a1, a2, a3, a4, a5, a6, a7) { - if (arguments.length > 8) { - throw new Error('max arguments reached'); - } - var _a = this, name = _a.name, items = _a.items; - this._aliasCount++; - for (var i = 0, len = items.length; i < len; i++) { - items[i][name](a0, a1, a2, a3, a4, a5, a6, a7); - } - if (items === this.items) { - this._aliasCount--; - } - return this; - }; - Runner.prototype.ensureNonAliasedItems = function () { - if (this._aliasCount > 0 && this.items.length > 1) { - this._aliasCount = 0; - this.items = this.items.slice(0); - } - }; - /** - * Add a listener to the Runner - * - * Runners do not need to have scope or functions passed to them. - * All that is required is to pass the listening object and ensure that it has contains a function that has the same name - * as the name provided to the Runner when it was created. - * - * Eg A listener passed to this Runner will require a 'complete' function. - * - * ``` - * import { Runner } from '@pixi/runner'; - * - * const complete = new Runner('complete'); - * ``` - * - * The scope used will be the object itself. - * @param {any} item - The object that will be listening. - */ - Runner.prototype.add = function (item) { - if (item[this._name]) { - this.ensureNonAliasedItems(); - this.remove(item); - this.items.push(item); - } - return this; - }; - /** - * Remove a single listener from the dispatch queue. - * @param {any} item - The listener that you would like to remove. - */ - Runner.prototype.remove = function (item) { - var index = this.items.indexOf(item); - if (index !== -1) { - this.ensureNonAliasedItems(); - this.items.splice(index, 1); - } - return this; - }; - /** - * Check to see if the listener is already in the Runner - * @param {any} item - The listener that you would like to check. - */ - Runner.prototype.contains = function (item) { - return this.items.indexOf(item) !== -1; - }; - /** Remove all listeners from the Runner */ - Runner.prototype.removeAll = function () { - this.ensureNonAliasedItems(); - this.items.length = 0; - return this; - }; - /** Remove all references, don't use after this. */ - Runner.prototype.destroy = function () { - this.removeAll(); - this.items = null; - this._name = null; - }; - Object.defineProperty(Runner.prototype, "empty", { - /** - * `true` if there are no this Runner contains no listeners - * @readonly - */ - get: function () { - return this.items.length === 0; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Runner.prototype, "name", { - /** - * The name of the runner. - * @readonly - */ - get: function () { - return this._name; - }, - enumerable: false, - configurable: true - }); - return Runner; - }()); - Object.defineProperties(Runner.prototype, { - /** - * Alias for `emit` - * @memberof PIXI.Runner# - * @method dispatch - * @see PIXI.Runner#emit - */ - dispatch: { value: Runner.prototype.emit }, - /** - * Alias for `emit` - * @memberof PIXI.Runner# - * @method run - * @see PIXI.Runner#emit - */ - run: { value: Runner.prototype.emit }, - }); - - /*! - * @pixi/ticker - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/ticker is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Target frames per millisecond. - * @static - * @name TARGET_FPMS - * @memberof PIXI.settings - * @type {number} - * @default 0.06 - */ - settings.TARGET_FPMS = 0.06; - - /** - * Represents the update priorities used by internal PIXI classes when registered with - * the {@link PIXI.Ticker} object. Higher priority items are updated first and lower - * priority items, such as render, should go later. - * @static - * @constant - * @name UPDATE_PRIORITY - * @memberof PIXI - * @enum {number} - * @property {number} [INTERACTION=50] Highest priority, used for {@link PIXI.InteractionManager} - * @property {number} [HIGH=25] High priority updating, {@link PIXI.VideoBaseTexture} and {@link PIXI.AnimatedSprite} - * @property {number} [NORMAL=0] Default priority for ticker events, see {@link PIXI.Ticker#add}. - * @property {number} [LOW=-25] Low priority used for {@link PIXI.Application} rendering. - * @property {number} [UTILITY=-50] Lowest priority used for {@link PIXI.BasePrepare} utility. - */ - exports.UPDATE_PRIORITY = void 0; - (function (UPDATE_PRIORITY) { - UPDATE_PRIORITY[UPDATE_PRIORITY["INTERACTION"] = 50] = "INTERACTION"; - UPDATE_PRIORITY[UPDATE_PRIORITY["HIGH"] = 25] = "HIGH"; - UPDATE_PRIORITY[UPDATE_PRIORITY["NORMAL"] = 0] = "NORMAL"; - UPDATE_PRIORITY[UPDATE_PRIORITY["LOW"] = -25] = "LOW"; - UPDATE_PRIORITY[UPDATE_PRIORITY["UTILITY"] = -50] = "UTILITY"; - })(exports.UPDATE_PRIORITY || (exports.UPDATE_PRIORITY = {})); - - /** - * Internal class for handling the priority sorting of ticker handlers. - * @private - * @class - * @memberof PIXI - */ - var TickerListener = /** @class */ (function () { - /** - * Constructor - * @private - * @param fn - The listener function to be added for one update - * @param context - The listener context - * @param priority - The priority for emitting - * @param once - If the handler should fire once - */ - function TickerListener(fn, context, priority, once) { - if (context === void 0) { context = null; } - if (priority === void 0) { priority = 0; } - if (once === void 0) { once = false; } - /** The next item in chain. */ - this.next = null; - /** The previous item in chain. */ - this.previous = null; - /** `true` if this listener has been destroyed already. */ - this._destroyed = false; - this.fn = fn; - this.context = context; - this.priority = priority; - this.once = once; - } - /** - * Simple compare function to figure out if a function and context match. - * @private - * @param fn - The listener function to be added for one update - * @param context - The listener context - * @returns `true` if the listener match the arguments - */ - TickerListener.prototype.match = function (fn, context) { - if (context === void 0) { context = null; } - return this.fn === fn && this.context === context; - }; - /** - * Emit by calling the current function. - * @private - * @param deltaTime - time since the last emit. - * @returns Next ticker - */ - TickerListener.prototype.emit = function (deltaTime) { - if (this.fn) { - if (this.context) { - this.fn.call(this.context, deltaTime); - } - else { - this.fn(deltaTime); - } - } - var redirect = this.next; - if (this.once) { - this.destroy(true); - } - // Soft-destroying should remove - // the next reference - if (this._destroyed) { - this.next = null; - } - return redirect; - }; - /** - * Connect to the list. - * @private - * @param previous - Input node, previous listener - */ - TickerListener.prototype.connect = function (previous) { - this.previous = previous; - if (previous.next) { - previous.next.previous = this; - } - this.next = previous.next; - previous.next = this; - }; - /** - * Destroy and don't use after this. - * @private - * @param hard - `true` to remove the `next` reference, this - * is considered a hard destroy. Soft destroy maintains the next reference. - * @returns The listener to redirect while emitting or removing. - */ - TickerListener.prototype.destroy = function (hard) { - if (hard === void 0) { hard = false; } - this._destroyed = true; - this.fn = null; - this.context = null; - // Disconnect, hook up next and previous - if (this.previous) { - this.previous.next = this.next; - } - if (this.next) { - this.next.previous = this.previous; - } - // Redirect to the next item - var redirect = this.next; - // Remove references - this.next = hard ? null : redirect; - this.previous = null; - return redirect; - }; - return TickerListener; - }()); - - /** - * A Ticker class that runs an update loop that other objects listen to. - * - * This class is composed around listeners meant for execution on the next requested animation frame. - * Animation frames are requested only when necessary, e.g. When the ticker is started and the emitter has listeners. - * @class - * @memberof PIXI - */ - var Ticker = /** @class */ (function () { - function Ticker() { - var _this = this; - /** - * Whether or not this ticker should invoke the method - * {@link PIXI.Ticker#start} automatically - * when a listener is added. - */ - this.autoStart = false; - /** - * Scalar time value from last frame to this frame. - * This value is capped by setting {@link PIXI.Ticker#minFPS} - * and is scaled with {@link PIXI.Ticker#speed}. - * **Note:** The cap may be exceeded by scaling. - */ - this.deltaTime = 1; - /** - * The last time {@link PIXI.Ticker#update} was invoked. - * This value is also reset internally outside of invoking - * update, but only when a new animation frame is requested. - * If the platform supports DOMHighResTimeStamp, - * this value will have a precision of 1 µs. - */ - this.lastTime = -1; - /** - * Factor of current {@link PIXI.Ticker#deltaTime}. - * @example - * // Scales ticker.deltaTime to what would be - * // the equivalent of approximately 120 FPS - * ticker.speed = 2; - */ - this.speed = 1; - /** - * Whether or not this ticker has been started. - * `true` if {@link PIXI.Ticker#start} has been called. - * `false` if {@link PIXI.Ticker#stop} has been called. - * While `false`, this value may change to `true` in the - * event of {@link PIXI.Ticker#autoStart} being `true` - * and a listener is added. - */ - this.started = false; - /** Internal current frame request ID */ - this._requestId = null; - /** - * Internal value managed by minFPS property setter and getter. - * This is the maximum allowed milliseconds between updates. - */ - this._maxElapsedMS = 100; - /** - * Internal value managed by minFPS property setter and getter. - * This is the minimum allowed milliseconds between updates. - */ - this._minElapsedMS = 0; - /** If enabled, deleting is disabled.*/ - this._protected = false; - /** The last time keyframe was executed. Maintains a relatively fixed interval with the previous value. */ - this._lastFrame = -1; - this._head = new TickerListener(null, null, Infinity); - this.deltaMS = 1 / settings.TARGET_FPMS; - this.elapsedMS = 1 / settings.TARGET_FPMS; - this._tick = function (time) { - _this._requestId = null; - if (_this.started) { - // Invoke listeners now - _this.update(time); - // Listener side effects may have modified ticker state. - if (_this.started && _this._requestId === null && _this._head.next) { - _this._requestId = requestAnimationFrame(_this._tick); - } - } - }; - } - /** - * Conditionally requests a new animation frame. - * If a frame has not already been requested, and if the internal - * emitter has listeners, a new frame is requested. - * @private - */ - Ticker.prototype._requestIfNeeded = function () { - if (this._requestId === null && this._head.next) { - // ensure callbacks get correct delta - this.lastTime = performance.now(); - this._lastFrame = this.lastTime; - this._requestId = requestAnimationFrame(this._tick); - } - }; - /** - * Conditionally cancels a pending animation frame. - * @private - */ - Ticker.prototype._cancelIfNeeded = function () { - if (this._requestId !== null) { - cancelAnimationFrame(this._requestId); - this._requestId = null; - } - }; - /** - * Conditionally requests a new animation frame. - * If the ticker has been started it checks if a frame has not already - * been requested, and if the internal emitter has listeners. If these - * conditions are met, a new frame is requested. If the ticker has not - * been started, but autoStart is `true`, then the ticker starts now, - * and continues with the previous conditions to request a new frame. - * @private - */ - Ticker.prototype._startIfPossible = function () { - if (this.started) { - this._requestIfNeeded(); - } - else if (this.autoStart) { - this.start(); - } - }; - /** - * Register a handler for tick events. Calls continuously unless - * it is removed or the ticker is stopped. - * @param fn - The listener function to be added for updates - * @param context - The listener context - * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting - * @returns This instance of a ticker - */ - Ticker.prototype.add = function (fn, context, priority) { - if (priority === void 0) { priority = exports.UPDATE_PRIORITY.NORMAL; } - return this._addListener(new TickerListener(fn, context, priority)); - }; - /** - * Add a handler for the tick event which is only execute once. - * @param fn - The listener function to be added for one update - * @param context - The listener context - * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting - * @returns This instance of a ticker - */ - Ticker.prototype.addOnce = function (fn, context, priority) { - if (priority === void 0) { priority = exports.UPDATE_PRIORITY.NORMAL; } - return this._addListener(new TickerListener(fn, context, priority, true)); - }; - /** - * Internally adds the event handler so that it can be sorted by priority. - * Priority allows certain handler (user, AnimatedSprite, Interaction) to be run - * before the rendering. - * @private - * @param listener - Current listener being added. - * @returns This instance of a ticker - */ - Ticker.prototype._addListener = function (listener) { - // For attaching to head - var current = this._head.next; - var previous = this._head; - // Add the first item - if (!current) { - listener.connect(previous); - } - else { - // Go from highest to lowest priority - while (current) { - if (listener.priority > current.priority) { - listener.connect(previous); - break; - } - previous = current; - current = current.next; - } - // Not yet connected - if (!listener.previous) { - listener.connect(previous); - } - } - this._startIfPossible(); - return this; - }; - /** - * Removes any handlers matching the function and context parameters. - * If no handlers are left after removing, then it cancels the animation frame. - * @param fn - The listener function to be removed - * @param context - The listener context to be removed - * @returns This instance of a ticker - */ - Ticker.prototype.remove = function (fn, context) { - var listener = this._head.next; - while (listener) { - // We found a match, lets remove it - // no break to delete all possible matches - // incase a listener was added 2+ times - if (listener.match(fn, context)) { - listener = listener.destroy(); - } - else { - listener = listener.next; - } - } - if (!this._head.next) { - this._cancelIfNeeded(); - } - return this; - }; - Object.defineProperty(Ticker.prototype, "count", { - /** - * The number of listeners on this ticker, calculated by walking through linked list - * @readonly - * @member {number} - */ - get: function () { - if (!this._head) { - return 0; - } - var count = 0; - var current = this._head; - while ((current = current.next)) { - count++; - } - return count; - }, - enumerable: false, - configurable: true - }); - /** Starts the ticker. If the ticker has listeners a new animation frame is requested at this point. */ - Ticker.prototype.start = function () { - if (!this.started) { - this.started = true; - this._requestIfNeeded(); - } - }; - /** Stops the ticker. If the ticker has requested an animation frame it is canceled at this point. */ - Ticker.prototype.stop = function () { - if (this.started) { - this.started = false; - this._cancelIfNeeded(); - } - }; - /** Destroy the ticker and don't use after this. Calling this method removes all references to internal events. */ - Ticker.prototype.destroy = function () { - if (!this._protected) { - this.stop(); - var listener = this._head.next; - while (listener) { - listener = listener.destroy(true); - } - this._head.destroy(); - this._head = null; - } - }; - /** - * Triggers an update. An update entails setting the - * current {@link PIXI.Ticker#elapsedMS}, - * the current {@link PIXI.Ticker#deltaTime}, - * invoking all listeners with current deltaTime, - * and then finally setting {@link PIXI.Ticker#lastTime} - * with the value of currentTime that was provided. - * This method will be called automatically by animation - * frame callbacks if the ticker instance has been started - * and listeners are added. - * @param {number} [currentTime=performance.now()] - the current time of execution - */ - Ticker.prototype.update = function (currentTime) { - if (currentTime === void 0) { currentTime = performance.now(); } - var elapsedMS; - // If the difference in time is zero or negative, we ignore most of the work done here. - // If there is no valid difference, then should be no reason to let anyone know about it. - // A zero delta, is exactly that, nothing should update. - // - // The difference in time can be negative, and no this does not mean time traveling. - // This can be the result of a race condition between when an animation frame is requested - // on the current JavaScript engine event loop, and when the ticker's start method is invoked - // (which invokes the internal _requestIfNeeded method). If a frame is requested before - // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, - // can receive a time argument that can be less than the lastTime value that was set within - // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. - // - // This check covers this browser engine timing issue, as well as if consumers pass an invalid - // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. - if (currentTime > this.lastTime) { - // Save uncapped elapsedMS for measurement - elapsedMS = this.elapsedMS = currentTime - this.lastTime; - // cap the milliseconds elapsed used for deltaTime - if (elapsedMS > this._maxElapsedMS) { - elapsedMS = this._maxElapsedMS; - } - elapsedMS *= this.speed; - // If not enough time has passed, exit the function. - // Get ready for next frame by setting _lastFrame, but based on _minElapsedMS - // adjustment to ensure a relatively stable interval. - if (this._minElapsedMS) { - var delta = currentTime - this._lastFrame | 0; - if (delta < this._minElapsedMS) { - return; - } - this._lastFrame = currentTime - (delta % this._minElapsedMS); - } - this.deltaMS = elapsedMS; - this.deltaTime = this.deltaMS * settings.TARGET_FPMS; - // Cache a local reference, in-case ticker is destroyed - // during the emit, we can still check for head.next - var head = this._head; - // Invoke listeners added to internal emitter - var listener = head.next; - while (listener) { - listener = listener.emit(this.deltaTime); - } - if (!head.next) { - this._cancelIfNeeded(); - } - } - else { - this.deltaTime = this.deltaMS = this.elapsedMS = 0; - } - this.lastTime = currentTime; - }; - Object.defineProperty(Ticker.prototype, "FPS", { - /** - * The frames per second at which this ticker is running. - * The default is approximately 60 in most modern browsers. - * **Note:** This does not factor in the value of - * {@link PIXI.Ticker#speed}, which is specific - * to scaling {@link PIXI.Ticker#deltaTime}. - * @member {number} - * @readonly - */ - get: function () { - return 1000 / this.elapsedMS; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Ticker.prototype, "minFPS", { - /** - * Manages the maximum amount of milliseconds allowed to - * elapse between invoking {@link PIXI.Ticker#update}. - * This value is used to cap {@link PIXI.Ticker#deltaTime}, - * but does not effect the measured value of {@link PIXI.Ticker#FPS}. - * When setting this property it is clamped to a value between - * `0` and `PIXI.settings.TARGET_FPMS * 1000`. - * @member {number} - * @default 10 - */ - get: function () { - return 1000 / this._maxElapsedMS; - }, - set: function (fps) { - // Minimum must be below the maxFPS - var minFPS = Math.min(this.maxFPS, fps); - // Must be at least 0, but below 1 / settings.TARGET_FPMS - var minFPMS = Math.min(Math.max(0, minFPS) / 1000, settings.TARGET_FPMS); - this._maxElapsedMS = 1 / minFPMS; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Ticker.prototype, "maxFPS", { - /** - * Manages the minimum amount of milliseconds required to - * elapse between invoking {@link PIXI.Ticker#update}. - * This will effect the measured value of {@link PIXI.Ticker#FPS}. - * If it is set to `0`, then there is no limit; PixiJS will render as many frames as it can. - * Otherwise it will be at least `minFPS` - * @member {number} - * @default 0 - */ - get: function () { - if (this._minElapsedMS) { - return Math.round(1000 / this._minElapsedMS); - } - return 0; - }, - set: function (fps) { - if (fps === 0) { - this._minElapsedMS = 0; - } - else { - // Max must be at least the minFPS - var maxFPS = Math.max(this.minFPS, fps); - this._minElapsedMS = 1 / (maxFPS / 1000); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Ticker, "shared", { - /** - * The shared ticker instance used by {@link PIXI.AnimatedSprite} and by - * {@link PIXI.VideoResource} to update animation frames / video textures. - * - * It may also be used by {@link PIXI.Application} if created with the `sharedTicker` option property set to true. - * - * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance. - * Please follow the examples for usage, including how to opt-out of auto-starting the shared ticker. - * @example - * let ticker = PIXI.Ticker.shared; - * // Set this to prevent starting this ticker when listeners are added. - * // By default this is true only for the PIXI.Ticker.shared instance. - * ticker.autoStart = false; - * // FYI, call this to ensure the ticker is stopped. It should be stopped - * // if you have not attempted to render anything yet. - * ticker.stop(); - * // Call this when you are ready for a running shared ticker. - * ticker.start(); - * @example - * // You may use the shared ticker to render... - * let renderer = PIXI.autoDetectRenderer(); - * let stage = new PIXI.Container(); - * document.body.appendChild(renderer.view); - * ticker.add(function (time) { - * renderer.render(stage); - * }); - * @example - * // Or you can just update it manually. - * ticker.autoStart = false; - * ticker.stop(); - * function animate(time) { - * ticker.update(time); - * renderer.render(stage); - * requestAnimationFrame(animate); - * } - * animate(performance.now()); - * @member {PIXI.Ticker} - * @static - */ - get: function () { - if (!Ticker._shared) { - var shared = Ticker._shared = new Ticker(); - shared.autoStart = true; - shared._protected = true; - } - return Ticker._shared; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Ticker, "system", { - /** - * The system ticker instance used by {@link PIXI.InteractionManager} and by - * {@link PIXI.BasePrepare} for core timing functionality that shouldn't usually need to be paused, - * unlike the `shared` ticker which drives visual animations and rendering which may want to be paused. - * - * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance. - * @member {PIXI.Ticker} - * @static - */ - get: function () { - if (!Ticker._system) { - var system = Ticker._system = new Ticker(); - system.autoStart = true; - system._protected = true; - } - return Ticker._system; - }, - enumerable: false, - configurable: true - }); - return Ticker; - }()); - - /** - * Middleware for for Application Ticker. - * @example - * import {TickerPlugin} from '@pixi/ticker'; - * import {Application} from '@pixi/app'; - * import {extensions} from '@pixi/extensions'; - * extensions.add(TickerPlugin); - * @class - * @memberof PIXI - */ - var TickerPlugin = /** @class */ (function () { - function TickerPlugin() { - } - /** - * Initialize the plugin with scope of application instance - * @static - * @private - * @param {object} [options] - See application options - */ - TickerPlugin.init = function (options) { - var _this = this; - // Set default - options = Object.assign({ - autoStart: true, - sharedTicker: false, - }, options); - // Create ticker setter - Object.defineProperty(this, 'ticker', { - set: function (ticker) { - if (this._ticker) { - this._ticker.remove(this.render, this); - } - this._ticker = ticker; - if (ticker) { - ticker.add(this.render, this, exports.UPDATE_PRIORITY.LOW); - } - }, - get: function () { - return this._ticker; - }, - }); - /** - * Convenience method for stopping the render. - * @method - * @memberof PIXI.Application - * @instance - */ - this.stop = function () { - _this._ticker.stop(); - }; - /** - * Convenience method for starting the render. - * @method - * @memberof PIXI.Application - * @instance - */ - this.start = function () { - _this._ticker.start(); - }; - /** - * Internal reference to the ticker. - * @type {PIXI.Ticker} - * @name _ticker - * @memberof PIXI.Application# - * @private - */ - this._ticker = null; - /** - * Ticker for doing render updates. - * @type {PIXI.Ticker} - * @name ticker - * @memberof PIXI.Application# - * @default PIXI.Ticker.shared - */ - this.ticker = options.sharedTicker ? Ticker.shared : new Ticker(); - // Start the rendering - if (options.autoStart) { - this.start(); - } - }; - /** - * Clean up the ticker, scoped to application. - * @static - * @private - */ - TickerPlugin.destroy = function () { - if (this._ticker) { - var oldTicker = this._ticker; - this.ticker = null; - oldTicker.destroy(); - } - }; - /** @ignore */ - TickerPlugin.extension = exports.ExtensionType.Application; - return TickerPlugin; - }()); - - /*! - * @pixi/core - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/core is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * The maximum support for using WebGL. If a device does not - * support WebGL version, for instance WebGL 2, it will still - * attempt to fallback support to WebGL 1. If you want to - * explicitly remove feature support to target a more stable - * baseline, prefer a lower environment. - * - * Due to {@link https://bugs.chromium.org/p/chromium/issues/detail?id=934823|bug in chromium} - * we disable webgl2 by default for all non-apple mobile devices. - * @static - * @name PREFER_ENV - * @memberof PIXI.settings - * @type {number} - * @default PIXI.ENV.WEBGL2 - */ - settings.PREFER_ENV = isMobile.any ? exports.ENV.WEBGL : exports.ENV.WEBGL2; - /** - * If set to `true`, *only* Textures and BaseTexture objects stored - * in the caches ({@link PIXI.utils.TextureCache TextureCache} and - * {@link PIXI.utils.BaseTextureCache BaseTextureCache}) can be - * used when calling {@link PIXI.Texture.from Texture.from} or - * {@link PIXI.BaseTexture.from BaseTexture.from}. - * Otherwise, these `from` calls throw an exception. Using this property - * can be useful if you want to enforce preloading all assets with - * {@link PIXI.Loader Loader}. - * @static - * @name STRICT_TEXTURE_CACHE - * @memberof PIXI.settings - * @type {boolean} - * @default false - */ - settings.STRICT_TEXTURE_CACHE = false; - - /** - * Collection of installed resource types, class must extend {@link PIXI.Resource}. - * @example - * class CustomResource extends PIXI.Resource { - * // MUST have source, options constructor signature - * // for auto-detected resources to be created. - * constructor(source, options) { - * super(); - * } - * upload(renderer, baseTexture, glTexture) { - * // upload with GL - * return true; - * } - * // used to auto-detect resource - * static test(source, extension) { - * return extension === 'xyz'|| source instanceof SomeClass; - * } - * } - * // Install the new resource type - * PIXI.INSTALLED.push(CustomResource); - * @memberof PIXI - * @type {Array} - * @static - * @readonly - */ - var INSTALLED = []; - /** - * Create a resource element from a single source element. This - * auto-detects which type of resource to create. All resources that - * are auto-detectable must have a static `test` method and a constructor - * with the arguments `(source, options?)`. Currently, the supported - * resources for auto-detection include: - * - {@link PIXI.ImageResource} - * - {@link PIXI.CanvasResource} - * - {@link PIXI.VideoResource} - * - {@link PIXI.SVGResource} - * - {@link PIXI.BufferResource} - * @static - * @memberof PIXI - * @function autoDetectResource - * @param {string|*} source - Resource source, this can be the URL to the resource, - * a typed-array (for BufferResource), HTMLVideoElement, SVG data-uri - * or any other resource that can be auto-detected. If not resource is - * detected, it's assumed to be an ImageResource. - * @param {object} [options] - Pass-through options to use for Resource - * @param {number} [options.width] - Width of BufferResource or SVG rasterization - * @param {number} [options.height] - Height of BufferResource or SVG rasterization - * @param {boolean} [options.autoLoad=true] - Image, SVG and Video flag to start loading - * @param {number} [options.scale=1] - SVG source scale. Overridden by width, height - * @param {boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - Image option to create Bitmap object - * @param {boolean} [options.crossorigin=true] - Image and Video option to set crossOrigin - * @param {boolean} [options.autoPlay=true] - Video option to start playing video immediately - * @param {number} [options.updateFPS=0] - Video option to update how many times a second the - * texture should be updated from the video. Leave at 0 to update at every render - * @returns {PIXI.Resource} The created resource. - */ - function autoDetectResource(source, options) { - if (!source) { - return null; - } - var extension = ''; - if (typeof source === 'string') { - // search for file extension: period, 3-4 chars, then ?, # or EOL - var result = (/\.(\w{3,4})(?:$|\?|#)/i).exec(source); - if (result) { - extension = result[1].toLowerCase(); - } - } - for (var i = INSTALLED.length - 1; i >= 0; --i) { - var ResourcePlugin = INSTALLED[i]; - if (ResourcePlugin.test && ResourcePlugin.test(source, extension)) { - return new ResourcePlugin(source, options); - } - } - throw new Error('Unrecognized source type to auto-detect Resource'); - } - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$i = function(d, b) { - extendStatics$i = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$i(d, b); - }; - - function __extends$i(d, b) { - extendStatics$i(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var __assign = function() { - __assign = Object.assign || function __assign(t) { - var arguments$1 = arguments; - - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments$1[i]; - for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p)) { t[p] = s[p]; } } - } - return t; - }; - return __assign.apply(this, arguments); - }; - - function __rest(s, e) { - var t = {}; - for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - { t[p] = s[p]; } } - if (s != null && typeof Object.getOwnPropertySymbols === "function") - { for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - { t[p[i]] = s[p[i]]; } - } } - return t; - } - - /** - * Base resource class for textures that manages validation and uploading, depending on its type. - * - * Uploading of a base texture to the GPU is required. - * @memberof PIXI - */ - var Resource = /** @class */ (function () { - /** - * @param width - Width of the resource - * @param height - Height of the resource - */ - function Resource(width, height) { - if (width === void 0) { width = 0; } - if (height === void 0) { height = 0; } - this._width = width; - this._height = height; - this.destroyed = false; - this.internal = false; - this.onResize = new Runner('setRealSize'); - this.onUpdate = new Runner('update'); - this.onError = new Runner('onError'); - } - /** - * Bind to a parent BaseTexture - * @param baseTexture - Parent texture - */ - Resource.prototype.bind = function (baseTexture) { - this.onResize.add(baseTexture); - this.onUpdate.add(baseTexture); - this.onError.add(baseTexture); - // Call a resize immediate if we already - // have the width and height of the resource - if (this._width || this._height) { - this.onResize.emit(this._width, this._height); - } - }; - /** - * Unbind to a parent BaseTexture - * @param baseTexture - Parent texture - */ - Resource.prototype.unbind = function (baseTexture) { - this.onResize.remove(baseTexture); - this.onUpdate.remove(baseTexture); - this.onError.remove(baseTexture); - }; - /** - * Trigger a resize event - * @param width - X dimension - * @param height - Y dimension - */ - Resource.prototype.resize = function (width, height) { - if (width !== this._width || height !== this._height) { - this._width = width; - this._height = height; - this.onResize.emit(width, height); - } - }; - Object.defineProperty(Resource.prototype, "valid", { - /** - * Has been validated - * @readonly - */ - get: function () { - return !!this._width && !!this._height; - }, - enumerable: false, - configurable: true - }); - /** Has been updated trigger event. */ - Resource.prototype.update = function () { - if (!this.destroyed) { - this.onUpdate.emit(); - } - }; - /** - * This can be overridden to start preloading a resource - * or do any other prepare step. - * @protected - * @returns Handle the validate event - */ - Resource.prototype.load = function () { - return Promise.resolve(this); - }; - Object.defineProperty(Resource.prototype, "width", { - /** - * The width of the resource. - * @readonly - */ - get: function () { - return this._width; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Resource.prototype, "height", { - /** - * The height of the resource. - * @readonly - */ - get: function () { - return this._height; - }, - enumerable: false, - configurable: true - }); - /** - * Set the style, optional to override - * @param _renderer - yeah, renderer! - * @param _baseTexture - the texture - * @param _glTexture - texture instance for this webgl context - * @returns - `true` is success - */ - Resource.prototype.style = function (_renderer, _baseTexture, _glTexture) { - return false; - }; - /** Clean up anything, this happens when destroying is ready. */ - Resource.prototype.dispose = function () { - // override - }; - /** - * Call when destroying resource, unbind any BaseTexture object - * before calling this method, as reference counts are maintained - * internally. - */ - Resource.prototype.destroy = function () { - if (!this.destroyed) { - this.destroyed = true; - this.dispose(); - this.onError.removeAll(); - this.onError = null; - this.onResize.removeAll(); - this.onResize = null; - this.onUpdate.removeAll(); - this.onUpdate = null; - } - }; - /** - * Abstract, used to auto-detect resource type. - * @param {*} _source - The source object - * @param {string} _extension - The extension of source, if set - */ - Resource.test = function (_source, _extension) { - return false; - }; - return Resource; - }()); - - /** - * @interface SharedArrayBuffer - */ - /** - * Buffer resource with data of typed array. - * @memberof PIXI - */ - var BufferResource = /** @class */ (function (_super) { - __extends$i(BufferResource, _super); - /** - * @param source - Source buffer - * @param options - Options - * @param {number} options.width - Width of the texture - * @param {number} options.height - Height of the texture - */ - function BufferResource(source, options) { - var _this = this; - var _a = options || {}, width = _a.width, height = _a.height; - if (!width || !height) { - throw new Error('BufferResource width or height invalid'); - } - _this = _super.call(this, width, height) || this; - _this.data = source; - return _this; - } - /** - * Upload the texture to the GPU. - * @param renderer - Upload to the renderer - * @param baseTexture - Reference to parent texture - * @param glTexture - glTexture - * @returns - true is success - */ - BufferResource.prototype.upload = function (renderer, baseTexture, glTexture) { - var gl = renderer.gl; - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === exports.ALPHA_MODES.UNPACK); - var width = baseTexture.realWidth; - var height = baseTexture.realHeight; - if (glTexture.width === width && glTexture.height === height) { - gl.texSubImage2D(baseTexture.target, 0, 0, 0, width, height, baseTexture.format, glTexture.type, this.data); - } - else { - glTexture.width = width; - glTexture.height = height; - gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, width, height, 0, baseTexture.format, glTexture.type, this.data); - } - return true; - }; - /** Destroy and don't use after this. */ - BufferResource.prototype.dispose = function () { - this.data = null; - }; - /** - * Used to auto-detect the type of resource. - * @param {*} source - The source object - * @returns {boolean} `true` if - */ - BufferResource.test = function (source) { - return source instanceof Float32Array - || source instanceof Uint8Array - || source instanceof Uint32Array; - }; - return BufferResource; - }(Resource)); - - var defaultBufferOptions = { - scaleMode: exports.SCALE_MODES.NEAREST, - format: exports.FORMATS.RGBA, - alphaMode: exports.ALPHA_MODES.NPM, - }; - /** - * A Texture stores the information that represents an image. - * All textures have a base texture, which contains information about the source. - * Therefore you can have many textures all using a single BaseTexture - * @memberof PIXI - * @typeParam R - The BaseTexture's Resource type. - * @typeParam RO - The options for constructing resource. - */ - var BaseTexture = /** @class */ (function (_super) { - __extends$i(BaseTexture, _super); - /** - * @param {PIXI.Resource|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} [resource=null] - - * The current resource to use, for things that aren't Resource objects, will be converted - * into a Resource. - * @param options - Collection of options - * @param {PIXI.MIPMAP_MODES} [options.mipmap=PIXI.settings.MIPMAP_TEXTURES] - If mipmapping is enabled for texture - * @param {number} [options.anisotropicLevel=PIXI.settings.ANISOTROPIC_LEVEL] - Anisotropic filtering level of texture - * @param {PIXI.WRAP_MODES} [options.wrapMode=PIXI.settings.WRAP_MODE] - Wrap mode for textures - * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.settings.SCALE_MODE] - Default scale mode, linear, nearest - * @param {PIXI.FORMATS} [options.format=PIXI.FORMATS.RGBA] - GL format type - * @param {PIXI.TYPES} [options.type=PIXI.TYPES.UNSIGNED_BYTE] - GL data type - * @param {PIXI.TARGETS} [options.target=PIXI.TARGETS.TEXTURE_2D] - GL texture target - * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Pre multiply the image alpha - * @param {number} [options.width=0] - Width of the texture - * @param {number} [options.height=0] - Height of the texture - * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - Resolution of the base texture - * @param {object} [options.resourceOptions] - Optional resource options, - * see {@link PIXI.autoDetectResource autoDetectResource} - */ - function BaseTexture(resource, options) { - if (resource === void 0) { resource = null; } - if (options === void 0) { options = null; } - var _this = _super.call(this) || this; - options = options || {}; - var alphaMode = options.alphaMode, mipmap = options.mipmap, anisotropicLevel = options.anisotropicLevel, scaleMode = options.scaleMode, width = options.width, height = options.height, wrapMode = options.wrapMode, format = options.format, type = options.type, target = options.target, resolution = options.resolution, resourceOptions = options.resourceOptions; - // Convert the resource to a Resource object - if (resource && !(resource instanceof Resource)) { - resource = autoDetectResource(resource, resourceOptions); - resource.internal = true; - } - _this.resolution = resolution || settings.RESOLUTION; - _this.width = Math.round((width || 0) * _this.resolution) / _this.resolution; - _this.height = Math.round((height || 0) * _this.resolution) / _this.resolution; - _this._mipmap = mipmap !== undefined ? mipmap : settings.MIPMAP_TEXTURES; - _this.anisotropicLevel = anisotropicLevel !== undefined ? anisotropicLevel : settings.ANISOTROPIC_LEVEL; - _this._wrapMode = wrapMode || settings.WRAP_MODE; - _this._scaleMode = scaleMode !== undefined ? scaleMode : settings.SCALE_MODE; - _this.format = format || exports.FORMATS.RGBA; - _this.type = type || exports.TYPES.UNSIGNED_BYTE; - _this.target = target || exports.TARGETS.TEXTURE_2D; - _this.alphaMode = alphaMode !== undefined ? alphaMode : exports.ALPHA_MODES.UNPACK; - _this.uid = uid(); - _this.touched = 0; - _this.isPowerOfTwo = false; - _this._refreshPOT(); - _this._glTextures = {}; - _this.dirtyId = 0; - _this.dirtyStyleId = 0; - _this.cacheId = null; - _this.valid = width > 0 && height > 0; - _this.textureCacheIds = []; - _this.destroyed = false; - _this.resource = null; - _this._batchEnabled = 0; - _this._batchLocation = 0; - _this.parentTextureArray = null; - /** - * Fired when a not-immediately-available source finishes loading. - * @protected - * @event PIXI.BaseTexture#loaded - * @param {PIXI.BaseTexture} baseTexture - Resource loaded. - */ - /** - * Fired when a not-immediately-available source fails to load. - * @protected - * @event PIXI.BaseTexture#error - * @param {PIXI.BaseTexture} baseTexture - Resource errored. - * @param {ErrorEvent} event - Load error event. - */ - /** - * Fired when BaseTexture is updated. - * @protected - * @event PIXI.BaseTexture#loaded - * @param {PIXI.BaseTexture} baseTexture - Resource loaded. - */ - /** - * Fired when BaseTexture is updated. - * @protected - * @event PIXI.BaseTexture#update - * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated. - */ - /** - * Fired when BaseTexture is destroyed. - * @protected - * @event PIXI.BaseTexture#dispose - * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed. - */ - // Set the resource - _this.setResource(resource); - return _this; - } - Object.defineProperty(BaseTexture.prototype, "realWidth", { - /** - * Pixel width of the source of this texture - * @readonly - */ - get: function () { - return Math.round(this.width * this.resolution); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseTexture.prototype, "realHeight", { - /** - * Pixel height of the source of this texture - * @readonly - */ - get: function () { - return Math.round(this.height * this.resolution); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseTexture.prototype, "mipmap", { - /** - * Mipmap mode of the texture, affects downscaled images - * @default PIXI.settings.MIPMAP_TEXTURES - */ - get: function () { - return this._mipmap; - }, - set: function (value) { - if (this._mipmap !== value) { - this._mipmap = value; - this.dirtyStyleId++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseTexture.prototype, "scaleMode", { - /** - * The scale mode to apply when scaling this texture - * @default PIXI.settings.SCALE_MODE - */ - get: function () { - return this._scaleMode; - }, - set: function (value) { - if (this._scaleMode !== value) { - this._scaleMode = value; - this.dirtyStyleId++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseTexture.prototype, "wrapMode", { - /** - * How the texture wraps - * @default PIXI.settings.WRAP_MODE - */ - get: function () { - return this._wrapMode; - }, - set: function (value) { - if (this._wrapMode !== value) { - this._wrapMode = value; - this.dirtyStyleId++; - } - }, - enumerable: false, - configurable: true - }); - /** - * Changes style options of BaseTexture - * @param scaleMode - Pixi scalemode - * @param mipmap - enable mipmaps - * @returns - this - */ - BaseTexture.prototype.setStyle = function (scaleMode, mipmap) { - var dirty; - if (scaleMode !== undefined && scaleMode !== this.scaleMode) { - this.scaleMode = scaleMode; - dirty = true; - } - if (mipmap !== undefined && mipmap !== this.mipmap) { - this.mipmap = mipmap; - dirty = true; - } - if (dirty) { - this.dirtyStyleId++; - } - return this; - }; - /** - * Changes w/h/resolution. Texture becomes valid if width and height are greater than zero. - * @param desiredWidth - Desired visual width - * @param desiredHeight - Desired visual height - * @param resolution - Optionally set resolution - * @returns - this - */ - BaseTexture.prototype.setSize = function (desiredWidth, desiredHeight, resolution) { - resolution = resolution || this.resolution; - return this.setRealSize(desiredWidth * resolution, desiredHeight * resolution, resolution); - }; - /** - * Sets real size of baseTexture, preserves current resolution. - * @param realWidth - Full rendered width - * @param realHeight - Full rendered height - * @param resolution - Optionally set resolution - * @returns - this - */ - BaseTexture.prototype.setRealSize = function (realWidth, realHeight, resolution) { - this.resolution = resolution || this.resolution; - this.width = Math.round(realWidth) / this.resolution; - this.height = Math.round(realHeight) / this.resolution; - this._refreshPOT(); - this.update(); - return this; - }; - /** - * Refresh check for isPowerOfTwo texture based on size - * @private - */ - BaseTexture.prototype._refreshPOT = function () { - this.isPowerOfTwo = isPow2(this.realWidth) && isPow2(this.realHeight); - }; - /** - * Changes resolution - * @param resolution - res - * @returns - this - */ - BaseTexture.prototype.setResolution = function (resolution) { - var oldResolution = this.resolution; - if (oldResolution === resolution) { - return this; - } - this.resolution = resolution; - if (this.valid) { - this.width = Math.round(this.width * oldResolution) / resolution; - this.height = Math.round(this.height * oldResolution) / resolution; - this.emit('update', this); - } - this._refreshPOT(); - return this; - }; - /** - * Sets the resource if it wasn't set. Throws error if resource already present - * @param resource - that is managing this BaseTexture - * @returns - this - */ - BaseTexture.prototype.setResource = function (resource) { - if (this.resource === resource) { - return this; - } - if (this.resource) { - throw new Error('Resource can be set only once'); - } - resource.bind(this); - this.resource = resource; - return this; - }; - /** Invalidates the object. Texture becomes valid if width and height are greater than zero. */ - BaseTexture.prototype.update = function () { - if (!this.valid) { - if (this.width > 0 && this.height > 0) { - this.valid = true; - this.emit('loaded', this); - this.emit('update', this); - } - } - else { - this.dirtyId++; - this.dirtyStyleId++; - this.emit('update', this); - } - }; - /** - * Handle errors with resources. - * @private - * @param event - Error event emitted. - */ - BaseTexture.prototype.onError = function (event) { - this.emit('error', this, event); - }; - /** - * Destroys this base texture. - * The method stops if resource doesn't want this texture to be destroyed. - * Removes texture from all caches. - */ - BaseTexture.prototype.destroy = function () { - // remove and destroy the resource - if (this.resource) { - this.resource.unbind(this); - // only destroy resourced created internally - if (this.resource.internal) { - this.resource.destroy(); - } - this.resource = null; - } - if (this.cacheId) { - delete BaseTextureCache[this.cacheId]; - delete TextureCache[this.cacheId]; - this.cacheId = null; - } - // finally let the WebGL renderer know.. - this.dispose(); - BaseTexture.removeFromCache(this); - this.textureCacheIds = null; - this.destroyed = true; - }; - /** - * Frees the texture from WebGL memory without destroying this texture object. - * This means you can still use the texture later which will upload it to GPU - * memory again. - * @fires PIXI.BaseTexture#dispose - */ - BaseTexture.prototype.dispose = function () { - this.emit('dispose', this); - }; - /** Utility function for BaseTexture|Texture cast. */ - BaseTexture.prototype.castToBaseTexture = function () { - return this; - }; - /** - * Helper function that creates a base texture based on the source you provide. - * The source can be - image url, image element, canvas element. If the - * source is an image url or an image element and not in the base texture - * cache, it will be created and loaded. - * @static - * @param {string|string[]|HTMLImageElement|HTMLCanvasElement|SVGElement|HTMLVideoElement} source - The - * source to create base texture from. - * @param options - See {@link PIXI.BaseTexture}'s constructor for options. - * @param {string} [options.pixiIdPrefix=pixiid] - If a source has no id, this is the prefix of the generated id - * @param {boolean} [strict] - Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}. - * @returns {PIXI.BaseTexture} The new base texture. - */ - BaseTexture.from = function (source, options, strict) { - if (strict === void 0) { strict = settings.STRICT_TEXTURE_CACHE; } - var isFrame = typeof source === 'string'; - var cacheId = null; - if (isFrame) { - cacheId = source; - } - else { - if (!source._pixiId) { - var prefix = (options && options.pixiIdPrefix) || 'pixiid'; - source._pixiId = prefix + "_" + uid(); - } - cacheId = source._pixiId; - } - var baseTexture = BaseTextureCache[cacheId]; - // Strict-mode rejects invalid cacheIds - if (isFrame && strict && !baseTexture) { - throw new Error("The cacheId \"" + cacheId + "\" does not exist in BaseTextureCache."); - } - if (!baseTexture) { - baseTexture = new BaseTexture(source, options); - baseTexture.cacheId = cacheId; - BaseTexture.addToCache(baseTexture, cacheId); - } - return baseTexture; - }; - /** - * Create a new BaseTexture with a BufferResource from a Float32Array. - * RGBA values are floats from 0 to 1. - * @param {Float32Array|Uint8Array} buffer - The optional array to use, if no data - * is provided, a new Float32Array is created. - * @param width - Width of the resource - * @param height - Height of the resource - * @param options - See {@link PIXI.BaseTexture}'s constructor for options. - * Default properties are different from the constructor's defaults. - * @param {PIXI.FORMATS} [options.format=PIXI.FORMATS.RGBA] - GL format type - * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.NPM] - Image alpha, not premultiplied by default - * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.SCALE_MODES.NEAREST] - Scale mode, pixelating by default - * @returns - The resulting new BaseTexture - */ - BaseTexture.fromBuffer = function (buffer, width, height, options) { - buffer = buffer || new Float32Array(width * height * 4); - var resource = new BufferResource(buffer, { width: width, height: height }); - var type = buffer instanceof Float32Array ? exports.TYPES.FLOAT : exports.TYPES.UNSIGNED_BYTE; - return new BaseTexture(resource, Object.assign({}, defaultBufferOptions, options || { width: width, height: height, type: type })); - }; - /** - * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object. - * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache. - * @param {string} id - The id that the BaseTexture will be stored against. - */ - BaseTexture.addToCache = function (baseTexture, id) { - if (id) { - if (baseTexture.textureCacheIds.indexOf(id) === -1) { - baseTexture.textureCacheIds.push(id); - } - if (BaseTextureCache[id]) { - // eslint-disable-next-line no-console - console.warn("BaseTexture added to the cache with an id [" + id + "] that already had an entry"); - } - BaseTextureCache[id] = baseTexture; - } - }; - /** - * Remove a BaseTexture from the global BaseTextureCache. - * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself. - * @returns {PIXI.BaseTexture|null} The BaseTexture that was removed. - */ - BaseTexture.removeFromCache = function (baseTexture) { - if (typeof baseTexture === 'string') { - var baseTextureFromCache = BaseTextureCache[baseTexture]; - if (baseTextureFromCache) { - var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture); - if (index > -1) { - baseTextureFromCache.textureCacheIds.splice(index, 1); - } - delete BaseTextureCache[baseTexture]; - return baseTextureFromCache; - } - } - else if (baseTexture && baseTexture.textureCacheIds) { - for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) { - delete BaseTextureCache[baseTexture.textureCacheIds[i]]; - } - baseTexture.textureCacheIds.length = 0; - return baseTexture; - } - return null; - }; - /** Global number of the texture batch, used by multi-texture renderers. */ - BaseTexture._globalBatch = 0; - return BaseTexture; - }(eventemitter3)); - - /** - * Resource that can manage several resource (items) inside. - * All resources need to have the same pixel size. - * Parent class for CubeResource and ArrayResource - * @memberof PIXI - */ - var AbstractMultiResource = /** @class */ (function (_super) { - __extends$i(AbstractMultiResource, _super); - /** - * @param length - * @param options - Options to for Resource constructor - * @param {number} [options.width] - Width of the resource - * @param {number} [options.height] - Height of the resource - */ - function AbstractMultiResource(length, options) { - var _this = this; - var _a = options || {}, width = _a.width, height = _a.height; - _this = _super.call(this, width, height) || this; - _this.items = []; - _this.itemDirtyIds = []; - for (var i = 0; i < length; i++) { - var partTexture = new BaseTexture(); - _this.items.push(partTexture); - // -2 - first run of texture array upload - // -1 - texture item was allocated - // >=0 - texture item uploaded , in sync with items[i].dirtyId - _this.itemDirtyIds.push(-2); - } - _this.length = length; - _this._load = null; - _this.baseTexture = null; - return _this; - } - /** - * Used from ArrayResource and CubeResource constructors. - * @param resources - Can be resources, image elements, canvas, etc. , - * length should be same as constructor length - * @param options - Detect options for resources - */ - AbstractMultiResource.prototype.initFromArray = function (resources, options) { - for (var i = 0; i < this.length; i++) { - if (!resources[i]) { - continue; - } - if (resources[i].castToBaseTexture) { - this.addBaseTextureAt(resources[i].castToBaseTexture(), i); - } - else if (resources[i] instanceof Resource) { - this.addResourceAt(resources[i], i); - } - else { - this.addResourceAt(autoDetectResource(resources[i], options), i); - } - } - }; - /** Destroy this BaseImageResource. */ - AbstractMultiResource.prototype.dispose = function () { - for (var i = 0, len = this.length; i < len; i++) { - this.items[i].destroy(); - } - this.items = null; - this.itemDirtyIds = null; - this._load = null; - }; - /** - * Set a resource by ID - * @param resource - * @param index - Zero-based index of resource to set - * @returns - Instance for chaining - */ - AbstractMultiResource.prototype.addResourceAt = function (resource, index) { - if (!this.items[index]) { - throw new Error("Index " + index + " is out of bounds"); - } - // Inherit the first resource dimensions - if (resource.valid && !this.valid) { - this.resize(resource.width, resource.height); - } - this.items[index].setResource(resource); - return this; - }; - /** - * Set the parent base texture. - * @param baseTexture - */ - AbstractMultiResource.prototype.bind = function (baseTexture) { - if (this.baseTexture !== null) { - throw new Error('Only one base texture per TextureArray is allowed'); - } - _super.prototype.bind.call(this, baseTexture); - for (var i = 0; i < this.length; i++) { - this.items[i].parentTextureArray = baseTexture; - this.items[i].on('update', baseTexture.update, baseTexture); - } - }; - /** - * Unset the parent base texture. - * @param baseTexture - */ - AbstractMultiResource.prototype.unbind = function (baseTexture) { - _super.prototype.unbind.call(this, baseTexture); - for (var i = 0; i < this.length; i++) { - this.items[i].parentTextureArray = null; - this.items[i].off('update', baseTexture.update, baseTexture); - } - }; - /** - * Load all the resources simultaneously - * @returns - When load is resolved - */ - AbstractMultiResource.prototype.load = function () { - var _this = this; - if (this._load) { - return this._load; - } - var resources = this.items.map(function (item) { return item.resource; }).filter(function (item) { return item; }); - // TODO: also implement load part-by-part strategy - var promises = resources.map(function (item) { return item.load(); }); - this._load = Promise.all(promises) - .then(function () { - var _a = _this.items[0], realWidth = _a.realWidth, realHeight = _a.realHeight; - _this.resize(realWidth, realHeight); - return Promise.resolve(_this); - }); - return this._load; - }; - return AbstractMultiResource; - }(Resource)); - - /** - * A resource that contains a number of sources. - * @memberof PIXI - */ - var ArrayResource = /** @class */ (function (_super) { - __extends$i(ArrayResource, _super); - /** - * @param source - Number of items in array or the collection - * of image URLs to use. Can also be resources, image elements, canvas, etc. - * @param options - Options to apply to {@link PIXI.autoDetectResource} - * @param {number} [options.width] - Width of the resource - * @param {number} [options.height] - Height of the resource - */ - function ArrayResource(source, options) { - var _this = this; - var _a = options || {}, width = _a.width, height = _a.height; - var urls; - var length; - if (Array.isArray(source)) { - urls = source; - length = source.length; - } - else { - length = source; - } - _this = _super.call(this, length, { width: width, height: height }) || this; - if (urls) { - _this.initFromArray(urls, options); - } - return _this; - } - /** - * Set a baseTexture by ID, - * ArrayResource just takes resource from it, nothing more - * @param baseTexture - * @param index - Zero-based index of resource to set - * @returns - Instance for chaining - */ - ArrayResource.prototype.addBaseTextureAt = function (baseTexture, index) { - if (baseTexture.resource) { - this.addResourceAt(baseTexture.resource, index); - } - else { - throw new Error('ArrayResource does not support RenderTexture'); - } - return this; - }; - /** - * Add binding - * @param baseTexture - */ - ArrayResource.prototype.bind = function (baseTexture) { - _super.prototype.bind.call(this, baseTexture); - baseTexture.target = exports.TARGETS.TEXTURE_2D_ARRAY; - }; - /** - * Upload the resources to the GPU. - * @param renderer - * @param texture - * @param glTexture - * @returns - whether texture was uploaded - */ - ArrayResource.prototype.upload = function (renderer, texture, glTexture) { - var _a = this, length = _a.length, itemDirtyIds = _a.itemDirtyIds, items = _a.items; - var gl = renderer.gl; - if (glTexture.dirtyId < 0) { - gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, glTexture.internalFormat, this._width, this._height, length, 0, texture.format, glTexture.type, null); - } - for (var i = 0; i < length; i++) { - var item = items[i]; - if (itemDirtyIds[i] < item.dirtyId) { - itemDirtyIds[i] = item.dirtyId; - if (item.valid) { - gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, 0, // xoffset - 0, // yoffset - i, // zoffset - item.resource.width, item.resource.height, 1, texture.format, glTexture.type, item.resource.source); - } - } - } - return true; - }; - return ArrayResource; - }(AbstractMultiResource)); - - /** - * Base for all the image/canvas resources. - * @memberof PIXI - */ - var BaseImageResource = /** @class */ (function (_super) { - __extends$i(BaseImageResource, _super); - /** - * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} source - */ - function BaseImageResource(source) { - var _this = this; - var sourceAny = source; - var width = sourceAny.naturalWidth || sourceAny.videoWidth || sourceAny.width; - var height = sourceAny.naturalHeight || sourceAny.videoHeight || sourceAny.height; - _this = _super.call(this, width, height) || this; - _this.source = source; - _this.noSubImage = false; - return _this; - } - /** - * Set cross origin based detecting the url and the crossorigin - * @param element - Element to apply crossOrigin - * @param url - URL to check - * @param crossorigin - Cross origin value to use - */ - BaseImageResource.crossOrigin = function (element, url, crossorigin) { - if (crossorigin === undefined && url.indexOf('data:') !== 0) { - element.crossOrigin = determineCrossOrigin(url); - } - else if (crossorigin !== false) { - element.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; - } - }; - /** - * Upload the texture to the GPU. - * @param renderer - Upload to the renderer - * @param baseTexture - Reference to parent texture - * @param glTexture - * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} [source] - (optional) - * @returns - true is success - */ - BaseImageResource.prototype.upload = function (renderer, baseTexture, glTexture, source) { - var gl = renderer.gl; - var width = baseTexture.realWidth; - var height = baseTexture.realHeight; - source = source || this.source; - if (source instanceof HTMLImageElement) { - if (!source.complete || source.naturalWidth === 0) { - return false; - } - } - else if (source instanceof HTMLVideoElement) { - if (source.readyState <= 1) { - return false; - } - } - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === exports.ALPHA_MODES.UNPACK); - if (!this.noSubImage - && baseTexture.target === gl.TEXTURE_2D - && glTexture.width === width - && glTexture.height === height) { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, baseTexture.format, glTexture.type, source); - } - else { - glTexture.width = width; - glTexture.height = height; - gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, baseTexture.format, glTexture.type, source); - } - return true; - }; - /** - * Checks if source width/height was changed, resize can cause extra baseTexture update. - * Triggers one update in any case. - */ - BaseImageResource.prototype.update = function () { - if (this.destroyed) { - return; - } - var source = this.source; - var width = source.naturalWidth || source.videoWidth || source.width; - var height = source.naturalHeight || source.videoHeight || source.height; - this.resize(width, height); - _super.prototype.update.call(this); - }; - /** Destroy this {@link BaseImageResource} */ - BaseImageResource.prototype.dispose = function () { - this.source = null; - }; - return BaseImageResource; - }(Resource)); - - /** - * @interface OffscreenCanvas - */ - /** - * Resource type for HTMLCanvasElement. - * @memberof PIXI - */ - var CanvasResource = /** @class */ (function (_super) { - __extends$i(CanvasResource, _super); - /** - * @param source - Canvas element to use - */ - // eslint-disable-next-line @typescript-eslint/no-useless-constructor - function CanvasResource(source) { - return _super.call(this, source) || this; - } - /** - * Used to auto-detect the type of resource. - * @param {*} source - The source object - * @returns {boolean} `true` if source is HTMLCanvasElement or OffscreenCanvas - */ - CanvasResource.test = function (source) { - var OffscreenCanvas = globalThis.OffscreenCanvas; - // Check for browsers that don't yet support OffscreenCanvas - if (OffscreenCanvas && source instanceof OffscreenCanvas) { - return true; - } - return globalThis.HTMLCanvasElement && source instanceof HTMLCanvasElement; - }; - return CanvasResource; - }(BaseImageResource)); - - /** - * Resource for a CubeTexture which contains six resources. - * @memberof PIXI - */ - var CubeResource = /** @class */ (function (_super) { - __extends$i(CubeResource, _super); - /** - * @param {Array} [source] - Collection of URLs or resources - * to use as the sides of the cube. - * @param options - ImageResource options - * @param {number} [options.width] - Width of resource - * @param {number} [options.height] - Height of resource - * @param {number} [options.autoLoad=true] - Whether to auto-load resources - * @param {number} [options.linkBaseTexture=true] - In case BaseTextures are supplied, - * whether to copy them or use - */ - function CubeResource(source, options) { - var _this = this; - var _a = options || {}, width = _a.width, height = _a.height, autoLoad = _a.autoLoad, linkBaseTexture = _a.linkBaseTexture; - if (source && source.length !== CubeResource.SIDES) { - throw new Error("Invalid length. Got " + source.length + ", expected 6"); - } - _this = _super.call(this, 6, { width: width, height: height }) || this; - for (var i = 0; i < CubeResource.SIDES; i++) { - _this.items[i].target = exports.TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + i; - } - _this.linkBaseTexture = linkBaseTexture !== false; - if (source) { - _this.initFromArray(source, options); - } - if (autoLoad !== false) { - _this.load(); - } - return _this; - } - /** - * Add binding. - * @param baseTexture - parent base texture - */ - CubeResource.prototype.bind = function (baseTexture) { - _super.prototype.bind.call(this, baseTexture); - baseTexture.target = exports.TARGETS.TEXTURE_CUBE_MAP; - }; - CubeResource.prototype.addBaseTextureAt = function (baseTexture, index, linkBaseTexture) { - if (!this.items[index]) { - throw new Error("Index " + index + " is out of bounds"); - } - if (!this.linkBaseTexture - || baseTexture.parentTextureArray - || Object.keys(baseTexture._glTextures).length > 0) { - // copy mode - if (baseTexture.resource) { - this.addResourceAt(baseTexture.resource, index); - } - else { - throw new Error("CubeResource does not support copying of renderTexture."); - } - } - else { - // link mode, the difficult one! - baseTexture.target = exports.TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + index; - baseTexture.parentTextureArray = this.baseTexture; - this.items[index] = baseTexture; - } - if (baseTexture.valid && !this.valid) { - this.resize(baseTexture.realWidth, baseTexture.realHeight); - } - this.items[index] = baseTexture; - return this; - }; - /** - * Upload the resource - * @param renderer - * @param _baseTexture - * @param glTexture - * @returns {boolean} true is success - */ - CubeResource.prototype.upload = function (renderer, _baseTexture, glTexture) { - var dirty = this.itemDirtyIds; - for (var i = 0; i < CubeResource.SIDES; i++) { - var side = this.items[i]; - if (dirty[i] < side.dirtyId || glTexture.dirtyId < _baseTexture.dirtyId) { - if (side.valid && side.resource) { - side.resource.upload(renderer, side, glTexture); - dirty[i] = side.dirtyId; - } - else if (dirty[i] < -1) { - // either item is not valid yet, either its a renderTexture - // allocate the memory - renderer.gl.texImage2D(side.target, 0, glTexture.internalFormat, _baseTexture.realWidth, _baseTexture.realHeight, 0, _baseTexture.format, glTexture.type, null); - dirty[i] = -1; - } - } - } - return true; - }; - /** - * Used to auto-detect the type of resource. - * @param {*} source - The source object - * @returns {boolean} `true` if source is an array of 6 elements - */ - CubeResource.test = function (source) { - return Array.isArray(source) && source.length === CubeResource.SIDES; - }; - /** Number of texture sides to store for CubeResources. */ - CubeResource.SIDES = 6; - return CubeResource; - }(AbstractMultiResource)); - - /** - * Resource type for HTMLImageElement. - * @memberof PIXI - */ - var ImageResource = /** @class */ (function (_super) { - __extends$i(ImageResource, _super); - /** - * @param source - image source or URL - * @param options - * @param {boolean} [options.autoLoad=true] - start loading process - * @param {boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - whether its required to create - * a bitmap before upload - * @param {boolean} [options.crossorigin=true] - Load image using cross origin - * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Premultiply image alpha in bitmap - */ - function ImageResource(source, options) { - var _this = this; - options = options || {}; - if (!(source instanceof HTMLImageElement)) { - var imageElement = new Image(); - BaseImageResource.crossOrigin(imageElement, source, options.crossorigin); - imageElement.src = source; - source = imageElement; - } - _this = _super.call(this, source) || this; - // FireFox 68, and possibly other versions, seems like setting the HTMLImageElement#width and #height - // to non-zero values before its loading completes if images are in a cache. - // Because of this, need to set the `_width` and the `_height` to zero to avoid uploading incomplete images. - // Please refer to the issue #5968 (https://github.com/pixijs/pixi.js/issues/5968). - if (!source.complete && !!_this._width && !!_this._height) { - _this._width = 0; - _this._height = 0; - } - _this.url = source.src; - _this._process = null; - _this.preserveBitmap = false; - _this.createBitmap = (options.createBitmap !== undefined - ? options.createBitmap : settings.CREATE_IMAGE_BITMAP) && !!globalThis.createImageBitmap; - _this.alphaMode = typeof options.alphaMode === 'number' ? options.alphaMode : null; - _this.bitmap = null; - _this._load = null; - if (options.autoLoad !== false) { - _this.load(); - } - return _this; - } - /** - * Returns a promise when image will be loaded and processed. - * @param createBitmap - whether process image into bitmap - */ - ImageResource.prototype.load = function (createBitmap) { - var _this = this; - if (this._load) { - return this._load; - } - if (createBitmap !== undefined) { - this.createBitmap = createBitmap; - } - this._load = new Promise(function (resolve, reject) { - var source = _this.source; - _this.url = source.src; - var completed = function () { - if (_this.destroyed) { - return; - } - source.onload = null; - source.onerror = null; - _this.resize(source.width, source.height); - _this._load = null; - if (_this.createBitmap) { - resolve(_this.process()); - } - else { - resolve(_this); - } - }; - if (source.complete && source.src) { - completed(); - } - else { - source.onload = completed; - source.onerror = function (event) { - // Avoids Promise freezing when resource broken - reject(event); - _this.onError.emit(event); - }; - } - }); - return this._load; - }; - /** - * Called when we need to convert image into BitmapImage. - * Can be called multiple times, real promise is cached inside. - * @returns - Cached promise to fill that bitmap - */ - ImageResource.prototype.process = function () { - var _this = this; - var source = this.source; - if (this._process !== null) { - return this._process; - } - if (this.bitmap !== null || !globalThis.createImageBitmap) { - return Promise.resolve(this); - } - var createImageBitmap = globalThis.createImageBitmap; - var cors = !source.crossOrigin || source.crossOrigin === 'anonymous'; - this._process = fetch(source.src, { - mode: cors ? 'cors' : 'no-cors' - }) - .then(function (r) { return r.blob(); }) - .then(function (blob) { return createImageBitmap(blob, 0, 0, source.width, source.height, { - premultiplyAlpha: _this.alphaMode === null || _this.alphaMode === exports.ALPHA_MODES.UNPACK - ? 'premultiply' : 'none', - }); }) - .then(function (bitmap) { - if (_this.destroyed) { - return Promise.reject(); - } - _this.bitmap = bitmap; - _this.update(); - _this._process = null; - return Promise.resolve(_this); - }); - return this._process; - }; - /** - * Upload the image resource to GPU. - * @param renderer - Renderer to upload to - * @param baseTexture - BaseTexture for this resource - * @param glTexture - GLTexture to use - * @returns {boolean} true is success - */ - ImageResource.prototype.upload = function (renderer, baseTexture, glTexture) { - if (typeof this.alphaMode === 'number') { - // bitmap stores unpack premultiply flag, we dont have to notify texImage2D about it - baseTexture.alphaMode = this.alphaMode; - } - if (!this.createBitmap) { - return _super.prototype.upload.call(this, renderer, baseTexture, glTexture); - } - if (!this.bitmap) { - // yeah, ignore the output - this.process(); - if (!this.bitmap) { - return false; - } - } - _super.prototype.upload.call(this, renderer, baseTexture, glTexture, this.bitmap); - if (!this.preserveBitmap) { - // checks if there are other renderers that possibly need this bitmap - var flag = true; - var glTextures = baseTexture._glTextures; - for (var key in glTextures) { - var otherTex = glTextures[key]; - if (otherTex !== glTexture && otherTex.dirtyId !== baseTexture.dirtyId) { - flag = false; - break; - } - } - if (flag) { - if (this.bitmap.close) { - this.bitmap.close(); - } - this.bitmap = null; - } - } - return true; - }; - /** Destroys this resource. */ - ImageResource.prototype.dispose = function () { - this.source.onload = null; - this.source.onerror = null; - _super.prototype.dispose.call(this); - if (this.bitmap) { - this.bitmap.close(); - this.bitmap = null; - } - this._process = null; - this._load = null; - }; - /** - * Used to auto-detect the type of resource. - * @param {*} source - The source object - * @returns {boolean} `true` if source is string or HTMLImageElement - */ - ImageResource.test = function (source) { - return typeof source === 'string' || source instanceof HTMLImageElement; - }; - return ImageResource; - }(BaseImageResource)); - - /** - * Resource type for SVG elements and graphics. - * @memberof PIXI - */ - var SVGResource = /** @class */ (function (_super) { - __extends$i(SVGResource, _super); - /** - * @param sourceBase64 - Base64 encoded SVG element or URL for SVG file. - * @param {object} [options] - Options to use - * @param {number} [options.scale=1] - Scale to apply to SVG. Overridden by... - * @param {number} [options.width] - Rasterize SVG this wide. Aspect ratio preserved if height not specified. - * @param {number} [options.height] - Rasterize SVG this high. Aspect ratio preserved if width not specified. - * @param {boolean} [options.autoLoad=true] - Start loading right away. - */ - function SVGResource(sourceBase64, options) { - var _this = this; - options = options || {}; - _this = _super.call(this, settings.ADAPTER.createCanvas()) || this; - _this._width = 0; - _this._height = 0; - _this.svg = sourceBase64; - _this.scale = options.scale || 1; - _this._overrideWidth = options.width; - _this._overrideHeight = options.height; - _this._resolve = null; - _this._crossorigin = options.crossorigin; - _this._load = null; - if (options.autoLoad !== false) { - _this.load(); - } - return _this; - } - SVGResource.prototype.load = function () { - var _this = this; - if (this._load) { - return this._load; - } - this._load = new Promise(function (resolve) { - // Save this until after load is finished - _this._resolve = function () { - _this.resize(_this.source.width, _this.source.height); - resolve(_this); - }; - // Convert SVG inline string to data-uri - if (SVGResource.SVG_XML.test(_this.svg.trim())) { - if (!btoa) { - throw new Error('Your browser doesn\'t support base64 conversions.'); - } - _this.svg = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(_this.svg))); - } - _this._loadSvg(); - }); - return this._load; - }; - /** Loads an SVG image from `imageUrl` or `data URL`. */ - SVGResource.prototype._loadSvg = function () { - var _this = this; - var tempImage = new Image(); - BaseImageResource.crossOrigin(tempImage, this.svg, this._crossorigin); - tempImage.src = this.svg; - tempImage.onerror = function (event) { - if (!_this._resolve) { - return; - } - tempImage.onerror = null; - _this.onError.emit(event); - }; - tempImage.onload = function () { - if (!_this._resolve) { - return; - } - var svgWidth = tempImage.width; - var svgHeight = tempImage.height; - if (!svgWidth || !svgHeight) { - throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.'); - } - // Set render size - var width = svgWidth * _this.scale; - var height = svgHeight * _this.scale; - if (_this._overrideWidth || _this._overrideHeight) { - width = _this._overrideWidth || _this._overrideHeight / svgHeight * svgWidth; - height = _this._overrideHeight || _this._overrideWidth / svgWidth * svgHeight; - } - width = Math.round(width); - height = Math.round(height); - // Create a canvas element - var canvas = _this.source; - canvas.width = width; - canvas.height = height; - canvas._pixiId = "canvas_" + uid(); - // Draw the Svg to the canvas - canvas - .getContext('2d') - .drawImage(tempImage, 0, 0, svgWidth, svgHeight, 0, 0, width, height); - _this._resolve(); - _this._resolve = null; - }; - }; - /** - * Get size from an svg string using a regular expression. - * @param svgString - a serialized svg element - * @returns - image extension - */ - SVGResource.getSize = function (svgString) { - var sizeMatch = SVGResource.SVG_SIZE.exec(svgString); - var size = {}; - if (sizeMatch) { - size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3])); - size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7])); - } - return size; - }; - /** Destroys this texture. */ - SVGResource.prototype.dispose = function () { - _super.prototype.dispose.call(this); - this._resolve = null; - this._crossorigin = null; - }; - /** - * Used to auto-detect the type of resource. - * @param {*} source - The source object - * @param {string} extension - The extension of source, if set - * @returns {boolean} - If the source is a SVG source or data file - */ - SVGResource.test = function (source, extension) { - // url file extension is SVG - return extension === 'svg' - // source is SVG data-uri - || (typeof source === 'string' && source.startsWith('data:image/svg+xml')) - // source is SVG inline - || (typeof source === 'string' && SVGResource.SVG_XML.test(source)); - }; - /** - * Regular expression for SVG XML document. - * @example <?xml version="1.0" encoding="utf-8" ?><!-- image/svg --><svg - * @readonly - */ - SVGResource.SVG_XML = /^(<\?xml[^?]+\?>)?\s*()]*-->)?\s*\]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len - return SVGResource; - }(BaseImageResource)); - - /** - * Resource type for {@code HTMLVideoElement}. - * @memberof PIXI - */ - var VideoResource = /** @class */ (function (_super) { - __extends$i(VideoResource, _super); - /** - * @param {HTMLVideoElement|object|string|Array} source - Video element to use. - * @param {object} [options] - Options to use - * @param {boolean} [options.autoLoad=true] - Start loading the video immediately - * @param {boolean} [options.autoPlay=true] - Start playing video immediately - * @param {number} [options.updateFPS=0] - How many times a second to update the texture from the video. - * Leave at 0 to update at every render. - * @param {boolean} [options.crossorigin=true] - Load image using cross origin - */ - function VideoResource(source, options) { - var _this = this; - options = options || {}; - if (!(source instanceof HTMLVideoElement)) { - var videoElement = document.createElement('video'); - // workaround for https://github.com/pixijs/pixi.js/issues/5996 - videoElement.setAttribute('preload', 'auto'); - videoElement.setAttribute('webkit-playsinline', ''); - videoElement.setAttribute('playsinline', ''); - if (typeof source === 'string') { - source = [source]; - } - var firstSrc = source[0].src || source[0]; - BaseImageResource.crossOrigin(videoElement, firstSrc, options.crossorigin); - // array of objects or strings - for (var i = 0; i < source.length; ++i) { - var sourceElement = document.createElement('source'); - var _a = source[i], src = _a.src, mime = _a.mime; - src = src || source[i]; - var baseSrc = src.split('?').shift().toLowerCase(); - var ext = baseSrc.slice(baseSrc.lastIndexOf('.') + 1); - mime = mime || VideoResource.MIME_TYPES[ext] || "video/" + ext; - sourceElement.src = src; - sourceElement.type = mime; - videoElement.appendChild(sourceElement); - } - // Override the source - source = videoElement; - } - _this = _super.call(this, source) || this; - _this.noSubImage = true; - _this._autoUpdate = true; - _this._isConnectedToTicker = false; - _this._updateFPS = options.updateFPS || 0; - _this._msToNextUpdate = 0; - _this.autoPlay = options.autoPlay !== false; - _this._load = null; - _this._resolve = null; - // Bind for listeners - _this._onCanPlay = _this._onCanPlay.bind(_this); - _this._onError = _this._onError.bind(_this); - if (options.autoLoad !== false) { - _this.load(); - } - return _this; - } - /** - * Trigger updating of the texture. - * @param _deltaTime - time delta since last tick - */ - VideoResource.prototype.update = function (_deltaTime) { - if (!this.destroyed) { - // account for if video has had its playbackRate changed - var elapsedMS = Ticker.shared.elapsedMS * this.source.playbackRate; - this._msToNextUpdate = Math.floor(this._msToNextUpdate - elapsedMS); - if (!this._updateFPS || this._msToNextUpdate <= 0) { - _super.prototype.update.call(this); - this._msToNextUpdate = this._updateFPS ? Math.floor(1000 / this._updateFPS) : 0; - } - } - }; - /** - * Start preloading the video resource. - * @returns {Promise} Handle the validate event - */ - VideoResource.prototype.load = function () { - var _this = this; - if (this._load) { - return this._load; - } - var source = this.source; - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) - && source.width && source.height) { - source.complete = true; - } - source.addEventListener('play', this._onPlayStart.bind(this)); - source.addEventListener('pause', this._onPlayStop.bind(this)); - if (!this._isSourceReady()) { - source.addEventListener('canplay', this._onCanPlay); - source.addEventListener('canplaythrough', this._onCanPlay); - source.addEventListener('error', this._onError, true); - } - else { - this._onCanPlay(); - } - this._load = new Promise(function (resolve) { - if (_this.valid) { - resolve(_this); - } - else { - _this._resolve = resolve; - source.load(); - } - }); - return this._load; - }; - /** - * Handle video error events. - * @param event - */ - VideoResource.prototype._onError = function (event) { - this.source.removeEventListener('error', this._onError, true); - this.onError.emit(event); - }; - /** - * Returns true if the underlying source is playing. - * @returns - True if playing. - */ - VideoResource.prototype._isSourcePlaying = function () { - var source = this.source; - return (!source.paused && !source.ended && this._isSourceReady()); - }; - /** - * Returns true if the underlying source is ready for playing. - * @returns - True if ready. - */ - VideoResource.prototype._isSourceReady = function () { - var source = this.source; - return source.readyState > 2; - }; - /** Runs the update loop when the video is ready to play. */ - VideoResource.prototype._onPlayStart = function () { - // Just in case the video has not received its can play even yet.. - if (!this.valid) { - this._onCanPlay(); - } - if (this.autoUpdate && !this._isConnectedToTicker) { - Ticker.shared.add(this.update, this); - this._isConnectedToTicker = true; - } - }; - /** Fired when a pause event is triggered, stops the update loop. */ - VideoResource.prototype._onPlayStop = function () { - if (this._isConnectedToTicker) { - Ticker.shared.remove(this.update, this); - this._isConnectedToTicker = false; - } - }; - /** Fired when the video is loaded and ready to play. */ - VideoResource.prototype._onCanPlay = function () { - var source = this.source; - source.removeEventListener('canplay', this._onCanPlay); - source.removeEventListener('canplaythrough', this._onCanPlay); - var valid = this.valid; - this.resize(source.videoWidth, source.videoHeight); - // prevent multiple loaded dispatches.. - if (!valid && this._resolve) { - this._resolve(this); - this._resolve = null; - } - if (this._isSourcePlaying()) { - this._onPlayStart(); - } - else if (this.autoPlay) { - source.play(); - } - }; - /** Destroys this texture. */ - VideoResource.prototype.dispose = function () { - if (this._isConnectedToTicker) { - Ticker.shared.remove(this.update, this); - this._isConnectedToTicker = false; - } - var source = this.source; - if (source) { - source.removeEventListener('error', this._onError, true); - source.pause(); - source.src = ''; - source.load(); - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(VideoResource.prototype, "autoUpdate", { - /** Should the base texture automatically update itself, set to true by default. */ - get: function () { - return this._autoUpdate; - }, - set: function (value) { - if (value !== this._autoUpdate) { - this._autoUpdate = value; - if (!this._autoUpdate && this._isConnectedToTicker) { - Ticker.shared.remove(this.update, this); - this._isConnectedToTicker = false; - } - else if (this._autoUpdate && !this._isConnectedToTicker && this._isSourcePlaying()) { - Ticker.shared.add(this.update, this); - this._isConnectedToTicker = true; - } - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(VideoResource.prototype, "updateFPS", { - /** - * How many times a second to update the texture from the video. Leave at 0 to update at every render. - * A lower fps can help performance, as updating the texture at 60fps on a 30ps video may not be efficient. - */ - get: function () { - return this._updateFPS; - }, - set: function (value) { - if (value !== this._updateFPS) { - this._updateFPS = value; - } - }, - enumerable: false, - configurable: true - }); - /** - * Used to auto-detect the type of resource. - * @param {*} source - The source object - * @param {string} extension - The extension of source, if set - * @returns {boolean} `true` if video source - */ - VideoResource.test = function (source, extension) { - return (globalThis.HTMLVideoElement && source instanceof HTMLVideoElement) - || VideoResource.TYPES.indexOf(extension) > -1; - }; - /** - * List of common video file extensions supported by VideoResource. - * @readonly - */ - VideoResource.TYPES = ['mp4', 'm4v', 'webm', 'ogg', 'ogv', 'h264', 'avi', 'mov']; - /** - * Map of video MIME types that can't be directly derived from file extensions. - * @readonly - */ - VideoResource.MIME_TYPES = { - ogv: 'video/ogg', - mov: 'video/quicktime', - m4v: 'video/mp4', - }; - return VideoResource; - }(BaseImageResource)); - - /** - * Resource type for ImageBitmap. - * @memberof PIXI - */ - var ImageBitmapResource = /** @class */ (function (_super) { - __extends$i(ImageBitmapResource, _super); - /** - * @param source - Image element to use - */ - // eslint-disable-next-line @typescript-eslint/no-useless-constructor - function ImageBitmapResource(source) { - return _super.call(this, source) || this; - } - /** - * Used to auto-detect the type of resource. - * @param {*} source - The source object - * @returns {boolean} `true` if source is an ImageBitmap - */ - ImageBitmapResource.test = function (source) { - return !!globalThis.createImageBitmap && typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap; - }; - return ImageBitmapResource; - }(BaseImageResource)); - - INSTALLED.push(ImageResource, ImageBitmapResource, CanvasResource, VideoResource, SVGResource, BufferResource, CubeResource, ArrayResource); - - var _resources = { - __proto__: null, - Resource: Resource, - BaseImageResource: BaseImageResource, - INSTALLED: INSTALLED, - autoDetectResource: autoDetectResource, - AbstractMultiResource: AbstractMultiResource, - ArrayResource: ArrayResource, - BufferResource: BufferResource, - CanvasResource: CanvasResource, - CubeResource: CubeResource, - ImageResource: ImageResource, - SVGResource: SVGResource, - VideoResource: VideoResource, - ImageBitmapResource: ImageBitmapResource - }; - - /** - * Resource type for DepthTexture. - * @memberof PIXI - */ - var DepthResource = /** @class */ (function (_super) { - __extends$i(DepthResource, _super); - function DepthResource() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * Upload the texture to the GPU. - * @param renderer - Upload to the renderer - * @param baseTexture - Reference to parent texture - * @param glTexture - glTexture - * @returns - true is success - */ - DepthResource.prototype.upload = function (renderer, baseTexture, glTexture) { - var gl = renderer.gl; - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === exports.ALPHA_MODES.UNPACK); - var width = baseTexture.realWidth; - var height = baseTexture.realHeight; - if (glTexture.width === width && glTexture.height === height) { - gl.texSubImage2D(baseTexture.target, 0, 0, 0, width, height, baseTexture.format, glTexture.type, this.data); - } - else { - glTexture.width = width; - glTexture.height = height; - gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, width, height, 0, baseTexture.format, glTexture.type, this.data); - } - return true; - }; - return DepthResource; - }(BufferResource)); - - /** - * A framebuffer can be used to render contents off of the screen. {@link PIXI.BaseRenderTexture} uses - * one internally to render into itself. You can attach a depth or stencil buffer to a framebuffer. - * - * On WebGL 2 machines, shaders can output to multiple textures simultaneously with GLSL 300 ES. - * @memberof PIXI - */ - var Framebuffer = /** @class */ (function () { - /** - * @param width - Width of the frame buffer - * @param height - Height of the frame buffer - */ - function Framebuffer(width, height) { - this.width = Math.round(width || 100); - this.height = Math.round(height || 100); - this.stencil = false; - this.depth = false; - this.dirtyId = 0; - this.dirtyFormat = 0; - this.dirtySize = 0; - this.depthTexture = null; - this.colorTextures = []; - this.glFramebuffers = {}; - this.disposeRunner = new Runner('disposeFramebuffer'); - this.multisample = exports.MSAA_QUALITY.NONE; - } - Object.defineProperty(Framebuffer.prototype, "colorTexture", { - /** - * Reference to the colorTexture. - * @readonly - */ - get: function () { - return this.colorTextures[0]; - }, - enumerable: false, - configurable: true - }); - /** - * Add texture to the colorTexture array. - * @param index - Index of the array to add the texture to - * @param texture - Texture to add to the array - */ - Framebuffer.prototype.addColorTexture = function (index, texture) { - if (index === void 0) { index = 0; } - // TODO add some validation to the texture - same width / height etc? - this.colorTextures[index] = texture || new BaseTexture(null, { - scaleMode: exports.SCALE_MODES.NEAREST, - resolution: 1, - mipmap: exports.MIPMAP_MODES.OFF, - width: this.width, - height: this.height, - }); - this.dirtyId++; - this.dirtyFormat++; - return this; - }; - /** - * Add a depth texture to the frame buffer. - * @param texture - Texture to add. - */ - Framebuffer.prototype.addDepthTexture = function (texture) { - /* eslint-disable max-len */ - this.depthTexture = texture || new BaseTexture(new DepthResource(null, { width: this.width, height: this.height }), { - scaleMode: exports.SCALE_MODES.NEAREST, - resolution: 1, - width: this.width, - height: this.height, - mipmap: exports.MIPMAP_MODES.OFF, - format: exports.FORMATS.DEPTH_COMPONENT, - type: exports.TYPES.UNSIGNED_SHORT, - }); - this.dirtyId++; - this.dirtyFormat++; - return this; - }; - /** Enable depth on the frame buffer. */ - Framebuffer.prototype.enableDepth = function () { - this.depth = true; - this.dirtyId++; - this.dirtyFormat++; - return this; - }; - /** Enable stencil on the frame buffer. */ - Framebuffer.prototype.enableStencil = function () { - this.stencil = true; - this.dirtyId++; - this.dirtyFormat++; - return this; - }; - /** - * Resize the frame buffer - * @param width - Width of the frame buffer to resize to - * @param height - Height of the frame buffer to resize to - */ - Framebuffer.prototype.resize = function (width, height) { - width = Math.round(width); - height = Math.round(height); - if (width === this.width && height === this.height) - { return; } - this.width = width; - this.height = height; - this.dirtyId++; - this.dirtySize++; - for (var i = 0; i < this.colorTextures.length; i++) { - var texture = this.colorTextures[i]; - var resolution = texture.resolution; - // take into account the fact the texture may have a different resolution.. - texture.setSize(width / resolution, height / resolution); - } - if (this.depthTexture) { - var resolution = this.depthTexture.resolution; - this.depthTexture.setSize(width / resolution, height / resolution); - } - }; - /** Disposes WebGL resources that are connected to this geometry. */ - Framebuffer.prototype.dispose = function () { - this.disposeRunner.emit(this, false); - }; - /** Destroys and removes the depth texture added to this framebuffer. */ - Framebuffer.prototype.destroyDepthTexture = function () { - if (this.depthTexture) { - this.depthTexture.destroy(); - this.depthTexture = null; - ++this.dirtyId; - ++this.dirtyFormat; - } - }; - return Framebuffer; - }()); - - /** - * A BaseRenderTexture is a special texture that allows any PixiJS display object to be rendered to it. - * - * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded - * otherwise black rectangles will be drawn instead. - * - * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position - * and rotation of the given Display Objects is ignored. For example: - * - * ```js - * let renderer = PIXI.autoDetectRenderer(); - * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 800, height: 600 }); - * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); - * let sprite = PIXI.Sprite.from("spinObj_01.png"); - * - * sprite.position.x = 800/2; - * sprite.position.y = 600/2; - * sprite.anchor.x = 0.5; - * sprite.anchor.y = 0.5; - * - * renderer.render(sprite, {renderTexture}); - * ``` - * - * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 - * you can clear the transform - * - * ```js - * - * sprite.setTransform() - * - * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 100, height: 100 }); - * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); - * - * renderer.render(sprite, {renderTexture}); // Renders to center of RenderTexture - * ``` - * @memberof PIXI - */ - var BaseRenderTexture = /** @class */ (function (_super) { - __extends$i(BaseRenderTexture, _super); - /** - * @param options - * @param {number} [options.width=100] - The width of the base render texture. - * @param {number} [options.height=100] - The height of the base render texture. - * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} - * for possible values. - * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio - * of the texture being generated. - * @param {PIXI.MSAA_QUALITY} [options.multisample=PIXI.MSAA_QUALITY.NONE] - The number of samples of the frame buffer. - */ - function BaseRenderTexture(options) { - if (options === void 0) { options = {}; } - var _this = this; - if (typeof options === 'number') { - /* eslint-disable prefer-rest-params */ - // Backward compatibility of signature - var width = arguments[0]; - var height = arguments[1]; - var scaleMode = arguments[2]; - var resolution = arguments[3]; - options = { width: width, height: height, scaleMode: scaleMode, resolution: resolution }; - /* eslint-enable prefer-rest-params */ - } - options.width = options.width || 100; - options.height = options.height || 100; - options.multisample = options.multisample !== undefined ? options.multisample : exports.MSAA_QUALITY.NONE; - _this = _super.call(this, null, options) || this; - // Set defaults - _this.mipmap = exports.MIPMAP_MODES.OFF; - _this.valid = true; - _this.clearColor = [0, 0, 0, 0]; - _this.framebuffer = new Framebuffer(_this.realWidth, _this.realHeight) - .addColorTexture(0, _this); - _this.framebuffer.multisample = options.multisample; - // TODO - could this be added the systems? - _this.maskStack = []; - _this.filterStack = [{}]; - return _this; - } - /** - * Resizes the BaseRenderTexture. - * @param desiredWidth - The desired width to resize to. - * @param desiredHeight - The desired height to resize to. - */ - BaseRenderTexture.prototype.resize = function (desiredWidth, desiredHeight) { - this.framebuffer.resize(desiredWidth * this.resolution, desiredHeight * this.resolution); - this.setRealSize(this.framebuffer.width, this.framebuffer.height); - }; - /** - * Frees the texture and framebuffer from WebGL memory without destroying this texture object. - * This means you can still use the texture later which will upload it to GPU - * memory again. - * @fires PIXI.BaseTexture#dispose - */ - BaseRenderTexture.prototype.dispose = function () { - this.framebuffer.dispose(); - _super.prototype.dispose.call(this); - }; - /** Destroys this texture. */ - BaseRenderTexture.prototype.destroy = function () { - _super.prototype.destroy.call(this); - this.framebuffer.destroyDepthTexture(); - this.framebuffer = null; - }; - return BaseRenderTexture; - }(BaseTexture)); - - /** - * Stores a texture's frame in UV coordinates, in - * which everything lies in the rectangle `[(0,0), (1,0), - * (1,1), (0,1)]`. - * - * | Corner | Coordinates | - * |--------------|-------------| - * | Top-Left | `(x0,y0)` | - * | Top-Right | `(x1,y1)` | - * | Bottom-Right | `(x2,y2)` | - * | Bottom-Left | `(x3,y3)` | - * @protected - * @memberof PIXI - */ - var TextureUvs = /** @class */ (function () { - function TextureUvs() { - this.x0 = 0; - this.y0 = 0; - this.x1 = 1; - this.y1 = 0; - this.x2 = 1; - this.y2 = 1; - this.x3 = 0; - this.y3 = 1; - this.uvsFloat32 = new Float32Array(8); - } - /** - * Sets the texture Uvs based on the given frame information. - * @protected - * @param frame - The frame of the texture - * @param baseFrame - The base frame of the texture - * @param rotate - Rotation of frame, see {@link PIXI.groupD8} - */ - TextureUvs.prototype.set = function (frame, baseFrame, rotate) { - var tw = baseFrame.width; - var th = baseFrame.height; - if (rotate) { - // width and height div 2 div baseFrame size - var w2 = frame.width / 2 / tw; - var h2 = frame.height / 2 / th; - // coordinates of center - var cX = (frame.x / tw) + w2; - var cY = (frame.y / th) + h2; - rotate = groupD8.add(rotate, groupD8.NW); // NW is top-left corner - this.x0 = cX + (w2 * groupD8.uX(rotate)); - this.y0 = cY + (h2 * groupD8.uY(rotate)); - rotate = groupD8.add(rotate, 2); // rotate 90 degrees clockwise - this.x1 = cX + (w2 * groupD8.uX(rotate)); - this.y1 = cY + (h2 * groupD8.uY(rotate)); - rotate = groupD8.add(rotate, 2); - this.x2 = cX + (w2 * groupD8.uX(rotate)); - this.y2 = cY + (h2 * groupD8.uY(rotate)); - rotate = groupD8.add(rotate, 2); - this.x3 = cX + (w2 * groupD8.uX(rotate)); - this.y3 = cY + (h2 * groupD8.uY(rotate)); - } - else { - this.x0 = frame.x / tw; - this.y0 = frame.y / th; - this.x1 = (frame.x + frame.width) / tw; - this.y1 = frame.y / th; - this.x2 = (frame.x + frame.width) / tw; - this.y2 = (frame.y + frame.height) / th; - this.x3 = frame.x / tw; - this.y3 = (frame.y + frame.height) / th; - } - this.uvsFloat32[0] = this.x0; - this.uvsFloat32[1] = this.y0; - this.uvsFloat32[2] = this.x1; - this.uvsFloat32[3] = this.y1; - this.uvsFloat32[4] = this.x2; - this.uvsFloat32[5] = this.y2; - this.uvsFloat32[6] = this.x3; - this.uvsFloat32[7] = this.y3; - }; - TextureUvs.prototype.toString = function () { - return "[@pixi/core:TextureUvs " - + ("x0=" + this.x0 + " y0=" + this.y0 + " ") - + ("x1=" + this.x1 + " y1=" + this.y1 + " x2=" + this.x2 + " ") - + ("y2=" + this.y2 + " x3=" + this.x3 + " y3=" + this.y3) - + "]"; - }; - return TextureUvs; - }()); - - var DEFAULT_UVS = new TextureUvs(); - /** - * Used to remove listeners from WHITE and EMPTY Textures - * @ignore - */ - function removeAllHandlers(tex) { - tex.destroy = function _emptyDestroy() { }; - tex.on = function _emptyOn() { }; - tex.once = function _emptyOnce() { }; - tex.emit = function _emptyEmit() { }; - } - /** - * A texture stores the information that represents an image or part of an image. - * - * It cannot be added to the display list directly; instead use it as the texture for a Sprite. - * If no frame is provided for a texture, then the whole image is used. - * - * You can directly create a texture from an image and then reuse it multiple times like this : - * - * ```js - * let texture = PIXI.Texture.from('assets/image.png'); - * let sprite1 = new PIXI.Sprite(texture); - * let sprite2 = new PIXI.Sprite(texture); - * ``` - * - * If you didnt pass the texture frame to constructor, it enables `noFrame` mode: - * it subscribes on baseTexture events, it automatically resizes at the same time as baseTexture. - * - * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. - * You can check for this by checking the sprite's _textureID property. - * ```js - * var texture = PIXI.Texture.from('assets/image.svg'); - * var sprite1 = new PIXI.Sprite(texture); - * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file - * ``` - * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. - * @memberof PIXI - * @typeParam R - The BaseTexture's Resource type. - */ - var Texture = /** @class */ (function (_super) { - __extends$i(Texture, _super); - /** - * @param baseTexture - The base texture source to create the texture from - * @param frame - The rectangle frame of the texture to show - * @param orig - The area of original texture - * @param trim - Trimmed rectangle of original texture - * @param rotate - indicates how the texture was rotated by texture packer. See {@link PIXI.groupD8} - * @param anchor - Default anchor point used for sprite placement / rotation - */ - function Texture(baseTexture, frame, orig, trim, rotate, anchor) { - var _this = _super.call(this) || this; - _this.noFrame = false; - if (!frame) { - _this.noFrame = true; - frame = new Rectangle(0, 0, 1, 1); - } - if (baseTexture instanceof Texture) { - baseTexture = baseTexture.baseTexture; - } - _this.baseTexture = baseTexture; - _this._frame = frame; - _this.trim = trim; - _this.valid = false; - _this._uvs = DEFAULT_UVS; - _this.uvMatrix = null; - _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); - _this._rotate = Number(rotate || 0); - if (rotate === true) { - // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures - _this._rotate = 2; - } - else if (_this._rotate % 2 !== 0) { - throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); - } - _this.defaultAnchor = anchor ? new Point(anchor.x, anchor.y) : new Point(0, 0); - _this._updateID = 0; - _this.textureCacheIds = []; - if (!baseTexture.valid) { - baseTexture.once('loaded', _this.onBaseTextureUpdated, _this); - } - else if (_this.noFrame) { - // if there is no frame we should monitor for any base texture changes.. - if (baseTexture.valid) { - _this.onBaseTextureUpdated(baseTexture); - } - } - else { - _this.frame = frame; - } - if (_this.noFrame) { - baseTexture.on('update', _this.onBaseTextureUpdated, _this); - } - return _this; - } - /** - * Updates this texture on the gpu. - * - * Calls the TextureResource update. - * - * If you adjusted `frame` manually, please call `updateUvs()` instead. - */ - Texture.prototype.update = function () { - if (this.baseTexture.resource) { - this.baseTexture.resource.update(); - } - }; - /** - * Called when the base texture is updated - * @protected - * @param baseTexture - The base texture. - */ - Texture.prototype.onBaseTextureUpdated = function (baseTexture) { - if (this.noFrame) { - if (!this.baseTexture.valid) { - return; - } - this._frame.width = baseTexture.width; - this._frame.height = baseTexture.height; - this.valid = true; - this.updateUvs(); - } - else { - // TODO this code looks confusing.. boo to abusing getters and setters! - // if user gave us frame that has bigger size than resized texture it can be a problem - this.frame = this._frame; - } - this.emit('update', this); - }; - /** - * Destroys this texture - * @param [destroyBase=false] - Whether to destroy the base texture as well - */ - Texture.prototype.destroy = function (destroyBase) { - if (this.baseTexture) { - if (destroyBase) { - var resource = this.baseTexture.resource; - // delete the texture if it exists in the texture cache.. - // this only needs to be removed if the base texture is actually destroyed too.. - if (resource && resource.url && TextureCache[resource.url]) { - Texture.removeFromCache(resource.url); - } - this.baseTexture.destroy(); - } - this.baseTexture.off('loaded', this.onBaseTextureUpdated, this); - this.baseTexture.off('update', this.onBaseTextureUpdated, this); - this.baseTexture = null; - } - this._frame = null; - this._uvs = null; - this.trim = null; - this.orig = null; - this.valid = false; - Texture.removeFromCache(this); - this.textureCacheIds = null; - }; - /** - * Creates a new texture object that acts the same as this one. - * @returns - The new texture - */ - Texture.prototype.clone = function () { - var clonedFrame = this._frame.clone(); - var clonedOrig = this._frame === this.orig ? clonedFrame : this.orig.clone(); - var clonedTexture = new Texture(this.baseTexture, !this.noFrame && clonedFrame, clonedOrig, this.trim && this.trim.clone(), this.rotate, this.defaultAnchor); - if (this.noFrame) { - clonedTexture._frame = clonedFrame; - } - return clonedTexture; - }; - /** - * Updates the internal WebGL UV cache. Use it after you change `frame` or `trim` of the texture. - * Call it after changing the frame - */ - Texture.prototype.updateUvs = function () { - if (this._uvs === DEFAULT_UVS) { - this._uvs = new TextureUvs(); - } - this._uvs.set(this._frame, this.baseTexture, this.rotate); - this._updateID++; - }; - /** - * Helper function that creates a new Texture based on the source you provide. - * The source can be - frame id, image url, video url, canvas element, video element, base texture - * @param {string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} source - - * Source or array of sources to create texture from - * @param options - See {@link PIXI.BaseTexture}'s constructor for options. - * @param {string} [options.pixiIdPrefix=pixiid] - If a source has no id, this is the prefix of the generated id - * @param {boolean} [strict] - Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}. - * @returns {PIXI.Texture} The newly created texture - */ - Texture.from = function (source, options, strict) { - if (options === void 0) { options = {}; } - if (strict === void 0) { strict = settings.STRICT_TEXTURE_CACHE; } - var isFrame = typeof source === 'string'; - var cacheId = null; - if (isFrame) { - cacheId = source; - } - else if (source instanceof BaseTexture) { - if (!source.cacheId) { - var prefix = (options && options.pixiIdPrefix) || 'pixiid'; - source.cacheId = prefix + "-" + uid(); - BaseTexture.addToCache(source, source.cacheId); - } - cacheId = source.cacheId; - } - else { - if (!source._pixiId) { - var prefix = (options && options.pixiIdPrefix) || 'pixiid'; - source._pixiId = prefix + "_" + uid(); - } - cacheId = source._pixiId; - } - var texture = TextureCache[cacheId]; - // Strict-mode rejects invalid cacheIds - if (isFrame && strict && !texture) { - throw new Error("The cacheId \"" + cacheId + "\" does not exist in TextureCache."); - } - if (!texture && !(source instanceof BaseTexture)) { - if (!options.resolution) { - options.resolution = getResolutionOfUrl(source); - } - texture = new Texture(new BaseTexture(source, options)); - texture.baseTexture.cacheId = cacheId; - BaseTexture.addToCache(texture.baseTexture, cacheId); - Texture.addToCache(texture, cacheId); - } - else if (!texture && (source instanceof BaseTexture)) { - texture = new Texture(source); - Texture.addToCache(texture, cacheId); - } - // lets assume its a base texture! - return texture; - }; - /** - * Useful for loading textures via URLs. Use instead of `Texture.from` because - * it does a better job of handling failed URLs more effectively. This also ignores - * `PIXI.settings.STRICT_TEXTURE_CACHE`. Works for Videos, SVGs, Images. - * @param url - The remote URL or array of URLs to load. - * @param options - Optional options to include - * @returns - A Promise that resolves to a Texture. - */ - Texture.fromURL = function (url, options) { - var resourceOptions = Object.assign({ autoLoad: false }, options === null || options === void 0 ? void 0 : options.resourceOptions); - var texture = Texture.from(url, Object.assign({ resourceOptions: resourceOptions }, options), false); - var resource = texture.baseTexture.resource; - // The texture was already loaded - if (texture.baseTexture.valid) { - return Promise.resolve(texture); - } - // Manually load the texture, this should allow users to handle load errors - return resource.load().then(function () { return Promise.resolve(texture); }); - }; - /** - * Create a new Texture with a BufferResource from a Float32Array. - * RGBA values are floats from 0 to 1. - * @param {Float32Array|Uint8Array} buffer - The optional array to use, if no data - * is provided, a new Float32Array is created. - * @param width - Width of the resource - * @param height - Height of the resource - * @param options - See {@link PIXI.BaseTexture}'s constructor for options. - * @returns - The resulting new BaseTexture - */ - Texture.fromBuffer = function (buffer, width, height, options) { - return new Texture(BaseTexture.fromBuffer(buffer, width, height, options)); - }; - /** - * Create a texture from a source and add to the cache. - * @param {HTMLImageElement|HTMLCanvasElement|string} source - The input source. - * @param imageUrl - File name of texture, for cache and resolving resolution. - * @param name - Human readable name for the texture cache. If no name is - * specified, only `imageUrl` will be used as the cache ID. - * @param options - * @returns - Output texture - */ - Texture.fromLoader = function (source, imageUrl, name, options) { - var baseTexture = new BaseTexture(source, Object.assign({ - scaleMode: settings.SCALE_MODE, - resolution: getResolutionOfUrl(imageUrl), - }, options)); - var resource = baseTexture.resource; - if (resource instanceof ImageResource) { - resource.url = imageUrl; - } - var texture = new Texture(baseTexture); - // No name, use imageUrl instead - if (!name) { - name = imageUrl; - } - // lets also add the frame to pixi's global cache for 'fromLoader' function - BaseTexture.addToCache(texture.baseTexture, name); - Texture.addToCache(texture, name); - // also add references by url if they are different. - if (name !== imageUrl) { - BaseTexture.addToCache(texture.baseTexture, imageUrl); - Texture.addToCache(texture, imageUrl); - } - // Generally images are valid right away - if (texture.baseTexture.valid) { - return Promise.resolve(texture); - } - // SVG assets need to be parsed async, let's wait - return new Promise(function (resolve) { - texture.baseTexture.once('loaded', function () { return resolve(texture); }); - }); - }; - /** - * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object. - * @param texture - The Texture to add to the cache. - * @param id - The id that the Texture will be stored against. - */ - Texture.addToCache = function (texture, id) { - if (id) { - if (texture.textureCacheIds.indexOf(id) === -1) { - texture.textureCacheIds.push(id); - } - if (TextureCache[id]) { - // eslint-disable-next-line no-console - console.warn("Texture added to the cache with an id [" + id + "] that already had an entry"); - } - TextureCache[id] = texture; - } - }; - /** - * Remove a Texture from the global TextureCache. - * @param texture - id of a Texture to be removed, or a Texture instance itself - * @returns - The Texture that was removed - */ - Texture.removeFromCache = function (texture) { - if (typeof texture === 'string') { - var textureFromCache = TextureCache[texture]; - if (textureFromCache) { - var index = textureFromCache.textureCacheIds.indexOf(texture); - if (index > -1) { - textureFromCache.textureCacheIds.splice(index, 1); - } - delete TextureCache[texture]; - return textureFromCache; - } - } - else if (texture && texture.textureCacheIds) { - for (var i = 0; i < texture.textureCacheIds.length; ++i) { - // Check that texture matches the one being passed in before deleting it from the cache. - if (TextureCache[texture.textureCacheIds[i]] === texture) { - delete TextureCache[texture.textureCacheIds[i]]; - } - } - texture.textureCacheIds.length = 0; - return texture; - } - return null; - }; - Object.defineProperty(Texture.prototype, "resolution", { - /** - * Returns resolution of baseTexture - * @readonly - */ - get: function () { - return this.baseTexture.resolution; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Texture.prototype, "frame", { - /** - * The frame specifies the region of the base texture that this texture uses. - * Please call `updateUvs()` after you change coordinates of `frame` manually. - */ - get: function () { - return this._frame; - }, - set: function (frame) { - this._frame = frame; - this.noFrame = false; - var x = frame.x, y = frame.y, width = frame.width, height = frame.height; - var xNotFit = x + width > this.baseTexture.width; - var yNotFit = y + height > this.baseTexture.height; - if (xNotFit || yNotFit) { - var relationship = xNotFit && yNotFit ? 'and' : 'or'; - var errorX = "X: " + x + " + " + width + " = " + (x + width) + " > " + this.baseTexture.width; - var errorY = "Y: " + y + " + " + height + " = " + (y + height) + " > " + this.baseTexture.height; - throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' - + (errorX + " " + relationship + " " + errorY)); - } - this.valid = width && height && this.baseTexture.valid; - if (!this.trim && !this.rotate) { - this.orig = frame; - } - if (this.valid) { - this.updateUvs(); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Texture.prototype, "rotate", { - /** - * Indicates whether the texture is rotated inside the atlas - * set to 2 to compensate for texture packer rotation - * set to 6 to compensate for spine packer rotation - * can be used to rotate or mirror sprites - * See {@link PIXI.groupD8} for explanation - */ - get: function () { - return this._rotate; - }, - set: function (rotate) { - this._rotate = rotate; - if (this.valid) { - this.updateUvs(); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Texture.prototype, "width", { - /** The width of the Texture in pixels. */ - get: function () { - return this.orig.width; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Texture.prototype, "height", { - /** The height of the Texture in pixels. */ - get: function () { - return this.orig.height; - }, - enumerable: false, - configurable: true - }); - /** Utility function for BaseTexture|Texture cast. */ - Texture.prototype.castToBaseTexture = function () { - return this.baseTexture; - }; - Object.defineProperty(Texture, "EMPTY", { - /** An empty texture, used often to not have to create multiple empty textures. Can not be destroyed. */ - get: function () { - if (!Texture._EMPTY) { - Texture._EMPTY = new Texture(new BaseTexture()); - removeAllHandlers(Texture._EMPTY); - removeAllHandlers(Texture._EMPTY.baseTexture); - } - return Texture._EMPTY; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Texture, "WHITE", { - /** A white texture of 16x16 size, used for graphics and other things Can not be destroyed. */ - get: function () { - if (!Texture._WHITE) { - var canvas = settings.ADAPTER.createCanvas(16, 16); - var context = canvas.getContext('2d'); - canvas.width = 16; - canvas.height = 16; - context.fillStyle = 'white'; - context.fillRect(0, 0, 16, 16); - Texture._WHITE = new Texture(BaseTexture.from(canvas)); - removeAllHandlers(Texture._WHITE); - removeAllHandlers(Texture._WHITE.baseTexture); - } - return Texture._WHITE; - }, - enumerable: false, - configurable: true - }); - return Texture; - }(eventemitter3)); - - /** - * A RenderTexture is a special texture that allows any PixiJS display object to be rendered to it. - * - * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded - * otherwise black rectangles will be drawn instead. - * - * __Hint-2__: The actual memory allocation will happen on first render. - * You shouldn't create renderTextures each frame just to delete them after, try to reuse them. - * - * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: - * - * ```js - * let renderer = PIXI.autoDetectRenderer(); - * let renderTexture = PIXI.RenderTexture.create({ width: 800, height: 600 }); - * let sprite = PIXI.Sprite.from("spinObj_01.png"); - * - * sprite.position.x = 800/2; - * sprite.position.y = 600/2; - * sprite.anchor.x = 0.5; - * sprite.anchor.y = 0.5; - * - * renderer.render(sprite, {renderTexture}); - * ``` - * Note that you should not create a new renderer, but reuse the same one as the rest of the application. - * - * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 - * you can clear the transform - * - * ```js - * - * sprite.setTransform() - * - * let renderTexture = new PIXI.RenderTexture.create({ width: 100, height: 100 }); - * - * renderer.render(sprite, {renderTexture}); // Renders to center of RenderTexture - * ``` - * @memberof PIXI - */ - var RenderTexture = /** @class */ (function (_super) { - __extends$i(RenderTexture, _super); - /** - * @param baseRenderTexture - The base texture object that this texture uses. - * @param frame - The rectangle frame of the texture to show. - */ - function RenderTexture(baseRenderTexture, frame) { - var _this = _super.call(this, baseRenderTexture, frame) || this; - _this.valid = true; - _this.filterFrame = null; - _this.filterPoolKey = null; - _this.updateUvs(); - return _this; - } - Object.defineProperty(RenderTexture.prototype, "framebuffer", { - /** - * Shortcut to `this.baseTexture.framebuffer`, saves baseTexture cast. - * @readonly - */ - get: function () { - return this.baseTexture.framebuffer; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RenderTexture.prototype, "multisample", { - /** - * Shortcut to `this.framebuffer.multisample`. - * @default PIXI.MSAA_QUALITY.NONE - */ - get: function () { - return this.framebuffer.multisample; - }, - set: function (value) { - this.framebuffer.multisample = value; - }, - enumerable: false, - configurable: true - }); - /** - * Resizes the RenderTexture. - * @param desiredWidth - The desired width to resize to. - * @param desiredHeight - The desired height to resize to. - * @param resizeBaseTexture - Should the baseTexture.width and height values be resized as well? - */ - RenderTexture.prototype.resize = function (desiredWidth, desiredHeight, resizeBaseTexture) { - if (resizeBaseTexture === void 0) { resizeBaseTexture = true; } - var resolution = this.baseTexture.resolution; - var width = Math.round(desiredWidth * resolution) / resolution; - var height = Math.round(desiredHeight * resolution) / resolution; - // TODO - could be not required.. - this.valid = (width > 0 && height > 0); - this._frame.width = this.orig.width = width; - this._frame.height = this.orig.height = height; - if (resizeBaseTexture) { - this.baseTexture.resize(width, height); - } - this.updateUvs(); - }; - /** - * Changes the resolution of baseTexture, but does not change framebuffer size. - * @param resolution - The new resolution to apply to RenderTexture - */ - RenderTexture.prototype.setResolution = function (resolution) { - var baseTexture = this.baseTexture; - if (baseTexture.resolution === resolution) { - return; - } - baseTexture.setResolution(resolution); - this.resize(baseTexture.width, baseTexture.height, false); - }; - RenderTexture.create = function (options) { - var arguments$1 = arguments; - - var rest = []; - for (var _i = 1; _i < arguments.length; _i++) { - rest[_i - 1] = arguments$1[_i]; - } - // @deprecated fallback, old-style: create(width, height, scaleMode, resolution) - if (typeof options === 'number') { - deprecation('6.0.0', 'Arguments (width, height, scaleMode, resolution) have been deprecated.'); - /* eslint-disable prefer-rest-params */ - options = { - width: options, - height: rest[0], - scaleMode: rest[1], - resolution: rest[2], - }; - /* eslint-enable prefer-rest-params */ - } - return new RenderTexture(new BaseRenderTexture(options)); - }; - return RenderTexture; - }(Texture)); - - /** - * Texture pool, used by FilterSystem and plugins. - * - * Stores collection of temporary pow2 or screen-sized renderTextures - * - * If you use custom RenderTexturePool for your filters, you can use methods - * `getFilterTexture` and `returnFilterTexture` same as in - * @memberof PIXI - */ - var RenderTexturePool = /** @class */ (function () { - /** - * @param textureOptions - options that will be passed to BaseRenderTexture constructor - * @param {PIXI.SCALE_MODES} [textureOptions.scaleMode] - See {@link PIXI.SCALE_MODES} for possible values. - */ - function RenderTexturePool(textureOptions) { - this.texturePool = {}; - this.textureOptions = textureOptions || {}; - this.enableFullScreen = false; - this._pixelsWidth = 0; - this._pixelsHeight = 0; - } - /** - * Creates texture with params that were specified in pool constructor. - * @param realWidth - Width of texture in pixels. - * @param realHeight - Height of texture in pixels. - * @param multisample - Number of samples of the framebuffer. - */ - RenderTexturePool.prototype.createTexture = function (realWidth, realHeight, multisample) { - if (multisample === void 0) { multisample = exports.MSAA_QUALITY.NONE; } - var baseRenderTexture = new BaseRenderTexture(Object.assign({ - width: realWidth, - height: realHeight, - resolution: 1, - multisample: multisample, - }, this.textureOptions)); - return new RenderTexture(baseRenderTexture); - }; - /** - * Gets a Power-of-Two render texture or fullScreen texture - * @param minWidth - The minimum width of the render texture. - * @param minHeight - The minimum height of the render texture. - * @param resolution - The resolution of the render texture. - * @param multisample - Number of samples of the render texture. - * @returns The new render texture. - */ - RenderTexturePool.prototype.getOptimalTexture = function (minWidth, minHeight, resolution, multisample) { - if (resolution === void 0) { resolution = 1; } - if (multisample === void 0) { multisample = exports.MSAA_QUALITY.NONE; } - var key; - minWidth = Math.ceil((minWidth * resolution) - 1e-6); - minHeight = Math.ceil((minHeight * resolution) - 1e-6); - if (!this.enableFullScreen || minWidth !== this._pixelsWidth || minHeight !== this._pixelsHeight) { - minWidth = nextPow2(minWidth); - minHeight = nextPow2(minHeight); - key = (((minWidth & 0xFFFF) << 16) | (minHeight & 0xFFFF)) >>> 0; - if (multisample > 1) { - key += multisample * 0x100000000; - } - } - else { - key = multisample > 1 ? -multisample : -1; - } - if (!this.texturePool[key]) { - this.texturePool[key] = []; - } - var renderTexture = this.texturePool[key].pop(); - if (!renderTexture) { - renderTexture = this.createTexture(minWidth, minHeight, multisample); - } - renderTexture.filterPoolKey = key; - renderTexture.setResolution(resolution); - return renderTexture; - }; - /** - * Gets extra texture of the same size as input renderTexture - * - * `getFilterTexture(input, 0.5)` or `getFilterTexture(0.5, input)` - * @param input - renderTexture from which size and resolution will be copied - * @param resolution - override resolution of the renderTexture - * It overrides, it does not multiply - * @param multisample - number of samples of the renderTexture - */ - RenderTexturePool.prototype.getFilterTexture = function (input, resolution, multisample) { - var filterTexture = this.getOptimalTexture(input.width, input.height, resolution || input.resolution, multisample || exports.MSAA_QUALITY.NONE); - filterTexture.filterFrame = input.filterFrame; - return filterTexture; - }; - /** - * Place a render texture back into the pool. - * @param renderTexture - The renderTexture to free - */ - RenderTexturePool.prototype.returnTexture = function (renderTexture) { - var key = renderTexture.filterPoolKey; - renderTexture.filterFrame = null; - this.texturePool[key].push(renderTexture); - }; - /** - * Alias for returnTexture, to be compliant with FilterSystem interface. - * @param renderTexture - The renderTexture to free - */ - RenderTexturePool.prototype.returnFilterTexture = function (renderTexture) { - this.returnTexture(renderTexture); - }; - /** - * Clears the pool. - * @param destroyTextures - Destroy all stored textures. - */ - RenderTexturePool.prototype.clear = function (destroyTextures) { - destroyTextures = destroyTextures !== false; - if (destroyTextures) { - for (var i in this.texturePool) { - var textures = this.texturePool[i]; - if (textures) { - for (var j = 0; j < textures.length; j++) { - textures[j].destroy(true); - } - } - } - } - this.texturePool = {}; - }; - /** - * If screen size was changed, drops all screen-sized textures, - * sets new screen size, sets `enableFullScreen` to true - * - * Size is measured in pixels, `renderer.view` can be passed here, not `renderer.screen` - * @param size - Initial size of screen. - */ - RenderTexturePool.prototype.setScreenSize = function (size) { - if (size.width === this._pixelsWidth - && size.height === this._pixelsHeight) { - return; - } - this.enableFullScreen = size.width > 0 && size.height > 0; - for (var i in this.texturePool) { - if (!(Number(i) < 0)) { - continue; - } - var textures = this.texturePool[i]; - if (textures) { - for (var j = 0; j < textures.length; j++) { - textures[j].destroy(true); - } - } - this.texturePool[i] = []; - } - this._pixelsWidth = size.width; - this._pixelsHeight = size.height; - }; - /** - * Key that is used to store fullscreen renderTextures in a pool - * @constant - */ - RenderTexturePool.SCREEN_KEY = -1; - return RenderTexturePool; - }()); - - /* eslint-disable max-len */ - /** - * Holds the information for a single attribute structure required to render geometry. - * - * This does not contain the actual data, but instead has a buffer id that maps to a {@link PIXI.Buffer} - * This can include anything from positions, uvs, normals, colors etc. - * @memberof PIXI - */ - var Attribute = /** @class */ (function () { - /** - * @param buffer - the id of the buffer that this attribute will look for - * @param size - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2. - * @param normalized - should the data be normalized. - * @param {PIXI.TYPES} [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available - * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data) - * @param [start=0] - How far into the array to start reading values (used for interleaving data) - * @param [instance=false] - Whether the geometry is instanced. - */ - function Attribute(buffer, size, normalized, type, stride, start, instance) { - if (size === void 0) { size = 0; } - if (normalized === void 0) { normalized = false; } - if (type === void 0) { type = exports.TYPES.FLOAT; } - this.buffer = buffer; - this.size = size; - this.normalized = normalized; - this.type = type; - this.stride = stride; - this.start = start; - this.instance = instance; - } - /** Destroys the Attribute. */ - Attribute.prototype.destroy = function () { - this.buffer = null; - }; - /** - * Helper function that creates an Attribute based on the information provided - * @param buffer - the id of the buffer that this attribute will look for - * @param [size=0] - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2 - * @param [normalized=false] - should the data be normalized. - * @param [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available - * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data) - * @returns - A new {@link PIXI.Attribute} based on the information provided - */ - Attribute.from = function (buffer, size, normalized, type, stride) { - return new Attribute(buffer, size, normalized, type, stride); - }; - return Attribute; - }()); - - var UID$4 = 0; - /** - * A wrapper for data so that it can be used and uploaded by WebGL - * @memberof PIXI - */ - var Buffer = /** @class */ (function () { - /** - * @param {PIXI.IArrayBuffer} data - the data to store in the buffer. - * @param _static - `true` for static buffer - * @param index - `true` for index buffer - */ - function Buffer(data, _static, index) { - if (_static === void 0) { _static = true; } - if (index === void 0) { index = false; } - this.data = (data || new Float32Array(1)); - this._glBuffers = {}; - this._updateID = 0; - this.index = index; - this.static = _static; - this.id = UID$4++; - this.disposeRunner = new Runner('disposeBuffer'); - } - // TODO could explore flagging only a partial upload? - /** - * Flags this buffer as requiring an upload to the GPU. - * @param {PIXI.IArrayBuffer|number[]} [data] - the data to update in the buffer. - */ - Buffer.prototype.update = function (data) { - if (data instanceof Array) { - data = new Float32Array(data); - } - this.data = data || this.data; - this._updateID++; - }; - /** Disposes WebGL resources that are connected to this geometry. */ - Buffer.prototype.dispose = function () { - this.disposeRunner.emit(this, false); - }; - /** Destroys the buffer. */ - Buffer.prototype.destroy = function () { - this.dispose(); - this.data = null; - }; - Object.defineProperty(Buffer.prototype, "index", { - get: function () { - return this.type === exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; - }, - /** - * Flags whether this is an index buffer. - * - * Index buffers are of type `ELEMENT_ARRAY_BUFFER`. Note that setting this property to false will make - * the buffer of type `ARRAY_BUFFER`. - * - * For backwards compatibility. - */ - set: function (value) { - this.type = value ? exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER : exports.BUFFER_TYPE.ARRAY_BUFFER; - }, - enumerable: false, - configurable: true - }); - /** - * Helper function that creates a buffer based on an array or TypedArray - * @param {ArrayBufferView | number[]} data - the TypedArray that the buffer will store. If this is a regular Array it will be converted to a Float32Array. - * @returns - A new Buffer based on the data provided. - */ - Buffer.from = function (data) { - if (data instanceof Array) { - data = new Float32Array(data); - } - return new Buffer(data); - }; - return Buffer; - }()); - - /* eslint-disable object-shorthand */ - var map$1 = { - Float32Array: Float32Array, - Uint32Array: Uint32Array, - Int32Array: Int32Array, - Uint8Array: Uint8Array, - }; - function interleaveTypedArrays(arrays, sizes) { - var outSize = 0; - var stride = 0; - var views = {}; - for (var i = 0; i < arrays.length; i++) { - stride += sizes[i]; - outSize += arrays[i].length; - } - var buffer = new ArrayBuffer(outSize * 4); - var out = null; - var littleOffset = 0; - for (var i = 0; i < arrays.length; i++) { - var size = sizes[i]; - var array = arrays[i]; - var type = getBufferType(array); - if (!views[type]) { - views[type] = new map$1[type](buffer); - } - out = views[type]; - for (var j = 0; j < array.length; j++) { - var indexStart = ((j / size | 0) * stride) + littleOffset; - var index = j % size; - out[indexStart + index] = array[j]; - } - littleOffset += size; - } - return new Float32Array(buffer); - } - - var byteSizeMap$1 = { 5126: 4, 5123: 2, 5121: 1 }; - var UID$3 = 0; - /* eslint-disable object-shorthand */ - var map = { - Float32Array: Float32Array, - Uint32Array: Uint32Array, - Int32Array: Int32Array, - Uint8Array: Uint8Array, - Uint16Array: Uint16Array, - }; - /* eslint-disable max-len */ - /** - * The Geometry represents a model. It consists of two components: - * - GeometryStyle - The structure of the model such as the attributes layout - * - GeometryData - the data of the model - this consists of buffers. - * This can include anything from positions, uvs, normals, colors etc. - * - * Geometry can be defined without passing in a style or data if required (thats how I prefer!) - * - * ```js - * let geometry = new PIXI.Geometry(); - * - * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2); - * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1],2) - * geometry.addIndex([0,1,2,1,3,2]) - * ``` - * @memberof PIXI - */ - var Geometry = /** @class */ (function () { - /** - * @param buffers - An array of buffers. optional. - * @param attributes - Of the geometry, optional structure of the attributes layout - */ - function Geometry(buffers, attributes) { - if (buffers === void 0) { buffers = []; } - if (attributes === void 0) { attributes = {}; } - this.buffers = buffers; - this.indexBuffer = null; - this.attributes = attributes; - this.glVertexArrayObjects = {}; - this.id = UID$3++; - this.instanced = false; - this.instanceCount = 1; - this.disposeRunner = new Runner('disposeGeometry'); - this.refCount = 0; - } - /** - * - * Adds an attribute to the geometry - * Note: `stride` and `start` should be `undefined` if you dont know them, not 0! - * @param id - the name of the attribute (matching up to a shader) - * @param {PIXI.Buffer|number[]} buffer - the buffer that holds the data of the attribute . You can also provide an Array and a buffer will be created from it. - * @param size - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2 - * @param normalized - should the data be normalized. - * @param [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {PIXI.TYPES} to see the ones available - * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data) - * @param [start=0] - How far into the array to start reading values (used for interleaving data) - * @param instance - Instancing flag - * @returns - Returns self, useful for chaining. - */ - Geometry.prototype.addAttribute = function (id, buffer, size, normalized, type, stride, start, instance) { - if (size === void 0) { size = 0; } - if (normalized === void 0) { normalized = false; } - if (instance === void 0) { instance = false; } - if (!buffer) { - throw new Error('You must pass a buffer when creating an attribute'); - } - // check if this is a buffer! - if (!(buffer instanceof Buffer)) { - // its an array! - if (buffer instanceof Array) { - buffer = new Float32Array(buffer); - } - buffer = new Buffer(buffer); - } - var ids = id.split('|'); - if (ids.length > 1) { - for (var i = 0; i < ids.length; i++) { - this.addAttribute(ids[i], buffer, size, normalized, type); - } - return this; - } - var bufferIndex = this.buffers.indexOf(buffer); - if (bufferIndex === -1) { - this.buffers.push(buffer); - bufferIndex = this.buffers.length - 1; - } - this.attributes[id] = new Attribute(bufferIndex, size, normalized, type, stride, start, instance); - // assuming that if there is instanced data then this will be drawn with instancing! - this.instanced = this.instanced || instance; - return this; - }; - /** - * Returns the requested attribute. - * @param id - The name of the attribute required - * @returns - The attribute requested. - */ - Geometry.prototype.getAttribute = function (id) { - return this.attributes[id]; - }; - /** - * Returns the requested buffer. - * @param id - The name of the buffer required. - * @returns - The buffer requested. - */ - Geometry.prototype.getBuffer = function (id) { - return this.buffers[this.getAttribute(id).buffer]; - }; - /** - * - * Adds an index buffer to the geometry - * The index buffer contains integers, three for each triangle in the geometry, which reference the various attribute buffers (position, colour, UV coordinates, other UV coordinates, normal, …). There is only ONE index buffer. - * @param {PIXI.Buffer|number[]} [buffer] - The buffer that holds the data of the index buffer. You can also provide an Array and a buffer will be created from it. - * @returns - Returns self, useful for chaining. - */ - Geometry.prototype.addIndex = function (buffer) { - if (!(buffer instanceof Buffer)) { - // its an array! - if (buffer instanceof Array) { - buffer = new Uint16Array(buffer); - } - buffer = new Buffer(buffer); - } - buffer.type = exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; - this.indexBuffer = buffer; - if (this.buffers.indexOf(buffer) === -1) { - this.buffers.push(buffer); - } - return this; - }; - /** - * Returns the index buffer - * @returns - The index buffer. - */ - Geometry.prototype.getIndex = function () { - return this.indexBuffer; - }; - /** - * This function modifies the structure so that all current attributes become interleaved into a single buffer - * This can be useful if your model remains static as it offers a little performance boost - * @returns - Returns self, useful for chaining. - */ - Geometry.prototype.interleave = function () { - // a simple check to see if buffers are already interleaved.. - if (this.buffers.length === 1 || (this.buffers.length === 2 && this.indexBuffer)) - { return this; } - // assume already that no buffers are interleaved - var arrays = []; - var sizes = []; - var interleavedBuffer = new Buffer(); - var i; - for (i in this.attributes) { - var attribute = this.attributes[i]; - var buffer = this.buffers[attribute.buffer]; - arrays.push(buffer.data); - sizes.push((attribute.size * byteSizeMap$1[attribute.type]) / 4); - attribute.buffer = 0; - } - interleavedBuffer.data = interleaveTypedArrays(arrays, sizes); - for (i = 0; i < this.buffers.length; i++) { - if (this.buffers[i] !== this.indexBuffer) { - this.buffers[i].destroy(); - } - } - this.buffers = [interleavedBuffer]; - if (this.indexBuffer) { - this.buffers.push(this.indexBuffer); - } - return this; - }; - /** Get the size of the geometries, in vertices. */ - Geometry.prototype.getSize = function () { - for (var i in this.attributes) { - var attribute = this.attributes[i]; - var buffer = this.buffers[attribute.buffer]; - return buffer.data.length / ((attribute.stride / 4) || attribute.size); - } - return 0; - }; - /** Disposes WebGL resources that are connected to this geometry. */ - Geometry.prototype.dispose = function () { - this.disposeRunner.emit(this, false); - }; - /** Destroys the geometry. */ - Geometry.prototype.destroy = function () { - this.dispose(); - this.buffers = null; - this.indexBuffer = null; - this.attributes = null; - }; - /** - * Returns a clone of the geometry. - * @returns - A new clone of this geometry. - */ - Geometry.prototype.clone = function () { - var geometry = new Geometry(); - for (var i = 0; i < this.buffers.length; i++) { - geometry.buffers[i] = new Buffer(this.buffers[i].data.slice(0)); - } - for (var i in this.attributes) { - var attrib = this.attributes[i]; - geometry.attributes[i] = new Attribute(attrib.buffer, attrib.size, attrib.normalized, attrib.type, attrib.stride, attrib.start, attrib.instance); - } - if (this.indexBuffer) { - geometry.indexBuffer = geometry.buffers[this.buffers.indexOf(this.indexBuffer)]; - geometry.indexBuffer.type = exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; - } - return geometry; - }; - /** - * Merges an array of geometries into a new single one. - * - * Geometry attribute styles must match for this operation to work. - * @param geometries - array of geometries to merge - * @returns - Shiny new geometry! - */ - Geometry.merge = function (geometries) { - // todo add a geometry check! - // also a size check.. cant be too big!] - var geometryOut = new Geometry(); - var arrays = []; - var sizes = []; - var offsets = []; - var geometry; - // pass one.. get sizes.. - for (var i = 0; i < geometries.length; i++) { - geometry = geometries[i]; - for (var j = 0; j < geometry.buffers.length; j++) { - sizes[j] = sizes[j] || 0; - sizes[j] += geometry.buffers[j].data.length; - offsets[j] = 0; - } - } - // build the correct size arrays.. - for (var i = 0; i < geometry.buffers.length; i++) { - // TODO types! - arrays[i] = new map[getBufferType(geometry.buffers[i].data)](sizes[i]); - geometryOut.buffers[i] = new Buffer(arrays[i]); - } - // pass to set data.. - for (var i = 0; i < geometries.length; i++) { - geometry = geometries[i]; - for (var j = 0; j < geometry.buffers.length; j++) { - arrays[j].set(geometry.buffers[j].data, offsets[j]); - offsets[j] += geometry.buffers[j].data.length; - } - } - geometryOut.attributes = geometry.attributes; - if (geometry.indexBuffer) { - geometryOut.indexBuffer = geometryOut.buffers[geometry.buffers.indexOf(geometry.indexBuffer)]; - geometryOut.indexBuffer.type = exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; - var offset = 0; - var stride = 0; - var offset2 = 0; - var bufferIndexToCount = 0; - // get a buffer - for (var i = 0; i < geometry.buffers.length; i++) { - if (geometry.buffers[i] !== geometry.indexBuffer) { - bufferIndexToCount = i; - break; - } - } - // figure out the stride of one buffer.. - for (var i in geometry.attributes) { - var attribute = geometry.attributes[i]; - if ((attribute.buffer | 0) === bufferIndexToCount) { - stride += ((attribute.size * byteSizeMap$1[attribute.type]) / 4); - } - } - // time to off set all indexes.. - for (var i = 0; i < geometries.length; i++) { - var indexBufferData = geometries[i].indexBuffer.data; - for (var j = 0; j < indexBufferData.length; j++) { - geometryOut.indexBuffer.data[j + offset2] += offset; - } - offset += geometries[i].buffers[bufferIndexToCount].data.length / (stride); - offset2 += indexBufferData.length; - } - } - return geometryOut; - }; - return Geometry; - }()); - - /** - * Helper class to create a quad - * @memberof PIXI - */ - var Quad = /** @class */ (function (_super) { - __extends$i(Quad, _super); - function Quad() { - var _this = _super.call(this) || this; - _this.addAttribute('aVertexPosition', new Float32Array([ - 0, 0, - 1, 0, - 1, 1, - 0, 1 ])) - .addIndex([0, 1, 3, 2]); - return _this; - } - return Quad; - }(Geometry)); - - /** - * Helper class to create a quad with uvs like in v4 - * @memberof PIXI - */ - var QuadUv = /** @class */ (function (_super) { - __extends$i(QuadUv, _super); - function QuadUv() { - var _this = _super.call(this) || this; - _this.vertices = new Float32Array([ - -1, -1, - 1, -1, - 1, 1, - -1, 1 ]); - _this.uvs = new Float32Array([ - 0, 0, - 1, 0, - 1, 1, - 0, 1 ]); - _this.vertexBuffer = new Buffer(_this.vertices); - _this.uvBuffer = new Buffer(_this.uvs); - _this.addAttribute('aVertexPosition', _this.vertexBuffer) - .addAttribute('aTextureCoord', _this.uvBuffer) - .addIndex([0, 1, 2, 0, 2, 3]); - return _this; - } - /** - * Maps two Rectangle to the quad. - * @param targetTextureFrame - The first rectangle - * @param destinationFrame - The second rectangle - * @returns - Returns itself. - */ - QuadUv.prototype.map = function (targetTextureFrame, destinationFrame) { - var x = 0; // destinationFrame.x / targetTextureFrame.width; - var y = 0; // destinationFrame.y / targetTextureFrame.height; - this.uvs[0] = x; - this.uvs[1] = y; - this.uvs[2] = x + (destinationFrame.width / targetTextureFrame.width); - this.uvs[3] = y; - this.uvs[4] = x + (destinationFrame.width / targetTextureFrame.width); - this.uvs[5] = y + (destinationFrame.height / targetTextureFrame.height); - this.uvs[6] = x; - this.uvs[7] = y + (destinationFrame.height / targetTextureFrame.height); - x = destinationFrame.x; - y = destinationFrame.y; - this.vertices[0] = x; - this.vertices[1] = y; - this.vertices[2] = x + destinationFrame.width; - this.vertices[3] = y; - this.vertices[4] = x + destinationFrame.width; - this.vertices[5] = y + destinationFrame.height; - this.vertices[6] = x; - this.vertices[7] = y + destinationFrame.height; - this.invalidate(); - return this; - }; - /** - * Legacy upload method, just marks buffers dirty. - * @returns - Returns itself. - */ - QuadUv.prototype.invalidate = function () { - this.vertexBuffer._updateID++; - this.uvBuffer._updateID++; - return this; - }; - return QuadUv; - }(Geometry)); - - var UID$2 = 0; - /** - * Uniform group holds uniform map and some ID's for work - * - * `UniformGroup` has two modes: - * - * 1: Normal mode - * Normal mode will upload the uniforms with individual function calls as required - * - * 2: Uniform buffer mode - * This mode will treat the uniforms as a uniform buffer. You can pass in either a buffer that you manually handle, or - * or a generic object that PixiJS will automatically map to a buffer for you. - * For maximum benefits, make Ubo UniformGroups static, and only update them each frame. - * - * Rules of UBOs: - * - UBOs only work with WebGL2, so make sure you have a fallback! - * - Only floats are supported (including vec[2,3,4], mat[2,3,4]) - * - Samplers cannot be used in ubo's (a GPU limitation) - * - You must ensure that the object you pass in exactly matches in the shader ubo structure. - * Otherwise, weirdness will ensue! - * - The name of the ubo object added to the group must match exactly the name of the ubo in the shader. - * - * ``` - * // ubo in shader: - * uniform myCoolData { // declaring a ubo.. - * mat4 uCoolMatrix; - * float uFloatyMcFloatFace - * - * - * // a new uniform buffer object.. - * const myCoolData = new UniformBufferGroup({ - * uCoolMatrix: new Matrix(), - * uFloatyMcFloatFace: 23, - * }} - * - * // build a shader... - * const shader = Shader.from(srcVert, srcFrag, { - * myCoolData // name matches the ubo name in the shader. will be processed accordingly. - * }) - * - * ``` - * @memberof PIXI - */ - var UniformGroup = /** @class */ (function () { - /** - * @param {object | Buffer} [uniforms] - Custom uniforms to use to augment the built-in ones. Or a pixi buffer. - * @param isStatic - Uniforms wont be changed after creation. - * @param isUbo - If true, will treat this uniform group as a uniform buffer object. - */ - function UniformGroup(uniforms, isStatic, isUbo) { - this.group = true; - // lets generate this when the shader ? - this.syncUniforms = {}; - this.dirtyId = 0; - this.id = UID$2++; - this.static = !!isStatic; - this.ubo = !!isUbo; - if (uniforms instanceof Buffer) { - this.buffer = uniforms; - this.buffer.type = exports.BUFFER_TYPE.UNIFORM_BUFFER; - this.autoManage = false; - this.ubo = true; - } - else { - this.uniforms = uniforms; - if (this.ubo) { - this.buffer = new Buffer(new Float32Array(1)); - this.buffer.type = exports.BUFFER_TYPE.UNIFORM_BUFFER; - this.autoManage = true; - } - } - } - UniformGroup.prototype.update = function () { - this.dirtyId++; - if (!this.autoManage && this.buffer) { - this.buffer.update(); - } - }; - UniformGroup.prototype.add = function (name, uniforms, _static) { - if (!this.ubo) { - this.uniforms[name] = new UniformGroup(uniforms, _static); - } - else { - // eslint-disable-next-line max-len - throw new Error('[UniformGroup] uniform groups in ubo mode cannot be modified, or have uniform groups nested in them'); - } - }; - UniformGroup.from = function (uniforms, _static, _ubo) { - return new UniformGroup(uniforms, _static, _ubo); - }; - /** - * A short hand function for creating a static UBO UniformGroup. - * @param uniforms - the ubo item - * @param _static - should this be updated each time it is used? defaults to true here! - */ - UniformGroup.uboFrom = function (uniforms, _static) { - return new UniformGroup(uniforms, _static !== null && _static !== void 0 ? _static : true, true); - }; - return UniformGroup; - }()); - - /** - * System plugin to the renderer to manage filter states. - * @ignore - */ - var FilterState = /** @class */ (function () { - function FilterState() { - this.renderTexture = null; - this.target = null; - this.legacy = false; - this.resolution = 1; - this.multisample = exports.MSAA_QUALITY.NONE; - // next three fields are created only for root - // re-assigned for everything else - this.sourceFrame = new Rectangle(); - this.destinationFrame = new Rectangle(); - this.bindingSourceFrame = new Rectangle(); - this.bindingDestinationFrame = new Rectangle(); - this.filters = []; - this.transform = null; - } - /** Clears the state */ - FilterState.prototype.clear = function () { - this.target = null; - this.filters = null; - this.renderTexture = null; - }; - return FilterState; - }()); - - var tempPoints = [new Point(), new Point(), new Point(), new Point()]; - var tempMatrix$2 = new Matrix(); - /** - * System plugin to the renderer to manage filters. - * - * ## Pipeline - * - * The FilterSystem executes the filtering pipeline by rendering the display-object into a texture, applying its - * [filters]{@link PIXI.Filter} in series, and the last filter outputs into the final render-target. - * - * The filter-frame is the rectangle in world space being filtered, and those contents are mapped into - * `(0, 0, filterFrame.width, filterFrame.height)` into the filter render-texture. The filter-frame is also called - * the source-frame, as it is used to bind the filter render-textures. The last filter outputs to the `filterFrame` - * in the final render-target. - * - * ## Usage - * - * {@link PIXI.Container#renderAdvanced} is an example of how to use the filter system. It is a 3 step process: - * - * **push**: Use {@link PIXI.FilterSystem#push} to push the set of filters to be applied on a filter-target. - * **render**: Render the contents to be filtered using the renderer. The filter-system will only capture the contents - * inside the bounds of the filter-target. NOTE: Using {@link PIXI.Renderer#render} is - * illegal during an existing render cycle, and it may reset the filter system. - * **pop**: Use {@link PIXI.FilterSystem#pop} to pop & execute the filters you initially pushed. It will apply them - * serially and output to the bounds of the filter-target. - * @memberof PIXI - */ - var FilterSystem = /** @class */ (function () { - /** - * @param renderer - The renderer this System works for. - */ - function FilterSystem(renderer) { - this.renderer = renderer; - this.defaultFilterStack = [{}]; - this.texturePool = new RenderTexturePool(); - this.texturePool.setScreenSize(renderer.view); - this.statePool = []; - this.quad = new Quad(); - this.quadUv = new QuadUv(); - this.tempRect = new Rectangle(); - this.activeState = {}; - this.globalUniforms = new UniformGroup({ - outputFrame: new Rectangle(), - inputSize: new Float32Array(4), - inputPixel: new Float32Array(4), - inputClamp: new Float32Array(4), - resolution: 1, - // legacy variables - filterArea: new Float32Array(4), - filterClamp: new Float32Array(4), - }, true); - this.forceClear = false; - this.useMaxPadding = false; - } - /** - * Pushes a set of filters to be applied later to the system. This will redirect further rendering into an - * input render-texture for the rest of the filtering pipeline. - * @param {PIXI.DisplayObject} target - The target of the filter to render. - * @param filters - The filters to apply. - */ - FilterSystem.prototype.push = function (target, filters) { - var _a, _b; - var renderer = this.renderer; - var filterStack = this.defaultFilterStack; - var state = this.statePool.pop() || new FilterState(); - var renderTextureSystem = this.renderer.renderTexture; - var resolution = filters[0].resolution; - var multisample = filters[0].multisample; - var padding = filters[0].padding; - var autoFit = filters[0].autoFit; - // We don't know whether it's a legacy filter until it was bound for the first time, - // therefore we have to assume that it is if legacy is undefined. - var legacy = (_a = filters[0].legacy) !== null && _a !== void 0 ? _a : true; - for (var i = 1; i < filters.length; i++) { - var filter = filters[i]; - // let's use the lowest resolution - resolution = Math.min(resolution, filter.resolution); - // let's use the lowest number of samples - multisample = Math.min(multisample, filter.multisample); - // figure out the padding required for filters - padding = this.useMaxPadding - // old behavior: use largest amount of padding! - ? Math.max(padding, filter.padding) - // new behavior: sum the padding - : padding + filter.padding; - // only auto fit if all filters are autofit - autoFit = autoFit && filter.autoFit; - legacy = legacy || ((_b = filter.legacy) !== null && _b !== void 0 ? _b : true); - } - if (filterStack.length === 1) { - this.defaultFilterStack[0].renderTexture = renderTextureSystem.current; - } - filterStack.push(state); - state.resolution = resolution; - state.multisample = multisample; - state.legacy = legacy; - state.target = target; - state.sourceFrame.copyFrom(target.filterArea || target.getBounds(true)); - state.sourceFrame.pad(padding); - var sourceFrameProjected = this.tempRect.copyFrom(renderTextureSystem.sourceFrame); - // Project source frame into world space (if projection is applied) - if (renderer.projection.transform) { - this.transformAABB(tempMatrix$2.copyFrom(renderer.projection.transform).invert(), sourceFrameProjected); - } - if (autoFit) { - state.sourceFrame.fit(sourceFrameProjected); - if (state.sourceFrame.width <= 0 || state.sourceFrame.height <= 0) { - state.sourceFrame.width = 0; - state.sourceFrame.height = 0; - } - } - else if (!state.sourceFrame.intersects(sourceFrameProjected)) { - state.sourceFrame.width = 0; - state.sourceFrame.height = 0; - } - // Round sourceFrame in screen space based on render-texture. - this.roundFrame(state.sourceFrame, renderTextureSystem.current ? renderTextureSystem.current.resolution : renderer.resolution, renderTextureSystem.sourceFrame, renderTextureSystem.destinationFrame, renderer.projection.transform); - state.renderTexture = this.getOptimalFilterTexture(state.sourceFrame.width, state.sourceFrame.height, resolution, multisample); - state.filters = filters; - state.destinationFrame.width = state.renderTexture.width; - state.destinationFrame.height = state.renderTexture.height; - var destinationFrame = this.tempRect; - destinationFrame.x = 0; - destinationFrame.y = 0; - destinationFrame.width = state.sourceFrame.width; - destinationFrame.height = state.sourceFrame.height; - state.renderTexture.filterFrame = state.sourceFrame; - state.bindingSourceFrame.copyFrom(renderTextureSystem.sourceFrame); - state.bindingDestinationFrame.copyFrom(renderTextureSystem.destinationFrame); - state.transform = renderer.projection.transform; - renderer.projection.transform = null; - renderTextureSystem.bind(state.renderTexture, state.sourceFrame, destinationFrame); - renderer.framebuffer.clear(0, 0, 0, 0); - }; - /** Pops off the filter and applies it. */ - FilterSystem.prototype.pop = function () { - var filterStack = this.defaultFilterStack; - var state = filterStack.pop(); - var filters = state.filters; - this.activeState = state; - var globalUniforms = this.globalUniforms.uniforms; - globalUniforms.outputFrame = state.sourceFrame; - globalUniforms.resolution = state.resolution; - var inputSize = globalUniforms.inputSize; - var inputPixel = globalUniforms.inputPixel; - var inputClamp = globalUniforms.inputClamp; - inputSize[0] = state.destinationFrame.width; - inputSize[1] = state.destinationFrame.height; - inputSize[2] = 1.0 / inputSize[0]; - inputSize[3] = 1.0 / inputSize[1]; - inputPixel[0] = Math.round(inputSize[0] * state.resolution); - inputPixel[1] = Math.round(inputSize[1] * state.resolution); - inputPixel[2] = 1.0 / inputPixel[0]; - inputPixel[3] = 1.0 / inputPixel[1]; - inputClamp[0] = 0.5 * inputPixel[2]; - inputClamp[1] = 0.5 * inputPixel[3]; - inputClamp[2] = (state.sourceFrame.width * inputSize[2]) - (0.5 * inputPixel[2]); - inputClamp[3] = (state.sourceFrame.height * inputSize[3]) - (0.5 * inputPixel[3]); - // only update the rect if its legacy.. - if (state.legacy) { - var filterArea = globalUniforms.filterArea; - filterArea[0] = state.destinationFrame.width; - filterArea[1] = state.destinationFrame.height; - filterArea[2] = state.sourceFrame.x; - filterArea[3] = state.sourceFrame.y; - globalUniforms.filterClamp = globalUniforms.inputClamp; - } - this.globalUniforms.update(); - var lastState = filterStack[filterStack.length - 1]; - this.renderer.framebuffer.blit(); - if (filters.length === 1) { - filters[0].apply(this, state.renderTexture, lastState.renderTexture, exports.CLEAR_MODES.BLEND, state); - this.returnFilterTexture(state.renderTexture); - } - else { - var flip = state.renderTexture; - var flop = this.getOptimalFilterTexture(flip.width, flip.height, state.resolution); - flop.filterFrame = flip.filterFrame; - var i = 0; - for (i = 0; i < filters.length - 1; ++i) { - if (i === 1 && state.multisample > 1) { - flop = this.getOptimalFilterTexture(flip.width, flip.height, state.resolution); - flop.filterFrame = flip.filterFrame; - } - filters[i].apply(this, flip, flop, exports.CLEAR_MODES.CLEAR, state); - var t = flip; - flip = flop; - flop = t; - } - filters[i].apply(this, flip, lastState.renderTexture, exports.CLEAR_MODES.BLEND, state); - if (i > 1 && state.multisample > 1) { - this.returnFilterTexture(state.renderTexture); - } - this.returnFilterTexture(flip); - this.returnFilterTexture(flop); - } - // lastState.renderTexture is blitted when lastState is popped - state.clear(); - this.statePool.push(state); - }; - /** - * Binds a renderTexture with corresponding `filterFrame`, clears it if mode corresponds. - * @param filterTexture - renderTexture to bind, should belong to filter pool or filter stack - * @param clearMode - clearMode, by default its CLEAR/YES. See {@link PIXI.CLEAR_MODES} - */ - FilterSystem.prototype.bindAndClear = function (filterTexture, clearMode) { - if (clearMode === void 0) { clearMode = exports.CLEAR_MODES.CLEAR; } - var _a = this.renderer, renderTextureSystem = _a.renderTexture, stateSystem = _a.state; - if (filterTexture === this.defaultFilterStack[this.defaultFilterStack.length - 1].renderTexture) { - // Restore projection transform if rendering into the output render-target. - this.renderer.projection.transform = this.activeState.transform; - } - else { - // Prevent projection within filtering pipeline. - this.renderer.projection.transform = null; - } - if (filterTexture && filterTexture.filterFrame) { - var destinationFrame = this.tempRect; - destinationFrame.x = 0; - destinationFrame.y = 0; - destinationFrame.width = filterTexture.filterFrame.width; - destinationFrame.height = filterTexture.filterFrame.height; - renderTextureSystem.bind(filterTexture, filterTexture.filterFrame, destinationFrame); - } - else if (filterTexture !== this.defaultFilterStack[this.defaultFilterStack.length - 1].renderTexture) { - renderTextureSystem.bind(filterTexture); - } - else { - // Restore binding for output render-target. - this.renderer.renderTexture.bind(filterTexture, this.activeState.bindingSourceFrame, this.activeState.bindingDestinationFrame); - } - // Clear the texture in BLIT mode if blending is disabled or the forceClear flag is set. The blending - // is stored in the 0th bit of the state. - var autoClear = (stateSystem.stateId & 1) || this.forceClear; - if (clearMode === exports.CLEAR_MODES.CLEAR - || (clearMode === exports.CLEAR_MODES.BLIT && autoClear)) { - // Use framebuffer.clear because we want to clear the whole filter texture, not just the filtering - // area over which the shaders are run. This is because filters may sampling outside of it (e.g. blur) - // instead of clamping their arithmetic. - this.renderer.framebuffer.clear(0, 0, 0, 0); - } - }; - /** - * Draws a filter using the default rendering process. - * - * This should be called only by {@link Filter#apply}. - * @param filter - The filter to draw. - * @param input - The input render target. - * @param output - The target to output to. - * @param clearMode - Should the output be cleared before rendering to it - */ - FilterSystem.prototype.applyFilter = function (filter, input, output, clearMode) { - var renderer = this.renderer; - // Set state before binding, so bindAndClear gets the blend mode. - renderer.state.set(filter.state); - this.bindAndClear(output, clearMode); - // set the uniforms.. - filter.uniforms.uSampler = input; - filter.uniforms.filterGlobals = this.globalUniforms; - // TODO make it so that the order of this does not matter.. - // because it does at the moment cos of global uniforms. - // they need to get resynced - renderer.shader.bind(filter); - // check to see if the filter is a legacy one.. - filter.legacy = !!filter.program.attributeData.aTextureCoord; - if (filter.legacy) { - this.quadUv.map(input._frame, input.filterFrame); - renderer.geometry.bind(this.quadUv); - renderer.geometry.draw(exports.DRAW_MODES.TRIANGLES); - } - else { - renderer.geometry.bind(this.quad); - renderer.geometry.draw(exports.DRAW_MODES.TRIANGLE_STRIP); - } - }; - /** - * Multiply _input normalized coordinates_ to this matrix to get _sprite texture normalized coordinates_. - * - * Use `outputMatrix * vTextureCoord` in the shader. - * @param outputMatrix - The matrix to output to. - * @param {PIXI.Sprite} sprite - The sprite to map to. - * @returns The mapped matrix. - */ - FilterSystem.prototype.calculateSpriteMatrix = function (outputMatrix, sprite) { - var _a = this.activeState, sourceFrame = _a.sourceFrame, destinationFrame = _a.destinationFrame; - var orig = sprite._texture.orig; - var mappedMatrix = outputMatrix.set(destinationFrame.width, 0, 0, destinationFrame.height, sourceFrame.x, sourceFrame.y); - var worldTransform = sprite.worldTransform.copyTo(Matrix.TEMP_MATRIX); - worldTransform.invert(); - mappedMatrix.prepend(worldTransform); - mappedMatrix.scale(1.0 / orig.width, 1.0 / orig.height); - mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); - return mappedMatrix; - }; - /** Destroys this Filter System. */ - FilterSystem.prototype.destroy = function () { - this.renderer = null; - // Those textures has to be destroyed by RenderTextureSystem or FramebufferSystem - this.texturePool.clear(false); - }; - /** - * Gets a Power-of-Two render texture or fullScreen texture - * @param minWidth - The minimum width of the render texture in real pixels. - * @param minHeight - The minimum height of the render texture in real pixels. - * @param resolution - The resolution of the render texture. - * @param multisample - Number of samples of the render texture. - * @returns - The new render texture. - */ - FilterSystem.prototype.getOptimalFilterTexture = function (minWidth, minHeight, resolution, multisample) { - if (resolution === void 0) { resolution = 1; } - if (multisample === void 0) { multisample = exports.MSAA_QUALITY.NONE; } - return this.texturePool.getOptimalTexture(minWidth, minHeight, resolution, multisample); - }; - /** - * Gets extra render texture to use inside current filter - * To be compliant with older filters, you can use params in any order - * @param input - renderTexture from which size and resolution will be copied - * @param resolution - override resolution of the renderTexture - * @param multisample - number of samples of the renderTexture - */ - FilterSystem.prototype.getFilterTexture = function (input, resolution, multisample) { - if (typeof input === 'number') { - var swap = input; - input = resolution; - resolution = swap; - } - input = input || this.activeState.renderTexture; - var filterTexture = this.texturePool.getOptimalTexture(input.width, input.height, resolution || input.resolution, multisample || exports.MSAA_QUALITY.NONE); - filterTexture.filterFrame = input.filterFrame; - return filterTexture; - }; - /** - * Frees a render texture back into the pool. - * @param renderTexture - The renderTarget to free - */ - FilterSystem.prototype.returnFilterTexture = function (renderTexture) { - this.texturePool.returnTexture(renderTexture); - }; - /** Empties the texture pool. */ - FilterSystem.prototype.emptyPool = function () { - this.texturePool.clear(true); - }; - /** Calls `texturePool.resize()`, affects fullScreen renderTextures. */ - FilterSystem.prototype.resize = function () { - this.texturePool.setScreenSize(this.renderer.view); - }; - /** - * @param matrix - first param - * @param rect - second param - */ - FilterSystem.prototype.transformAABB = function (matrix, rect) { - var lt = tempPoints[0]; - var lb = tempPoints[1]; - var rt = tempPoints[2]; - var rb = tempPoints[3]; - lt.set(rect.left, rect.top); - lb.set(rect.left, rect.bottom); - rt.set(rect.right, rect.top); - rb.set(rect.right, rect.bottom); - matrix.apply(lt, lt); - matrix.apply(lb, lb); - matrix.apply(rt, rt); - matrix.apply(rb, rb); - var x0 = Math.min(lt.x, lb.x, rt.x, rb.x); - var y0 = Math.min(lt.y, lb.y, rt.y, rb.y); - var x1 = Math.max(lt.x, lb.x, rt.x, rb.x); - var y1 = Math.max(lt.y, lb.y, rt.y, rb.y); - rect.x = x0; - rect.y = y0; - rect.width = x1 - x0; - rect.height = y1 - y0; - }; - FilterSystem.prototype.roundFrame = function (frame, resolution, bindingSourceFrame, bindingDestinationFrame, transform) { - if (frame.width <= 0 || frame.height <= 0 || bindingSourceFrame.width <= 0 || bindingSourceFrame.height <= 0) { - return; - } - if (transform) { - var a = transform.a, b = transform.b, c = transform.c, d = transform.d; - // Skip if skew/rotation present in matrix, except for multiple of 90° rotation. If rotation - // is a multiple of 90°, then either pair of (b,c) or (a,d) will be (0,0). - if ((Math.abs(b) > 1e-4 || Math.abs(c) > 1e-4) - && (Math.abs(a) > 1e-4 || Math.abs(d) > 1e-4)) { - return; - } - } - transform = transform ? tempMatrix$2.copyFrom(transform) : tempMatrix$2.identity(); - // Get forward transform from world space to screen space - transform - .translate(-bindingSourceFrame.x, -bindingSourceFrame.y) - .scale(bindingDestinationFrame.width / bindingSourceFrame.width, bindingDestinationFrame.height / bindingSourceFrame.height) - .translate(bindingDestinationFrame.x, bindingDestinationFrame.y); - // Convert frame to screen space - this.transformAABB(transform, frame); - // Round frame in screen space - frame.ceil(resolution); - // Project back into world space. - this.transformAABB(transform.invert(), frame); - }; - return FilterSystem; - }()); - - /** - * Base for a common object renderer that can be used as a - * system renderer plugin. - * @memberof PIXI - */ - var ObjectRenderer = /** @class */ (function () { - /** - * @param renderer - The renderer this manager works for. - */ - function ObjectRenderer(renderer) { - this.renderer = renderer; - } - /** Stub method that should be used to empty the current batch by rendering objects now. */ - ObjectRenderer.prototype.flush = function () { - // flush! - }; - /** Generic destruction method that frees all resources. This should be called by subclasses. */ - ObjectRenderer.prototype.destroy = function () { - this.renderer = null; - }; - /** - * Stub method that initializes any state required before - * rendering starts. It is different from the `prerender` - * signal, which occurs every frame, in that it is called - * whenever an object requests _this_ renderer specifically. - */ - ObjectRenderer.prototype.start = function () { - // set the shader.. - }; - /** Stops the renderer. It should free up any state and become dormant. */ - ObjectRenderer.prototype.stop = function () { - this.flush(); - }; - /** - * Keeps the object to render. It doesn't have to be - * rendered immediately. - * @param {PIXI.DisplayObject} _object - The object to render. - */ - ObjectRenderer.prototype.render = function (_object) { - // render the object - }; - return ObjectRenderer; - }()); - - /** - * System plugin to the renderer to manage batching. - * @memberof PIXI - */ - var BatchSystem = /** @class */ (function () { - /** - * @param renderer - The renderer this System works for. - */ - function BatchSystem(renderer) { - this.renderer = renderer; - this.emptyRenderer = new ObjectRenderer(renderer); - this.currentRenderer = this.emptyRenderer; - } - /** - * Changes the current renderer to the one given in parameter - * @param objectRenderer - The object renderer to use. - */ - BatchSystem.prototype.setObjectRenderer = function (objectRenderer) { - if (this.currentRenderer === objectRenderer) { - return; - } - this.currentRenderer.stop(); - this.currentRenderer = objectRenderer; - this.currentRenderer.start(); - }; - /** - * This should be called if you wish to do some custom rendering - * It will basically render anything that may be batched up such as sprites - */ - BatchSystem.prototype.flush = function () { - this.setObjectRenderer(this.emptyRenderer); - }; - /** Reset the system to an empty renderer */ - BatchSystem.prototype.reset = function () { - this.setObjectRenderer(this.emptyRenderer); - }; - /** - * Handy function for batch renderers: copies bound textures in first maxTextures locations to array - * sets actual _batchLocation for them - * @param arr - arr copy destination - * @param maxTextures - number of copied elements - */ - BatchSystem.prototype.copyBoundTextures = function (arr, maxTextures) { - var boundTextures = this.renderer.texture.boundTextures; - for (var i = maxTextures - 1; i >= 0; --i) { - arr[i] = boundTextures[i] || null; - if (arr[i]) { - arr[i]._batchLocation = i; - } - } - }; - /** - * Assigns batch locations to textures in array based on boundTextures state. - * All textures in texArray should have `_batchEnabled = _batchId`, - * and their count should be less than `maxTextures`. - * @param texArray - textures to bound - * @param boundTextures - current state of bound textures - * @param batchId - marker for _batchEnabled param of textures in texArray - * @param maxTextures - number of texture locations to manipulate - */ - BatchSystem.prototype.boundArray = function (texArray, boundTextures, batchId, maxTextures) { - var elements = texArray.elements, ids = texArray.ids, count = texArray.count; - var j = 0; - for (var i = 0; i < count; i++) { - var tex = elements[i]; - var loc = tex._batchLocation; - if (loc >= 0 && loc < maxTextures - && boundTextures[loc] === tex) { - ids[i] = loc; - continue; - } - while (j < maxTextures) { - var bound = boundTextures[j]; - if (bound && bound._batchEnabled === batchId - && bound._batchLocation === j) { - j++; - continue; - } - ids[i] = j; - tex._batchLocation = j; - boundTextures[j] = tex; - break; - } - } - }; - /** - * @ignore - */ - BatchSystem.prototype.destroy = function () { - this.renderer = null; - }; - return BatchSystem; - }()); - - var CONTEXT_UID_COUNTER = 0; - /** - * System plugin to the renderer to manage the context. - * @memberof PIXI - */ - var ContextSystem = /** @class */ (function () { - /** @param renderer - The renderer this System works for. */ - function ContextSystem(renderer) { - this.renderer = renderer; - this.webGLVersion = 1; - this.extensions = {}; - this.supports = { - uint32Indices: false, - }; - // Bind functions - this.handleContextLost = this.handleContextLost.bind(this); - this.handleContextRestored = this.handleContextRestored.bind(this); - renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); - renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } - Object.defineProperty(ContextSystem.prototype, "isLost", { - /** - * `true` if the context is lost - * @readonly - */ - get: function () { - return (!this.gl || this.gl.isContextLost()); - }, - enumerable: false, - configurable: true - }); - /** - * Handles the context change event. - * @param {WebGLRenderingContext} gl - New WebGL context. - */ - ContextSystem.prototype.contextChange = function (gl) { - this.gl = gl; - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID_COUNTER++; - }; - /** - * Initializes the context. - * @protected - * @param {WebGLRenderingContext} gl - WebGL context - */ - ContextSystem.prototype.initFromContext = function (gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID_COUNTER++; - this.renderer.runners.contextChange.emit(gl); - }; - /** - * Initialize from context options - * @protected - * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext - * @param {object} options - context attributes - */ - ContextSystem.prototype.initFromOptions = function (options) { - var gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); - }; - /** - * Helper class to create a WebGL Context - * @param canvas - the canvas element that we will get the context from - * @param options - An options object that gets passed in to the canvas element containing the - * context attributes - * @see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext - * @returns {WebGLRenderingContext} the WebGL context - */ - ContextSystem.prototype.createContext = function (canvas, options) { - var gl; - if (settings.PREFER_ENV >= exports.ENV.WEBGL2) { - gl = canvas.getContext('webgl2', options); - } - if (gl) { - this.webGLVersion = 2; - } - else { - this.webGLVersion = 1; - gl = canvas.getContext('webgl', options) || canvas.getContext('experimental-webgl', options); - if (!gl) { - // fail, not able to get a context - throw new Error('This browser does not support WebGL. Try using the canvas renderer'); - } - } - this.gl = gl; - this.getExtensions(); - return this.gl; - }; - /** Auto-populate the {@link PIXI.ContextSystem.extensions extensions}. */ - ContextSystem.prototype.getExtensions = function () { - // time to set up default extensions that Pixi uses. - var gl = this.gl; - var common = { - loseContext: gl.getExtension('WEBGL_lose_context'), - anisotropicFiltering: gl.getExtension('EXT_texture_filter_anisotropic'), - floatTextureLinear: gl.getExtension('OES_texture_float_linear'), - s3tc: gl.getExtension('WEBGL_compressed_texture_s3tc'), - s3tc_sRGB: gl.getExtension('WEBGL_compressed_texture_s3tc_srgb'), - etc: gl.getExtension('WEBGL_compressed_texture_etc'), - etc1: gl.getExtension('WEBGL_compressed_texture_etc1'), - pvrtc: gl.getExtension('WEBGL_compressed_texture_pvrtc') - || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'), - atc: gl.getExtension('WEBGL_compressed_texture_atc'), - astc: gl.getExtension('WEBGL_compressed_texture_astc') - }; - if (this.webGLVersion === 1) { - Object.assign(this.extensions, common, { - drawBuffers: gl.getExtension('WEBGL_draw_buffers'), - depthTexture: gl.getExtension('WEBGL_depth_texture'), - vertexArrayObject: gl.getExtension('OES_vertex_array_object') - || gl.getExtension('MOZ_OES_vertex_array_object') - || gl.getExtension('WEBKIT_OES_vertex_array_object'), - uint32ElementIndex: gl.getExtension('OES_element_index_uint'), - // Floats and half-floats - floatTexture: gl.getExtension('OES_texture_float'), - floatTextureLinear: gl.getExtension('OES_texture_float_linear'), - textureHalfFloat: gl.getExtension('OES_texture_half_float'), - textureHalfFloatLinear: gl.getExtension('OES_texture_half_float_linear'), - }); - } - else if (this.webGLVersion === 2) { - Object.assign(this.extensions, common, { - // Floats and half-floats - colorBufferFloat: gl.getExtension('EXT_color_buffer_float') - }); - } - }; - /** - * Handles a lost webgl context - * @param {WebGLContextEvent} event - The context lost event. - */ - ContextSystem.prototype.handleContextLost = function (event) { - var _this = this; - // Prevent default to be able to restore the context - event.preventDefault(); - // Restore the context after this event has exited - setTimeout(function () { - if (_this.gl.isContextLost() && _this.extensions.loseContext) { - _this.extensions.loseContext.restoreContext(); - } - }, 0); - }; - /** Handles a restored webgl context. */ - ContextSystem.prototype.handleContextRestored = function () { - this.renderer.runners.contextChange.emit(this.gl); - }; - ContextSystem.prototype.destroy = function () { - var view = this.renderer.view; - this.renderer = null; - // remove listeners - view.removeEventListener('webglcontextlost', this.handleContextLost); - view.removeEventListener('webglcontextrestored', this.handleContextRestored); - this.gl.useProgram(null); - if (this.extensions.loseContext) { - this.extensions.loseContext.loseContext(); - } - }; - /** Handle the post-render runner event. */ - ContextSystem.prototype.postrender = function () { - if (this.renderer.renderingToScreen) { - this.gl.flush(); - } - }; - /** - * Validate context. - * @param {WebGLRenderingContext} gl - Render context. - */ - ContextSystem.prototype.validateContext = function (gl) { - var attributes = gl.getContextAttributes(); - var isWebGl2 = 'WebGL2RenderingContext' in globalThis && gl instanceof globalThis.WebGL2RenderingContext; - if (isWebGl2) { - this.webGLVersion = 2; - } - // this is going to be fairly simple for now.. but at least we have room to grow! - if (attributes && !attributes.stencil) { - /* eslint-disable max-len, no-console */ - console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); - /* eslint-enable max-len, no-console */ - } - var hasuint32 = isWebGl2 || !!gl.getExtension('OES_element_index_uint'); - this.supports.uint32Indices = hasuint32; - if (!hasuint32) { - /* eslint-disable max-len, no-console */ - console.warn('Provided WebGL context does not support 32 index buffer, complex graphics may not render correctly'); - /* eslint-enable max-len, no-console */ - } - }; - return ContextSystem; - }()); - - /** - * Internal framebuffer for WebGL context. - * @memberof PIXI - */ - var GLFramebuffer = /** @class */ (function () { - function GLFramebuffer(framebuffer) { - this.framebuffer = framebuffer; - this.stencil = null; - this.dirtyId = -1; - this.dirtyFormat = -1; - this.dirtySize = -1; - this.multisample = exports.MSAA_QUALITY.NONE; - this.msaaBuffer = null; - this.blitFramebuffer = null; - this.mipLevel = 0; - } - return GLFramebuffer; - }()); - - var tempRectangle = new Rectangle(); - /** - * System plugin to the renderer to manage framebuffers. - * @memberof PIXI - */ - var FramebufferSystem = /** @class */ (function () { - /** - * @param renderer - The renderer this System works for. - */ - function FramebufferSystem(renderer) { - this.renderer = renderer; - this.managedFramebuffers = []; - this.unknownFramebuffer = new Framebuffer(10, 10); - this.msaaSamples = null; - } - /** Sets up the renderer context and necessary buffers. */ - FramebufferSystem.prototype.contextChange = function () { - this.disposeAll(true); - var gl = this.gl = this.renderer.gl; - this.CONTEXT_UID = this.renderer.CONTEXT_UID; - this.current = this.unknownFramebuffer; - this.viewport = new Rectangle(); - this.hasMRT = true; - this.writeDepthTexture = true; - // webgl2 - if (this.renderer.context.webGLVersion === 1) { - // webgl 1! - var nativeDrawBuffersExtension_1 = this.renderer.context.extensions.drawBuffers; - var nativeDepthTextureExtension = this.renderer.context.extensions.depthTexture; - if (settings.PREFER_ENV === exports.ENV.WEBGL_LEGACY) { - nativeDrawBuffersExtension_1 = null; - nativeDepthTextureExtension = null; - } - if (nativeDrawBuffersExtension_1) { - gl.drawBuffers = function (activeTextures) { - return nativeDrawBuffersExtension_1.drawBuffersWEBGL(activeTextures); - }; - } - else { - this.hasMRT = false; - gl.drawBuffers = function () { - // empty - }; - } - if (!nativeDepthTextureExtension) { - this.writeDepthTexture = false; - } - } - else { - // WebGL2 - // cache possible MSAA samples - this.msaaSamples = gl.getInternalformatParameter(gl.RENDERBUFFER, gl.RGBA8, gl.SAMPLES); - } - }; - /** - * Bind a framebuffer. - * @param framebuffer - * @param frame - frame, default is framebuffer size - * @param mipLevel - optional mip level to set on the framebuffer - defaults to 0 - */ - FramebufferSystem.prototype.bind = function (framebuffer, frame, mipLevel) { - if (mipLevel === void 0) { mipLevel = 0; } - var gl = this.gl; - if (framebuffer) { - // TODO caching layer! - var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); - if (this.current !== framebuffer) { - this.current = framebuffer; - gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); - } - // make sure all textures are unbound.. - if (fbo.mipLevel !== mipLevel) { - framebuffer.dirtyId++; - framebuffer.dirtyFormat++; - fbo.mipLevel = mipLevel; - } - // now check for updates... - if (fbo.dirtyId !== framebuffer.dirtyId) { - fbo.dirtyId = framebuffer.dirtyId; - if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { - fbo.dirtyFormat = framebuffer.dirtyFormat; - fbo.dirtySize = framebuffer.dirtySize; - this.updateFramebuffer(framebuffer, mipLevel); - } - else if (fbo.dirtySize !== framebuffer.dirtySize) { - fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer); - } - } - for (var i = 0; i < framebuffer.colorTextures.length; i++) { - var tex = framebuffer.colorTextures[i]; - this.renderer.texture.unbind(tex.parentTextureArray || tex); - } - if (framebuffer.depthTexture) { - this.renderer.texture.unbind(framebuffer.depthTexture); - } - if (frame) { - var mipWidth = (frame.width >> mipLevel); - var mipHeight = (frame.height >> mipLevel); - var scale = mipWidth / frame.width; - this.setViewport(frame.x * scale, frame.y * scale, mipWidth, mipHeight); - } - else { - var mipWidth = (framebuffer.width >> mipLevel); - var mipHeight = (framebuffer.height >> mipLevel); - this.setViewport(0, 0, mipWidth, mipHeight); - } - } - else { - if (this.current) { - this.current = null; - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - } - if (frame) { - this.setViewport(frame.x, frame.y, frame.width, frame.height); - } - else { - this.setViewport(0, 0, this.renderer.width, this.renderer.height); - } - } - }; - /** - * Set the WebGLRenderingContext's viewport. - * @param x - X position of viewport - * @param y - Y position of viewport - * @param width - Width of viewport - * @param height - Height of viewport - */ - FramebufferSystem.prototype.setViewport = function (x, y, width, height) { - var v = this.viewport; - x = Math.round(x); - y = Math.round(y); - width = Math.round(width); - height = Math.round(height); - if (v.width !== width || v.height !== height || v.x !== x || v.y !== y) { - v.x = x; - v.y = y; - v.width = width; - v.height = height; - this.gl.viewport(x, y, width, height); - } - }; - Object.defineProperty(FramebufferSystem.prototype, "size", { - /** - * Get the size of the current width and height. Returns object with `width` and `height` values. - * @readonly - */ - get: function () { - if (this.current) { - // TODO store temp - return { x: 0, y: 0, width: this.current.width, height: this.current.height }; - } - return { x: 0, y: 0, width: this.renderer.width, height: this.renderer.height }; - }, - enumerable: false, - configurable: true - }); - /** - * Clear the color of the context - * @param r - Red value from 0 to 1 - * @param g - Green value from 0 to 1 - * @param b - Blue value from 0 to 1 - * @param a - Alpha value from 0 to 1 - * @param {PIXI.BUFFER_BITS} [mask=BUFFER_BITS.COLOR | BUFFER_BITS.DEPTH] - Bitwise OR of masks - * that indicate the buffers to be cleared, by default COLOR and DEPTH buffers. - */ - FramebufferSystem.prototype.clear = function (r, g, b, a, mask) { - if (mask === void 0) { mask = exports.BUFFER_BITS.COLOR | exports.BUFFER_BITS.DEPTH; } - var gl = this.gl; - // TODO clear color can be set only one right? - gl.clearColor(r, g, b, a); - gl.clear(mask); - }; - /** - * Initialize framebuffer for this context - * @protected - * @param framebuffer - * @returns - created GLFramebuffer - */ - FramebufferSystem.prototype.initFramebuffer = function (framebuffer) { - var gl = this.gl; - var fbo = new GLFramebuffer(gl.createFramebuffer()); - fbo.multisample = this.detectSamples(framebuffer.multisample); - framebuffer.glFramebuffers[this.CONTEXT_UID] = fbo; - this.managedFramebuffers.push(framebuffer); - framebuffer.disposeRunner.add(this); - return fbo; - }; - /** - * Resize the framebuffer - * @param framebuffer - * @protected - */ - FramebufferSystem.prototype.resizeFramebuffer = function (framebuffer) { - var gl = this.gl; - var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; - if (fbo.msaaBuffer) { - gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.msaaBuffer); - gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.RGBA8, framebuffer.width, framebuffer.height); - } - if (fbo.stencil) { - gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil); - if (fbo.msaaBuffer) { - gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, framebuffer.width, framebuffer.height); - } - else { - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); - } - } - var colorTextures = framebuffer.colorTextures; - var count = colorTextures.length; - if (!gl.drawBuffers) { - count = Math.min(count, 1); - } - for (var i = 0; i < count; i++) { - var texture = colorTextures[i]; - var parentTexture = texture.parentTextureArray || texture; - this.renderer.texture.bind(parentTexture, 0); - } - if (framebuffer.depthTexture && this.writeDepthTexture) { - this.renderer.texture.bind(framebuffer.depthTexture, 0); - } - }; - /** - * Update the framebuffer - * @param framebuffer - * @param mipLevel - * @protected - */ - FramebufferSystem.prototype.updateFramebuffer = function (framebuffer, mipLevel) { - var gl = this.gl; - var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; - // bind the color texture - var colorTextures = framebuffer.colorTextures; - var count = colorTextures.length; - if (!gl.drawBuffers) { - count = Math.min(count, 1); - } - if (fbo.multisample > 1 && this.canMultisampleFramebuffer(framebuffer)) { - fbo.msaaBuffer = fbo.msaaBuffer || gl.createRenderbuffer(); - gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.msaaBuffer); - gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.RGBA8, framebuffer.width, framebuffer.height); - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, fbo.msaaBuffer); - } - else if (fbo.msaaBuffer) { - gl.deleteRenderbuffer(fbo.msaaBuffer); - fbo.msaaBuffer = null; - if (fbo.blitFramebuffer) { - fbo.blitFramebuffer.dispose(); - fbo.blitFramebuffer = null; - } - } - var activeTextures = []; - for (var i = 0; i < count; i++) { - var texture = colorTextures[i]; - var parentTexture = texture.parentTextureArray || texture; - this.renderer.texture.bind(parentTexture, 0); - if (i === 0 && fbo.msaaBuffer) { - continue; - } - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, texture.target, parentTexture._glTextures[this.CONTEXT_UID].texture, mipLevel); - activeTextures.push(gl.COLOR_ATTACHMENT0 + i); - } - if (activeTextures.length > 1) { - gl.drawBuffers(activeTextures); - } - if (framebuffer.depthTexture) { - var writeDepthTexture = this.writeDepthTexture; - if (writeDepthTexture) { - var depthTexture = framebuffer.depthTexture; - this.renderer.texture.bind(depthTexture, 0); - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._glTextures[this.CONTEXT_UID].texture, mipLevel); - } - } - if ((framebuffer.stencil || framebuffer.depth) && !(framebuffer.depthTexture && this.writeDepthTexture)) { - fbo.stencil = fbo.stencil || gl.createRenderbuffer(); - gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil); - if (fbo.msaaBuffer) { - gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, framebuffer.width, framebuffer.height); - } - else { - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); - } - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - } - else if (fbo.stencil) { - gl.deleteRenderbuffer(fbo.stencil); - fbo.stencil = null; - } - }; - /** - * Returns true if the frame buffer can be multisampled. - * @param framebuffer - */ - FramebufferSystem.prototype.canMultisampleFramebuffer = function (framebuffer) { - return this.renderer.context.webGLVersion !== 1 - && framebuffer.colorTextures.length <= 1 && !framebuffer.depthTexture; - }; - /** - * Detects number of samples that is not more than a param but as close to it as possible - * @param samples - number of samples - * @returns - recommended number of samples - */ - FramebufferSystem.prototype.detectSamples = function (samples) { - var msaaSamples = this.msaaSamples; - var res = exports.MSAA_QUALITY.NONE; - if (samples <= 1 || msaaSamples === null) { - return res; - } - for (var i = 0; i < msaaSamples.length; i++) { - if (msaaSamples[i] <= samples) { - res = msaaSamples[i]; - break; - } - } - if (res === 1) { - res = exports.MSAA_QUALITY.NONE; - } - return res; - }; - /** - * Only works with WebGL2 - * - * blits framebuffer to another of the same or bigger size - * after that target framebuffer is bound - * - * Fails with WebGL warning if blits multisample framebuffer to different size - * @param framebuffer - by default it blits "into itself", from renderBuffer to texture. - * @param sourcePixels - source rectangle in pixels - * @param destPixels - dest rectangle in pixels, assumed to be the same as sourcePixels - */ - FramebufferSystem.prototype.blit = function (framebuffer, sourcePixels, destPixels) { - var _a = this, current = _a.current, renderer = _a.renderer, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; - if (renderer.context.webGLVersion !== 2) { - return; - } - if (!current) { - return; - } - var fbo = current.glFramebuffers[CONTEXT_UID]; - if (!fbo) { - return; - } - if (!framebuffer) { - if (!fbo.msaaBuffer) { - return; - } - var colorTexture = current.colorTextures[0]; - if (!colorTexture) { - return; - } - if (!fbo.blitFramebuffer) { - fbo.blitFramebuffer = new Framebuffer(current.width, current.height); - fbo.blitFramebuffer.addColorTexture(0, colorTexture); - } - framebuffer = fbo.blitFramebuffer; - if (framebuffer.colorTextures[0] !== colorTexture) { - framebuffer.colorTextures[0] = colorTexture; - framebuffer.dirtyId++; - framebuffer.dirtyFormat++; - } - if (framebuffer.width !== current.width || framebuffer.height !== current.height) { - framebuffer.width = current.width; - framebuffer.height = current.height; - framebuffer.dirtyId++; - framebuffer.dirtySize++; - } - } - if (!sourcePixels) { - sourcePixels = tempRectangle; - sourcePixels.width = current.width; - sourcePixels.height = current.height; - } - if (!destPixels) { - destPixels = sourcePixels; - } - var sameSize = sourcePixels.width === destPixels.width && sourcePixels.height === destPixels.height; - this.bind(framebuffer); - gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fbo.framebuffer); - gl.blitFramebuffer(sourcePixels.left, sourcePixels.top, sourcePixels.right, sourcePixels.bottom, destPixels.left, destPixels.top, destPixels.right, destPixels.bottom, gl.COLOR_BUFFER_BIT, sameSize ? gl.NEAREST : gl.LINEAR); - }; - /** - * Disposes framebuffer. - * @param framebuffer - framebuffer that has to be disposed of - * @param contextLost - If context was lost, we suppress all delete function calls - */ - FramebufferSystem.prototype.disposeFramebuffer = function (framebuffer, contextLost) { - var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; - var gl = this.gl; - if (!fbo) { - return; - } - delete framebuffer.glFramebuffers[this.CONTEXT_UID]; - var index = this.managedFramebuffers.indexOf(framebuffer); - if (index >= 0) { - this.managedFramebuffers.splice(index, 1); - } - framebuffer.disposeRunner.remove(this); - if (!contextLost) { - gl.deleteFramebuffer(fbo.framebuffer); - if (fbo.msaaBuffer) { - gl.deleteRenderbuffer(fbo.msaaBuffer); - } - if (fbo.stencil) { - gl.deleteRenderbuffer(fbo.stencil); - } - } - if (fbo.blitFramebuffer) { - fbo.blitFramebuffer.dispose(); - } - }; - /** - * Disposes all framebuffers, but not textures bound to them. - * @param [contextLost=false] - If context was lost, we suppress all delete function calls - */ - FramebufferSystem.prototype.disposeAll = function (contextLost) { - var list = this.managedFramebuffers; - this.managedFramebuffers = []; - for (var i = 0; i < list.length; i++) { - this.disposeFramebuffer(list[i], contextLost); - } - }; - /** - * Forcing creation of stencil buffer for current framebuffer, if it wasn't done before. - * Used by MaskSystem, when its time to use stencil mask for Graphics element. - * - * Its an alternative for public lazy `framebuffer.enableStencil`, in case we need stencil without rebind. - * @private - */ - FramebufferSystem.prototype.forceStencil = function () { - var framebuffer = this.current; - if (!framebuffer) { - return; - } - var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; - if (!fbo || fbo.stencil) { - return; - } - framebuffer.stencil = true; - var w = framebuffer.width; - var h = framebuffer.height; - var gl = this.gl; - var stencil = gl.createRenderbuffer(); - gl.bindRenderbuffer(gl.RENDERBUFFER, stencil); - if (fbo.msaaBuffer) { - gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, w, h); - } - else { - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, w, h); - } - fbo.stencil = stencil; - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, stencil); - }; - /** Resets framebuffer stored state, binds screen framebuffer. Should be called before renderTexture reset(). */ - FramebufferSystem.prototype.reset = function () { - this.current = this.unknownFramebuffer; - this.viewport = new Rectangle(); - }; - FramebufferSystem.prototype.destroy = function () { - this.renderer = null; - }; - return FramebufferSystem; - }()); - - var byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; - /** - * System plugin to the renderer to manage geometry. - * @memberof PIXI - */ - var GeometrySystem = /** @class */ (function () { - /** @param renderer - The renderer this System works for. */ - function GeometrySystem(renderer) { - this.renderer = renderer; - this._activeGeometry = null; - this._activeVao = null; - this.hasVao = true; - this.hasInstance = true; - this.canUseUInt32ElementIndex = false; - this.managedGeometries = {}; - } - /** Sets up the renderer context and necessary buffers. */ - GeometrySystem.prototype.contextChange = function () { - this.disposeAll(true); - var gl = this.gl = this.renderer.gl; - var context = this.renderer.context; - this.CONTEXT_UID = this.renderer.CONTEXT_UID; - // webgl2 - if (context.webGLVersion !== 2) { - // webgl 1! - var nativeVaoExtension_1 = this.renderer.context.extensions.vertexArrayObject; - if (settings.PREFER_ENV === exports.ENV.WEBGL_LEGACY) { - nativeVaoExtension_1 = null; - } - if (nativeVaoExtension_1) { - gl.createVertexArray = function () { - return nativeVaoExtension_1.createVertexArrayOES(); - }; - gl.bindVertexArray = function (vao) { - return nativeVaoExtension_1.bindVertexArrayOES(vao); - }; - gl.deleteVertexArray = function (vao) { - return nativeVaoExtension_1.deleteVertexArrayOES(vao); - }; - } - else { - this.hasVao = false; - gl.createVertexArray = function () { - return null; - }; - gl.bindVertexArray = function () { - return null; - }; - gl.deleteVertexArray = function () { - return null; - }; - } - } - if (context.webGLVersion !== 2) { - var instanceExt_1 = gl.getExtension('ANGLE_instanced_arrays'); - if (instanceExt_1) { - gl.vertexAttribDivisor = function (a, b) { - return instanceExt_1.vertexAttribDivisorANGLE(a, b); - }; - gl.drawElementsInstanced = function (a, b, c, d, e) { - return instanceExt_1.drawElementsInstancedANGLE(a, b, c, d, e); - }; - gl.drawArraysInstanced = function (a, b, c, d) { - return instanceExt_1.drawArraysInstancedANGLE(a, b, c, d); - }; - } - else { - this.hasInstance = false; - } - } - this.canUseUInt32ElementIndex = context.webGLVersion === 2 || !!context.extensions.uint32ElementIndex; - }; - /** - * Binds geometry so that is can be drawn. Creating a Vao if required - * @param geometry - Instance of geometry to bind. - * @param shader - Instance of shader to use vao for. - */ - GeometrySystem.prototype.bind = function (geometry, shader) { - shader = shader || this.renderer.shader.shader; - var gl = this.gl; - // not sure the best way to address this.. - // currently different shaders require different VAOs for the same geometry - // Still mulling over the best way to solve this one.. - // will likely need to modify the shader attribute locations at run time! - var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - var incRefCount = false; - if (!vaos) { - this.managedGeometries[geometry.id] = geometry; - geometry.disposeRunner.add(this); - geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; - incRefCount = true; - } - var vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader, incRefCount); - this._activeGeometry = geometry; - if (this._activeVao !== vao) { - this._activeVao = vao; - if (this.hasVao) { - gl.bindVertexArray(vao); - } - else { - this.activateVao(geometry, shader.program); - } - } - // TODO - optimise later! - // don't need to loop through if nothing changed! - // maybe look to add an 'autoupdate' to geometry? - this.updateBuffers(); - }; - /** Reset and unbind any active VAO and geometry. */ - GeometrySystem.prototype.reset = function () { - this.unbind(); - }; - /** Update buffers of the currently bound geometry. */ - GeometrySystem.prototype.updateBuffers = function () { - var geometry = this._activeGeometry; - var bufferSystem = this.renderer.buffer; - for (var i = 0; i < geometry.buffers.length; i++) { - var buffer = geometry.buffers[i]; - bufferSystem.update(buffer); - } - }; - /** - * Check compatibility between a geometry and a program - * @param geometry - Geometry instance. - * @param program - Program instance. - */ - GeometrySystem.prototype.checkCompatibility = function (geometry, program) { - // geometry must have at least all the attributes that the shader requires. - var geometryAttributes = geometry.attributes; - var shaderAttributes = program.attributeData; - for (var j in shaderAttributes) { - if (!geometryAttributes[j]) { - throw new Error("shader and geometry incompatible, geometry missing the \"" + j + "\" attribute"); - } - } - }; - /** - * Takes a geometry and program and generates a unique signature for them. - * @param geometry - To get signature from. - * @param program - To test geometry against. - * @returns - Unique signature of the geometry and program - */ - GeometrySystem.prototype.getSignature = function (geometry, program) { - var attribs = geometry.attributes; - var shaderAttributes = program.attributeData; - var strings = ['g', geometry.id]; - for (var i in attribs) { - if (shaderAttributes[i]) { - strings.push(i, shaderAttributes[i].location); - } - } - return strings.join('-'); - }; - /** - * Creates or gets Vao with the same structure as the geometry and stores it on the geometry. - * If vao is created, it is bound automatically. We use a shader to infer what and how to set up the - * attribute locations. - * @param geometry - Instance of geometry to to generate Vao for. - * @param shader - Instance of the shader. - * @param incRefCount - Increment refCount of all geometry buffers. - */ - GeometrySystem.prototype.initGeometryVao = function (geometry, shader, incRefCount) { - if (incRefCount === void 0) { incRefCount = true; } - var gl = this.gl; - var CONTEXT_UID = this.CONTEXT_UID; - var bufferSystem = this.renderer.buffer; - var program = shader.program; - if (!program.glPrograms[CONTEXT_UID]) { - this.renderer.shader.generateProgram(shader); - } - this.checkCompatibility(geometry, program); - var signature = this.getSignature(geometry, program); - var vaoObjectHash = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - var vao = vaoObjectHash[signature]; - if (vao) { - // this will give us easy access to the vao - vaoObjectHash[program.id] = vao; - return vao; - } - var buffers = geometry.buffers; - var attributes = geometry.attributes; - var tempStride = {}; - var tempStart = {}; - for (var j in buffers) { - tempStride[j] = 0; - tempStart[j] = 0; - } - for (var j in attributes) { - if (!attributes[j].size && program.attributeData[j]) { - attributes[j].size = program.attributeData[j].size; - } - else if (!attributes[j].size) { - console.warn("PIXI Geometry attribute '" + j + "' size cannot be determined (likely the bound shader does not have the attribute)"); // eslint-disable-line - } - tempStride[attributes[j].buffer] += attributes[j].size * byteSizeMap[attributes[j].type]; - } - for (var j in attributes) { - var attribute = attributes[j]; - var attribSize = attribute.size; - if (attribute.stride === undefined) { - if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) { - attribute.stride = 0; - } - else { - attribute.stride = tempStride[attribute.buffer]; - } - } - if (attribute.start === undefined) { - attribute.start = tempStart[attribute.buffer]; - tempStart[attribute.buffer] += attribSize * byteSizeMap[attribute.type]; - } - } - vao = gl.createVertexArray(); - gl.bindVertexArray(vao); - // first update - and create the buffers! - // only create a gl buffer if it actually gets - for (var i = 0; i < buffers.length; i++) { - var buffer = buffers[i]; - bufferSystem.bind(buffer); - if (incRefCount) { - buffer._glBuffers[CONTEXT_UID].refCount++; - } - } - // TODO - maybe make this a data object? - // lets wait to see if we need to first! - this.activateVao(geometry, program); - this._activeVao = vao; - // add it to the cache! - vaoObjectHash[program.id] = vao; - vaoObjectHash[signature] = vao; - return vao; - }; - /** - * Disposes geometry. - * @param geometry - Geometry with buffers. Only VAO will be disposed - * @param [contextLost=false] - If context was lost, we suppress deleteVertexArray - */ - GeometrySystem.prototype.disposeGeometry = function (geometry, contextLost) { - var _a; - if (!this.managedGeometries[geometry.id]) { - return; - } - delete this.managedGeometries[geometry.id]; - var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - var gl = this.gl; - var buffers = geometry.buffers; - var bufferSystem = (_a = this.renderer) === null || _a === void 0 ? void 0 : _a.buffer; - geometry.disposeRunner.remove(this); - if (!vaos) { - return; - } - // bufferSystem may have already been destroyed.. - // if this is the case, there is no need to destroy the geometry buffers... - // they already have been! - if (bufferSystem) { - for (var i = 0; i < buffers.length; i++) { - var buf = buffers[i]._glBuffers[this.CONTEXT_UID]; - // my be null as context may have changed right before the dispose is called - if (buf) { - buf.refCount--; - if (buf.refCount === 0 && !contextLost) { - bufferSystem.dispose(buffers[i], contextLost); - } - } - } - } - if (!contextLost) { - for (var vaoId in vaos) { - // delete only signatures, everything else are copies - if (vaoId[0] === 'g') { - var vao = vaos[vaoId]; - if (this._activeVao === vao) { - this.unbind(); - } - gl.deleteVertexArray(vao); - } - } - } - delete geometry.glVertexArrayObjects[this.CONTEXT_UID]; - }; - /** - * Dispose all WebGL resources of all managed geometries. - * @param [contextLost=false] - If context was lost, we suppress `gl.delete` calls - */ - GeometrySystem.prototype.disposeAll = function (contextLost) { - var all = Object.keys(this.managedGeometries); - for (var i = 0; i < all.length; i++) { - this.disposeGeometry(this.managedGeometries[all[i]], contextLost); - } - }; - /** - * Activate vertex array object. - * @param geometry - Geometry instance. - * @param program - Shader program instance. - */ - GeometrySystem.prototype.activateVao = function (geometry, program) { - var gl = this.gl; - var CONTEXT_UID = this.CONTEXT_UID; - var bufferSystem = this.renderer.buffer; - var buffers = geometry.buffers; - var attributes = geometry.attributes; - if (geometry.indexBuffer) { - // first update the index buffer if we have one.. - bufferSystem.bind(geometry.indexBuffer); - } - var lastBuffer = null; - // add a new one! - for (var j in attributes) { - var attribute = attributes[j]; - var buffer = buffers[attribute.buffer]; - var glBuffer = buffer._glBuffers[CONTEXT_UID]; - if (program.attributeData[j]) { - if (lastBuffer !== glBuffer) { - bufferSystem.bind(buffer); - lastBuffer = glBuffer; - } - var location = program.attributeData[j].location; - // TODO introduce state again - // we can optimise this for older devices that have no VAOs - gl.enableVertexAttribArray(location); - gl.vertexAttribPointer(location, attribute.size, attribute.type || gl.FLOAT, attribute.normalized, attribute.stride, attribute.start); - if (attribute.instance) { - // TODO calculate instance count based of this... - if (this.hasInstance) { - gl.vertexAttribDivisor(location, 1); - } - else { - throw new Error('geometry error, GPU Instancing is not supported on this device'); - } - } - } - } - }; - /** - * Draws the currently bound geometry. - * @param type - The type primitive to render. - * @param size - The number of elements to be rendered. If not specified, all vertices after the - * starting vertex will be drawn. - * @param start - The starting vertex in the geometry to start drawing from. If not specified, - * drawing will start from the first vertex. - * @param instanceCount - The number of instances of the set of elements to execute. If not specified, - * all instances will be drawn. - */ - GeometrySystem.prototype.draw = function (type, size, start, instanceCount) { - var gl = this.gl; - var geometry = this._activeGeometry; - // TODO.. this should not change so maybe cache the function? - if (geometry.indexBuffer) { - var byteSize = geometry.indexBuffer.data.BYTES_PER_ELEMENT; - var glType = byteSize === 2 ? gl.UNSIGNED_SHORT : gl.UNSIGNED_INT; - if (byteSize === 2 || (byteSize === 4 && this.canUseUInt32ElementIndex)) { - if (geometry.instanced) { - /* eslint-disable max-len */ - gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize, instanceCount || 1); - /* eslint-enable max-len */ - } - else { - /* eslint-disable max-len */ - gl.drawElements(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize); - /* eslint-enable max-len */ - } - } - else { - console.warn('unsupported index buffer type: uint32'); - } - } - else if (geometry.instanced) { - // TODO need a better way to calculate size.. - gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } - else { - gl.drawArrays(type, start, size || geometry.getSize()); - } - return this; - }; - /** Unbind/reset everything. */ - GeometrySystem.prototype.unbind = function () { - this.gl.bindVertexArray(null); - this._activeVao = null; - this._activeGeometry = null; - }; - GeometrySystem.prototype.destroy = function () { - this.renderer = null; - }; - return GeometrySystem; - }()); - - /** - * Component for masked elements. - * - * Holds mask mode and temporary data about current mask. - * @memberof PIXI - */ - var MaskData = /** @class */ (function () { - /** - * Create MaskData - * @param {PIXI.DisplayObject} [maskObject=null] - object that describes the mask - */ - function MaskData(maskObject) { - if (maskObject === void 0) { maskObject = null; } - this.type = exports.MASK_TYPES.NONE; - this.autoDetect = true; - this.maskObject = maskObject || null; - this.pooled = false; - this.isMaskData = true; - this.resolution = null; - this.multisample = settings.FILTER_MULTISAMPLE; - this.enabled = true; - this.colorMask = 0xf; - this._filters = null; - this._stencilCounter = 0; - this._scissorCounter = 0; - this._scissorRect = null; - this._scissorRectLocal = null; - this._colorMask = 0xf; - this._target = null; - } - Object.defineProperty(MaskData.prototype, "filter", { - /** - * The sprite mask filter. - * If set to `null`, the default sprite mask filter is used. - * @default null - */ - get: function () { - return this._filters ? this._filters[0] : null; - }, - set: function (value) { - if (value) { - if (this._filters) { - this._filters[0] = value; - } - else { - this._filters = [value]; - } - } - else { - this._filters = null; - } - }, - enumerable: false, - configurable: true - }); - /** Resets the mask data after popMask(). */ - MaskData.prototype.reset = function () { - if (this.pooled) { - this.maskObject = null; - this.type = exports.MASK_TYPES.NONE; - this.autoDetect = true; - } - this._target = null; - this._scissorRectLocal = null; - }; - /** - * Copies counters from maskData above, called from pushMask(). - * @param maskAbove - */ - MaskData.prototype.copyCountersOrReset = function (maskAbove) { - if (maskAbove) { - this._stencilCounter = maskAbove._stencilCounter; - this._scissorCounter = maskAbove._scissorCounter; - this._scissorRect = maskAbove._scissorRect; - } - else { - this._stencilCounter = 0; - this._scissorCounter = 0; - this._scissorRect = null; - } - }; - return MaskData; - }()); - - /** - * @private - * @param {WebGLRenderingContext} gl - The current WebGL context {WebGLProgram} - * @param {number} type - the type, can be either VERTEX_SHADER or FRAGMENT_SHADER - * @param {string} src - The vertex shader source as an array of strings. - * @returns {WebGLShader} the shader - */ - function compileShader(gl, type, src) { - var shader = gl.createShader(type); - gl.shaderSource(shader, src); - gl.compileShader(shader); - return shader; - } - - /** - * will log a shader error highlighting the lines with the error - * also will add numbers along the side. - * @param gl - the WebGLContext - * @param shader - the shader to log errors for - */ - function logPrettyShaderError(gl, shader) { - var shaderSrc = gl.getShaderSource(shader) - .split('\n') - .map(function (line, index) { return index + ": " + line; }); - var shaderLog = gl.getShaderInfoLog(shader); - var splitShader = shaderLog.split('\n'); - var dedupe = {}; - var lineNumbers = splitShader.map(function (line) { return parseFloat(line.replace(/^ERROR\: 0\:([\d]+)\:.*$/, '$1')); }) - .filter(function (n) { - if (n && !dedupe[n]) { - dedupe[n] = true; - return true; - } - return false; - }); - var logArgs = ['']; - lineNumbers.forEach(function (number) { - shaderSrc[number - 1] = "%c" + shaderSrc[number - 1] + "%c"; - logArgs.push('background: #FF0000; color:#FFFFFF; font-size: 10px', 'font-size: 10px'); - }); - var fragmentSourceToLog = shaderSrc - .join('\n'); - logArgs[0] = fragmentSourceToLog; - console.error(shaderLog); - // eslint-disable-next-line no-console - console.groupCollapsed('click to view full shader code'); - console.warn.apply(console, logArgs); - // eslint-disable-next-line no-console - console.groupEnd(); - } - /** - * - * logs out any program errors - * @param gl - The current WebGL context - * @param program - the WebGL program to display errors for - * @param vertexShader - the fragment WebGL shader program - * @param fragmentShader - the vertex WebGL shader program - */ - function logProgramError(gl, program, vertexShader, fragmentShader) { - // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { - if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) { - logPrettyShaderError(gl, vertexShader); - } - if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) { - logPrettyShaderError(gl, fragmentShader); - } - console.error('PixiJS Error: Could not initialize shader.'); - // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { - console.warn('PixiJS Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); - } - } - } - - function booleanArray(size) { - var array = new Array(size); - for (var i = 0; i < array.length; i++) { - array[i] = false; - } - return array; - } - /** - * @method defaultValue - * @memberof PIXI.glCore.shader - * @param {string} type - Type of value - * @param {number} size - * @private - */ - function defaultValue(type, size) { - switch (type) { - case 'float': - return 0; - case 'vec2': - return new Float32Array(2 * size); - case 'vec3': - return new Float32Array(3 * size); - case 'vec4': - return new Float32Array(4 * size); - case 'int': - case 'uint': - case 'sampler2D': - case 'sampler2DArray': - return 0; - case 'ivec2': - return new Int32Array(2 * size); - case 'ivec3': - return new Int32Array(3 * size); - case 'ivec4': - return new Int32Array(4 * size); - case 'uvec2': - return new Uint32Array(2 * size); - case 'uvec3': - return new Uint32Array(3 * size); - case 'uvec4': - return new Uint32Array(4 * size); - case 'bool': - return false; - case 'bvec2': - return booleanArray(2 * size); - case 'bvec3': - return booleanArray(3 * size); - case 'bvec4': - return booleanArray(4 * size); - case 'mat2': - return new Float32Array([1, 0, - 0, 1]); - case 'mat3': - return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); - case 'mat4': - return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); - } - return null; - } - - var unknownContext = {}; - var context = unknownContext; - /** - * returns a little WebGL context to use for program inspection. - * @static - * @private - * @returns {WebGLRenderingContext} a gl context to test with - */ - function getTestContext() { - if (context === unknownContext || (context && context.isContextLost())) { - var canvas = settings.ADAPTER.createCanvas(); - var gl = void 0; - if (settings.PREFER_ENV >= exports.ENV.WEBGL2) { - gl = canvas.getContext('webgl2', {}); - } - if (!gl) { - gl = (canvas.getContext('webgl', {}) - || canvas.getContext('experimental-webgl', {})); - if (!gl) { - // fail, not able to get a context - gl = null; - } - else { - // for shader testing.. - gl.getExtension('WEBGL_draw_buffers'); - } - } - context = gl; - } - return context; - } - - var maxFragmentPrecision; - function getMaxFragmentPrecision() { - if (!maxFragmentPrecision) { - maxFragmentPrecision = exports.PRECISION.MEDIUM; - var gl = getTestContext(); - if (gl) { - if (gl.getShaderPrecisionFormat) { - var shaderFragment = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT); - maxFragmentPrecision = shaderFragment.precision ? exports.PRECISION.HIGH : exports.PRECISION.MEDIUM; - } - } - } - return maxFragmentPrecision; - } - - /** - * Sets the float precision on the shader, ensuring the device supports the request precision. - * If the precision is already present, it just ensures that the device is able to handle it. - * @private - * @param {string} src - The shader source - * @param {PIXI.PRECISION} requestedPrecision - The request float precision of the shader. - * @param {PIXI.PRECISION} maxSupportedPrecision - The maximum precision the shader supports. - * @returns {string} modified shader source - */ - function setPrecision(src, requestedPrecision, maxSupportedPrecision) { - if (src.substring(0, 9) !== 'precision') { - // no precision supplied, so PixiJS will add the requested level. - var precision = requestedPrecision; - // If highp is requested but not supported, downgrade precision to a level all devices support. - if (requestedPrecision === exports.PRECISION.HIGH && maxSupportedPrecision !== exports.PRECISION.HIGH) { - precision = exports.PRECISION.MEDIUM; - } - return "precision " + precision + " float;\n" + src; - } - else if (maxSupportedPrecision !== exports.PRECISION.HIGH && src.substring(0, 15) === 'precision highp') { - // precision was supplied, but at a level this device does not support, so downgrading to mediump. - return src.replace('precision highp', 'precision mediump'); - } - return src; - } - - var GLSL_TO_SIZE = { - float: 1, - vec2: 2, - vec3: 3, - vec4: 4, - int: 1, - ivec2: 2, - ivec3: 3, - ivec4: 4, - uint: 1, - uvec2: 2, - uvec3: 3, - uvec4: 4, - bool: 1, - bvec2: 2, - bvec3: 3, - bvec4: 4, - mat2: 4, - mat3: 9, - mat4: 16, - sampler2D: 1, - }; - /** - * @private - * @method mapSize - * @memberof PIXI.glCore.shader - * @param {string} type - */ - function mapSize(type) { - return GLSL_TO_SIZE[type]; - } - - var GL_TABLE = null; - var GL_TO_GLSL_TYPES = { - FLOAT: 'float', - FLOAT_VEC2: 'vec2', - FLOAT_VEC3: 'vec3', - FLOAT_VEC4: 'vec4', - INT: 'int', - INT_VEC2: 'ivec2', - INT_VEC3: 'ivec3', - INT_VEC4: 'ivec4', - UNSIGNED_INT: 'uint', - UNSIGNED_INT_VEC2: 'uvec2', - UNSIGNED_INT_VEC3: 'uvec3', - UNSIGNED_INT_VEC4: 'uvec4', - BOOL: 'bool', - BOOL_VEC2: 'bvec2', - BOOL_VEC3: 'bvec3', - BOOL_VEC4: 'bvec4', - FLOAT_MAT2: 'mat2', - FLOAT_MAT3: 'mat3', - FLOAT_MAT4: 'mat4', - SAMPLER_2D: 'sampler2D', - INT_SAMPLER_2D: 'sampler2D', - UNSIGNED_INT_SAMPLER_2D: 'sampler2D', - SAMPLER_CUBE: 'samplerCube', - INT_SAMPLER_CUBE: 'samplerCube', - UNSIGNED_INT_SAMPLER_CUBE: 'samplerCube', - SAMPLER_2D_ARRAY: 'sampler2DArray', - INT_SAMPLER_2D_ARRAY: 'sampler2DArray', - UNSIGNED_INT_SAMPLER_2D_ARRAY: 'sampler2DArray', - }; - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types - function mapType(gl, type) { - if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); - GL_TABLE = {}; - for (var i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; - } - } - return GL_TABLE[type]; - } - - /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ - // Parsers, each one of these will take a look at the type of shader property and uniform. - // if they pass the test function then the code function is called that returns a the shader upload code for that uniform. - // Shader upload code is automagically generated with these parsers. - // If no parser is valid then the default upload functions are used. - // exposing Parsers means that custom upload logic can be added to pixi's shaders. - // A good example would be a pixi rectangle can be directly set on a uniform. - // If the shader sees it it knows how to upload the rectangle structure as a vec4 - // format is as follows: - // - // { - // test: (data, uniform) => {} <--- test is this code should be used for this uniform - // code: (name, uniform) => {} <--- returns the string of the piece of code that uploads the uniform - // codeUbo: (name, uniform) => {} <--- returns the string of the piece of code that uploads the - // uniform to a uniform buffer - // } - var uniformParsers = [ - // a float cache layer - { - test: function (data) { - return data.type === 'float' && data.size === 1 && !data.isArray; - }, - code: function (name) { - return "\n if(uv[\"" + name + "\"] !== ud[\"" + name + "\"].value)\n {\n ud[\"" + name + "\"].value = uv[\"" + name + "\"]\n gl.uniform1f(ud[\"" + name + "\"].location, uv[\"" + name + "\"])\n }\n "; - }, - }, - // handling samplers - { - test: function (data, uniform) { - // eslint-disable-next-line max-len,no-eq-null,eqeqeq - return (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray && (uniform == null || uniform.castToBaseTexture !== undefined); - }, - code: function (name) { return "t = syncData.textureCount++;\n\n renderer.texture.bind(uv[\"" + name + "\"], t);\n\n if(ud[\"" + name + "\"].value !== t)\n {\n ud[\"" + name + "\"].value = t;\n gl.uniform1i(ud[\"" + name + "\"].location, t);\n; // eslint-disable-line max-len\n }"; }, - }, - // uploading pixi matrix object to mat3 - { - test: function (data, uniform) { - return data.type === 'mat3' && data.size === 1 && !data.isArray && uniform.a !== undefined; - }, - code: function (name) { - // TODO and some smart caching dirty ids here! - return "\n gl.uniformMatrix3fv(ud[\"" + name + "\"].location, false, uv[\"" + name + "\"].toArray(true));\n "; - }, - codeUbo: function (name) { - return "\n var " + name + "_matrix = uv." + name + ".toArray(true);\n\n data[offset] = " + name + "_matrix[0];\n data[offset+1] = " + name + "_matrix[1];\n data[offset+2] = " + name + "_matrix[2];\n \n data[offset + 4] = " + name + "_matrix[3];\n data[offset + 5] = " + name + "_matrix[4];\n data[offset + 6] = " + name + "_matrix[5];\n \n data[offset + 8] = " + name + "_matrix[6];\n data[offset + 9] = " + name + "_matrix[7];\n data[offset + 10] = " + name + "_matrix[8];\n "; - }, - }, - // uploading a pixi point as a vec2 with caching layer - { - test: function (data, uniform) { - return data.type === 'vec2' && data.size === 1 && !data.isArray && uniform.x !== undefined; - }, - code: function (name) { - return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v.x || cv[1] !== v.y)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n gl.uniform2f(ud[\"" + name + "\"].location, v.x, v.y);\n }"; - }, - codeUbo: function (name) { - return "\n v = uv." + name + ";\n\n data[offset] = v.x;\n data[offset+1] = v.y;\n "; - } - }, - // caching layer for a vec2 - { - test: function (data) { - return data.type === 'vec2' && data.size === 1 && !data.isArray; - }, - code: function (name) { - return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n gl.uniform2f(ud[\"" + name + "\"].location, v[0], v[1]);\n }\n "; - }, - }, - // upload a pixi rectangle as a vec4 with caching layer - { - test: function (data, uniform) { - return data.type === 'vec4' && data.size === 1 && !data.isArray && uniform.width !== undefined; - }, - code: function (name) { - return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.width || cv[3] !== v.height)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n cv[2] = v.width;\n cv[3] = v.height;\n gl.uniform4f(ud[\"" + name + "\"].location, v.x, v.y, v.width, v.height)\n }"; - }, - codeUbo: function (name) { - return "\n v = uv." + name + ";\n\n data[offset] = v.x;\n data[offset+1] = v.y;\n data[offset+2] = v.width;\n data[offset+3] = v.height;\n "; - } - }, - // a caching layer for vec4 uploading - { - test: function (data) { - return data.type === 'vec4' && data.size === 1 && !data.isArray; - }, - code: function (name) { - return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(ud[\"" + name + "\"].location, v[0], v[1], v[2], v[3])\n }"; - }, - } ]; - - // cu = Cached value's uniform data field - // cv = Cached value - // v = value to upload - // ud = uniformData - // uv = uniformValue - // l = location - var GLSL_TO_SINGLE_SETTERS_CACHED = { - float: "\n if (cv !== v)\n {\n cu.value = v;\n gl.uniform1f(location, v);\n }", - vec2: "\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2f(location, v[0], v[1])\n }", - vec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3f(location, v[0], v[1], v[2])\n }", - vec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(location, v[0], v[1], v[2], v[3]);\n }", - int: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }", - ivec2: "\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2i(location, v[0], v[1]);\n }", - ivec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3i(location, v[0], v[1], v[2]);\n }", - ivec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n }", - uint: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1ui(location, v);\n }", - uvec2: "\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2ui(location, v[0], v[1]);\n }", - uvec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3ui(location, v[0], v[1], v[2]);\n }", - uvec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4ui(location, v[0], v[1], v[2], v[3]);\n }", - bool: "\n if (cv !== v)\n {\n cu.value = v;\n gl.uniform1i(location, v);\n }", - bvec2: "\n if (cv[0] != v[0] || cv[1] != v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2i(location, v[0], v[1]);\n }", - bvec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3i(location, v[0], v[1], v[2]);\n }", - bvec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n }", - mat2: 'gl.uniformMatrix2fv(location, false, v)', - mat3: 'gl.uniformMatrix3fv(location, false, v)', - mat4: 'gl.uniformMatrix4fv(location, false, v)', - sampler2D: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }", - samplerCube: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }", - sampler2DArray: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }", - }; - var GLSL_TO_ARRAY_SETTERS = { - float: "gl.uniform1fv(location, v)", - vec2: "gl.uniform2fv(location, v)", - vec3: "gl.uniform3fv(location, v)", - vec4: 'gl.uniform4fv(location, v)', - mat4: 'gl.uniformMatrix4fv(location, false, v)', - mat3: 'gl.uniformMatrix3fv(location, false, v)', - mat2: 'gl.uniformMatrix2fv(location, false, v)', - int: 'gl.uniform1iv(location, v)', - ivec2: 'gl.uniform2iv(location, v)', - ivec3: 'gl.uniform3iv(location, v)', - ivec4: 'gl.uniform4iv(location, v)', - uint: 'gl.uniform1uiv(location, v)', - uvec2: 'gl.uniform2uiv(location, v)', - uvec3: 'gl.uniform3uiv(location, v)', - uvec4: 'gl.uniform4uiv(location, v)', - bool: 'gl.uniform1iv(location, v)', - bvec2: 'gl.uniform2iv(location, v)', - bvec3: 'gl.uniform3iv(location, v)', - bvec4: 'gl.uniform4iv(location, v)', - sampler2D: 'gl.uniform1iv(location, v)', - samplerCube: 'gl.uniform1iv(location, v)', - sampler2DArray: 'gl.uniform1iv(location, v)', - }; - function generateUniformsSync(group, uniformData) { - var _a; - var funcFragments = ["\n var v = null;\n var cv = null;\n var cu = null;\n var t = 0;\n var gl = renderer.gl;\n "]; - for (var i in group.uniforms) { - var data = uniformData[i]; - if (!data) { - if ((_a = group.uniforms[i]) === null || _a === void 0 ? void 0 : _a.group) { - if (group.uniforms[i].ubo) { - funcFragments.push("\n renderer.shader.syncUniformBufferGroup(uv." + i + ", '" + i + "');\n "); - } - else { - funcFragments.push("\n renderer.shader.syncUniformGroup(uv." + i + ", syncData);\n "); - } - } - continue; - } - var uniform = group.uniforms[i]; - var parsed = false; - for (var j = 0; j < uniformParsers.length; j++) { - if (uniformParsers[j].test(data, uniform)) { - funcFragments.push(uniformParsers[j].code(i, uniform)); - parsed = true; - break; - } - } - if (!parsed) { - var templateType = data.size === 1 && !data.isArray ? GLSL_TO_SINGLE_SETTERS_CACHED : GLSL_TO_ARRAY_SETTERS; - var template = templateType[data.type].replace('location', "ud[\"" + i + "\"].location"); - funcFragments.push("\n cu = ud[\"" + i + "\"];\n cv = cu.value;\n v = uv[\"" + i + "\"];\n " + template + ";"); - } - } - /* - * the introduction of syncData is to solve an issue where textures in uniform groups are not set correctly - * the texture count was always starting from 0 in each group. This needs to increment each time a texture is used - * no matter which group is being used - * - */ - // eslint-disable-next-line no-new-func - return new Function('ud', 'uv', 'renderer', 'syncData', funcFragments.join('\n')); - } - - var fragTemplate$1 = [ - 'precision mediump float;', - 'void main(void){', - 'float test = 0.1;', - '%forloop%', - 'gl_FragColor = vec4(0.0);', - '}' ].join('\n'); - function generateIfTestSrc(maxIfs) { - var src = ''; - for (var i = 0; i < maxIfs; ++i) { - if (i > 0) { - src += '\nelse '; - } - if (i < maxIfs - 1) { - src += "if(test == " + i + ".0){}"; - } - } - return src; - } - function checkMaxIfStatementsInShader(maxIfs, gl) { - if (maxIfs === 0) { - throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); - } - var shader = gl.createShader(gl.FRAGMENT_SHADER); - while (true) // eslint-disable-line no-constant-condition - { - var fragmentSrc = fragTemplate$1.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); - gl.shaderSource(shader, fragmentSrc); - gl.compileShader(shader); - if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - maxIfs = (maxIfs / 2) | 0; - } - else { - // valid! - break; - } - } - return maxIfs; - } - - // Cache the result to prevent running this over and over - var unsafeEval; - /** - * Not all platforms allow to generate function code (e.g., `new Function`). - * this provides the platform-level detection. - * @private - * @returns {boolean} `true` if `new Function` is supported. - */ - function unsafeEvalSupported() { - if (typeof unsafeEval === 'boolean') { - return unsafeEval; - } - try { - /* eslint-disable no-new-func */ - var func = new Function('param1', 'param2', 'param3', 'return param1[param2] === param3;'); - /* eslint-enable no-new-func */ - unsafeEval = func({ a: 'b' }, 'a', 'b') === true; - } - catch (e) { - unsafeEval = false; - } - return unsafeEval; - } - - var defaultFragment$2 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor *= texture2D(uSampler, vTextureCoord);\n}"; - - var defaultVertex$3 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}\n"; - - var UID$1 = 0; - var nameCache = {}; - /** - * Helper class to create a shader program. - * @memberof PIXI - */ - var Program = /** @class */ (function () { - /** - * @param vertexSrc - The source of the vertex shader. - * @param fragmentSrc - The source of the fragment shader. - * @param name - Name for shader - */ - function Program(vertexSrc, fragmentSrc, name) { - if (name === void 0) { name = 'pixi-shader'; } - this.id = UID$1++; - this.vertexSrc = vertexSrc || Program.defaultVertexSrc; - this.fragmentSrc = fragmentSrc || Program.defaultFragmentSrc; - this.vertexSrc = this.vertexSrc.trim(); - this.fragmentSrc = this.fragmentSrc.trim(); - if (this.vertexSrc.substring(0, 8) !== '#version') { - name = name.replace(/\s+/g, '-'); - if (nameCache[name]) { - nameCache[name]++; - name += "-" + nameCache[name]; - } - else { - nameCache[name] = 1; - } - this.vertexSrc = "#define SHADER_NAME " + name + "\n" + this.vertexSrc; - this.fragmentSrc = "#define SHADER_NAME " + name + "\n" + this.fragmentSrc; - this.vertexSrc = setPrecision(this.vertexSrc, settings.PRECISION_VERTEX, exports.PRECISION.HIGH); - this.fragmentSrc = setPrecision(this.fragmentSrc, settings.PRECISION_FRAGMENT, getMaxFragmentPrecision()); - } - // currently this does not extract structs only default types - // this is where we store shader references.. - this.glPrograms = {}; - this.syncUniforms = null; - } - Object.defineProperty(Program, "defaultVertexSrc", { - /** - * The default vertex shader source. - * @constant - */ - get: function () { - return defaultVertex$3; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Program, "defaultFragmentSrc", { - /** - * The default fragment shader source. - * @constant - */ - get: function () { - return defaultFragment$2; - }, - enumerable: false, - configurable: true - }); - /** - * A short hand function to create a program based of a vertex and fragment shader. - * - * This method will also check to see if there is a cached program. - * @param vertexSrc - The source of the vertex shader. - * @param fragmentSrc - The source of the fragment shader. - * @param name - Name for shader - * @returns A shiny new PixiJS shader program! - */ - Program.from = function (vertexSrc, fragmentSrc, name) { - var key = vertexSrc + fragmentSrc; - var program = ProgramCache[key]; - if (!program) { - ProgramCache[key] = program = new Program(vertexSrc, fragmentSrc, name); - } - return program; - }; - return Program; - }()); - - /** - * A helper class for shaders. - * @memberof PIXI - */ - var Shader = /** @class */ (function () { - /** - * @param program - The program the shader will use. - * @param uniforms - Custom uniforms to use to augment the built-in ones. - */ - function Shader(program, uniforms) { - /** - * Used internally to bind uniform buffer objects. - * @ignore - */ - this.uniformBindCount = 0; - this.program = program; - // lets see whats been passed in - // uniforms should be converted to a uniform group - if (uniforms) { - if (uniforms instanceof UniformGroup) { - this.uniformGroup = uniforms; - } - else { - this.uniformGroup = new UniformGroup(uniforms); - } - } - else { - this.uniformGroup = new UniformGroup({}); - } - this.disposeRunner = new Runner('disposeShader'); - } - // TODO move to shader system.. - Shader.prototype.checkUniformExists = function (name, group) { - if (group.uniforms[name]) { - return true; - } - for (var i in group.uniforms) { - var uniform = group.uniforms[i]; - if (uniform.group) { - if (this.checkUniformExists(name, uniform)) { - return true; - } - } - } - return false; - }; - Shader.prototype.destroy = function () { - // usage count on programs? - // remove if not used! - this.uniformGroup = null; - this.disposeRunner.emit(this); - this.disposeRunner.destroy(); - }; - Object.defineProperty(Shader.prototype, "uniforms", { - /** - * Shader uniform values, shortcut for `uniformGroup.uniforms`. - * @readonly - */ - get: function () { - return this.uniformGroup.uniforms; - }, - enumerable: false, - configurable: true - }); - /** - * A short hand function to create a shader based of a vertex and fragment shader. - * @param vertexSrc - The source of the vertex shader. - * @param fragmentSrc - The source of the fragment shader. - * @param uniforms - Custom uniforms to use to augment the built-in ones. - * @returns A shiny new PixiJS shader! - */ - Shader.from = function (vertexSrc, fragmentSrc, uniforms) { - var program = Program.from(vertexSrc, fragmentSrc); - return new Shader(program, uniforms); - }; - return Shader; - }()); - - /* eslint-disable max-len */ - var BLEND$1 = 0; - var OFFSET$1 = 1; - var CULLING$1 = 2; - var DEPTH_TEST$1 = 3; - var WINDING$1 = 4; - var DEPTH_MASK$1 = 5; - /** - * This is a WebGL state, and is is passed to {@link PIXI.StateSystem}. - * - * Each mesh rendered may require WebGL to be in a different state. - * For example you may want different blend mode or to enable polygon offsets - * @memberof PIXI - */ - var State = /** @class */ (function () { - function State() { - this.data = 0; - this.blendMode = exports.BLEND_MODES.NORMAL; - this.polygonOffset = 0; - this.blend = true; - this.depthMask = true; - // this.depthTest = true; - } - Object.defineProperty(State.prototype, "blend", { - /** - * Activates blending of the computed fragment color values. - * @default true - */ - get: function () { - return !!(this.data & (1 << BLEND$1)); - }, - set: function (value) { - if (!!(this.data & (1 << BLEND$1)) !== value) { - this.data ^= (1 << BLEND$1); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(State.prototype, "offsets", { - /** - * Activates adding an offset to depth values of polygon's fragments - * @default false - */ - get: function () { - return !!(this.data & (1 << OFFSET$1)); - }, - set: function (value) { - if (!!(this.data & (1 << OFFSET$1)) !== value) { - this.data ^= (1 << OFFSET$1); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(State.prototype, "culling", { - /** - * Activates culling of polygons. - * @default false - */ - get: function () { - return !!(this.data & (1 << CULLING$1)); - }, - set: function (value) { - if (!!(this.data & (1 << CULLING$1)) !== value) { - this.data ^= (1 << CULLING$1); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(State.prototype, "depthTest", { - /** - * Activates depth comparisons and updates to the depth buffer. - * @default false - */ - get: function () { - return !!(this.data & (1 << DEPTH_TEST$1)); - }, - set: function (value) { - if (!!(this.data & (1 << DEPTH_TEST$1)) !== value) { - this.data ^= (1 << DEPTH_TEST$1); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(State.prototype, "depthMask", { - /** - * Enables or disables writing to the depth buffer. - * @default true - */ - get: function () { - return !!(this.data & (1 << DEPTH_MASK$1)); - }, - set: function (value) { - if (!!(this.data & (1 << DEPTH_MASK$1)) !== value) { - this.data ^= (1 << DEPTH_MASK$1); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(State.prototype, "clockwiseFrontFace", { - /** - * Specifies whether or not front or back-facing polygons can be culled. - * @default false - */ - get: function () { - return !!(this.data & (1 << WINDING$1)); - }, - set: function (value) { - if (!!(this.data & (1 << WINDING$1)) !== value) { - this.data ^= (1 << WINDING$1); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(State.prototype, "blendMode", { - /** - * The blend mode to be applied when this state is set. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. - * Setting this mode to anything other than NO_BLEND will automatically switch blending on. - * @default PIXI.BLEND_MODES.NORMAL - */ - get: function () { - return this._blendMode; - }, - set: function (value) { - this.blend = (value !== exports.BLEND_MODES.NONE); - this._blendMode = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(State.prototype, "polygonOffset", { - /** - * The polygon offset. Setting this property to anything other than 0 will automatically enable polygon offset fill. - * @default 0 - */ - get: function () { - return this._polygonOffset; - }, - set: function (value) { - this.offsets = !!value; - this._polygonOffset = value; - }, - enumerable: false, - configurable: true - }); - State.prototype.toString = function () { - return "[@pixi/core:State " - + ("blendMode=" + this.blendMode + " ") - + ("clockwiseFrontFace=" + this.clockwiseFrontFace + " ") - + ("culling=" + this.culling + " ") - + ("depthMask=" + this.depthMask + " ") - + ("polygonOffset=" + this.polygonOffset) - + "]"; - }; - State.for2d = function () { - var state = new State(); - state.depthTest = false; - state.blend = true; - return state; - }; - return State; - }()); - - var defaultFragment$1 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n"; - - var defaultVertex$2 = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"; - - /** - * A filter is a special shader that applies post-processing effects to an input texture and writes into an output - * render-target. - * - * {@link http://pixijs.io/examples/#/filters/blur-filter.js Example} of the - * {@link PIXI.filters.BlurFilter BlurFilter}. - * - * ### Usage - * Filters can be applied to any DisplayObject or Container. - * PixiJS' `FilterSystem` renders the container into temporary Framebuffer, - * then filter renders it to the screen. - * Multiple filters can be added to the `filters` array property and stacked on each other. - * - * ``` - * const filter = new PIXI.Filter(myShaderVert, myShaderFrag, { myUniform: 0.5 }); - * const container = new PIXI.Container(); - * container.filters = [filter]; - * ``` - * - * ### Previous Version Differences - * - * In PixiJS **v3**, a filter was always applied to _whole screen_. - * - * In PixiJS **v4**, a filter can be applied _only part of the screen_. - * Developers had to create a set of uniforms to deal with coordinates. - * - * In PixiJS **v5** combines _both approaches_. - * Developers can use normal coordinates of v3 and then allow filter to use partial Framebuffers, - * bringing those extra uniforms into account. - * - * Also be aware that we have changed default vertex shader, please consult - * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}. - * - * ### Frames - * - * The following table summarizes the coordinate spaces used in the filtering pipeline: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Coordinate SpaceDescription
Texture Coordinates - * The texture (or UV) coordinates in the input base-texture's space. These are normalized into the (0,1) range along - * both axes. - *
World Space - * A point in the same space as the world bounds of any display-object (i.e. in the scene graph's space). - *
Physical Pixels - * This is base-texture's space with the origin on the top-left. You can calculate these by multiplying the texture - * coordinates by the dimensions of the texture. - *
- * - * ### Built-in Uniforms - * - * PixiJS viewport uses screen (CSS) coordinates, `(0, 0, renderer.screen.width, renderer.screen.height)`, - * and `projectionMatrix` uniform maps it to the gl viewport. - * - * **uSampler** - * - * The most important uniform is the input texture that container was rendered into. - * _Important note: as with all Framebuffers in PixiJS, both input and output are - * premultiplied by alpha._ - * - * By default, input normalized coordinates are passed to fragment shader with `vTextureCoord`. - * Use it to sample the input. - * - * ``` - * const fragment = ` - * varying vec2 vTextureCoord; - * uniform sampler2D uSampler; - * void main(void) - * { - * gl_FragColor = texture2D(uSampler, vTextureCoord); - * } - * `; - * - * const myFilter = new PIXI.Filter(null, fragment); - * ``` - * - * This filter is just one uniform less than {@link PIXI.filters.AlphaFilter AlphaFilter}. - * - * **outputFrame** - * - * The `outputFrame` holds the rectangle where filter is applied in screen (CSS) coordinates. - * It's the same as `renderer.screen` for a fullscreen filter. - * Only a part of `outputFrame.zw` size of temporary Framebuffer is used, - * `(0, 0, outputFrame.width, outputFrame.height)`, - * - * Filters uses this quad to normalized (0-1) space, its passed into `aVertexPosition` attribute. - * To calculate vertex position in screen space using normalized (0-1) space: - * - * ``` - * vec4 filterVertexPosition( void ) - * { - * vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy; - * return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0); - * } - * ``` - * - * **inputSize** - * - * Temporary framebuffer is different, it can be either the size of screen, either power-of-two. - * The `inputSize.xy` are size of temporary framebuffer that holds input. - * The `inputSize.zw` is inverted, it's a shortcut to evade division inside the shader. - * - * Set `inputSize.xy = outputFrame.zw` for a fullscreen filter. - * - * To calculate input normalized coordinate, you have to map it to filter normalized space. - * Multiply by `outputFrame.zw` to get input coordinate. - * Divide by `inputSize.xy` to get input normalized coordinate. - * - * ``` - * vec2 filterTextureCoord( void ) - * { - * return aVertexPosition * (outputFrame.zw * inputSize.zw); // same as /inputSize.xy - * } - * ``` - * **resolution** - * - * The `resolution` is the ratio of screen (CSS) pixels to real pixels. - * - * **inputPixel** - * - * `inputPixel.xy` is the size of framebuffer in real pixels, same as `inputSize.xy * resolution` - * `inputPixel.zw` is inverted `inputPixel.xy`. - * - * It's handy for filters that use neighbour pixels, like {@link PIXI.filters.FXAAFilter FXAAFilter}. - * - * **inputClamp** - * - * If you try to get info from outside of used part of Framebuffer - you'll get undefined behaviour. - * For displacements, coordinates has to be clamped. - * - * The `inputClamp.xy` is left-top pixel center, you may ignore it, because we use left-top part of Framebuffer - * `inputClamp.zw` is bottom-right pixel center. - * - * ``` - * vec4 color = texture2D(uSampler, clamp(modifiedTextureCoord, inputClamp.xy, inputClamp.zw)) - * ``` - * OR - * ``` - * vec4 color = texture2D(uSampler, min(modifigedTextureCoord, inputClamp.zw)) - * ``` - * - * ### Additional Information - * - * Complete documentation on Filter usage is located in the - * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}. - * - * Since PixiJS only had a handful of built-in filters, additional filters can be downloaded - * {@link https://github.com/pixijs/pixi-filters here} from the PixiJS Filters repository. - * @memberof PIXI - */ - var Filter = /** @class */ (function (_super) { - __extends$i(Filter, _super); - /** - * @param vertexSrc - The source of the vertex shader. - * @param fragmentSrc - The source of the fragment shader. - * @param uniforms - Custom uniforms to use to augment the built-in ones. - */ - function Filter(vertexSrc, fragmentSrc, uniforms) { - var _this = this; - var program = Program.from(vertexSrc || Filter.defaultVertexSrc, fragmentSrc || Filter.defaultFragmentSrc); - _this = _super.call(this, program, uniforms) || this; - _this.padding = 0; - _this.resolution = settings.FILTER_RESOLUTION; - _this.multisample = settings.FILTER_MULTISAMPLE; - _this.enabled = true; - _this.autoFit = true; - _this.state = new State(); - return _this; - } - /** - * Applies the filter - * @param {PIXI.FilterSystem} filterManager - The renderer to retrieve the filter from - * @param {PIXI.RenderTexture} input - The input render target. - * @param {PIXI.RenderTexture} output - The target to output to. - * @param {PIXI.CLEAR_MODES} [clearMode] - Should the output be cleared before rendering to it. - * @param {object} [_currentState] - It's current state of filter. - * There are some useful properties in the currentState : - * target, filters, sourceFrame, destinationFrame, renderTarget, resolution - */ - Filter.prototype.apply = function (filterManager, input, output, clearMode, _currentState) { - // do as you please! - filterManager.applyFilter(this, input, output, clearMode); - // or just do a regular render.. - }; - Object.defineProperty(Filter.prototype, "blendMode", { - /** - * Sets the blend mode of the filter. - * @default PIXI.BLEND_MODES.NORMAL - */ - get: function () { - return this.state.blendMode; - }, - set: function (value) { - this.state.blendMode = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Filter.prototype, "resolution", { - /** - * The resolution of the filter. Setting this to be lower will lower the quality but - * increase the performance of the filter. - */ - get: function () { - return this._resolution; - }, - set: function (value) { - this._resolution = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Filter, "defaultVertexSrc", { - /** - * The default vertex shader source - * @constant - */ - get: function () { - return defaultVertex$2; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Filter, "defaultFragmentSrc", { - /** - * The default fragment shader source - * @constant - */ - get: function () { - return defaultFragment$1; - }, - enumerable: false, - configurable: true - }); - return Filter; - }(Shader)); - - var vertex$4 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n"; - - var fragment$7 = "varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform float npmAlpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);\n\n original *= (alphaMul * masky.r * alpha * clip);\n\n gl_FragColor = original;\n}\n"; - - var tempMat$1 = new Matrix(); - /** - * Class controls uv mapping from Texture normal space to BaseTexture normal space. - * - * Takes `trim` and `rotate` into account. May contain clamp settings for Meshes and TilingSprite. - * - * Can be used in Texture `uvMatrix` field, or separately, you can use different clamp settings on the same texture. - * If you want to add support for texture region of certain feature or filter, that's what you're looking for. - * - * Takes track of Texture changes through `_lastTextureID` private field. - * Use `update()` method call to track it from outside. - * @see PIXI.Texture - * @see PIXI.Mesh - * @see PIXI.TilingSprite - * @memberof PIXI - */ - var TextureMatrix = /** @class */ (function () { - /** - * @param texture - observed texture - * @param clampMargin - Changes frame clamping, 0.5 by default. Use -0.5 for extra border. - */ - function TextureMatrix(texture, clampMargin) { - this._texture = texture; - this.mapCoord = new Matrix(); - this.uClampFrame = new Float32Array(4); - this.uClampOffset = new Float32Array(2); - this._textureID = -1; - this._updateID = 0; - this.clampOffset = 0; - this.clampMargin = (typeof clampMargin === 'undefined') ? 0.5 : clampMargin; - this.isSimple = false; - } - Object.defineProperty(TextureMatrix.prototype, "texture", { - /** Texture property. */ - get: function () { - return this._texture; - }, - set: function (value) { - this._texture = value; - this._textureID = -1; - }, - enumerable: false, - configurable: true - }); - /** - * Multiplies uvs array to transform - * @param uvs - mesh uvs - * @param [out=uvs] - output - * @returns - output - */ - TextureMatrix.prototype.multiplyUvs = function (uvs, out) { - if (out === undefined) { - out = uvs; - } - var mat = this.mapCoord; - for (var i = 0; i < uvs.length; i += 2) { - var x = uvs[i]; - var y = uvs[i + 1]; - out[i] = (x * mat.a) + (y * mat.c) + mat.tx; - out[i + 1] = (x * mat.b) + (y * mat.d) + mat.ty; - } - return out; - }; - /** - * Updates matrices if texture was changed. - * @param [forceUpdate=false] - if true, matrices will be updated any case - * @returns - Whether or not it was updated - */ - TextureMatrix.prototype.update = function (forceUpdate) { - var tex = this._texture; - if (!tex || !tex.valid) { - return false; - } - if (!forceUpdate - && this._textureID === tex._updateID) { - return false; - } - this._textureID = tex._updateID; - this._updateID++; - var uvs = tex._uvs; - this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); - var orig = tex.orig; - var trim = tex.trim; - if (trim) { - tempMat$1.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); - this.mapCoord.append(tempMat$1); - } - var texBase = tex.baseTexture; - var frame = this.uClampFrame; - var margin = this.clampMargin / texBase.resolution; - var offset = this.clampOffset; - frame[0] = (tex._frame.x + margin + offset) / texBase.width; - frame[1] = (tex._frame.y + margin + offset) / texBase.height; - frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; - frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; - this.uClampOffset[0] = offset / texBase.realWidth; - this.uClampOffset[1] = offset / texBase.realHeight; - this.isSimple = tex._frame.width === texBase.width - && tex._frame.height === texBase.height - && tex.rotate === 0; - return true; - }; - return TextureMatrix; - }()); - - /** - * This handles a Sprite acting as a mask, as opposed to a Graphic. - * - * WebGL only. - * @memberof PIXI - */ - var SpriteMaskFilter = /** @class */ (function (_super) { - __extends$i(SpriteMaskFilter, _super); - /** @ignore */ - function SpriteMaskFilter(vertexSrc, fragmentSrc, uniforms) { - var _this = this; - var sprite = null; - if (typeof vertexSrc !== 'string' && fragmentSrc === undefined && uniforms === undefined) { - sprite = vertexSrc; - vertexSrc = undefined; - fragmentSrc = undefined; - uniforms = undefined; - } - _this = _super.call(this, vertexSrc || vertex$4, fragmentSrc || fragment$7, uniforms) || this; - _this.maskSprite = sprite; - _this.maskMatrix = new Matrix(); - return _this; - } - Object.defineProperty(SpriteMaskFilter.prototype, "maskSprite", { - /** - * Sprite mask - * @type {PIXI.DisplayObject} - */ - get: function () { - return this._maskSprite; - }, - set: function (value) { - this._maskSprite = value; - if (this._maskSprite) { - this._maskSprite.renderable = false; - } - }, - enumerable: false, - configurable: true - }); - /** - * Applies the filter - * @param filterManager - The renderer to retrieve the filter from - * @param input - The input render target. - * @param output - The target to output to. - * @param clearMode - Should the output be cleared before rendering to it. - */ - SpriteMaskFilter.prototype.apply = function (filterManager, input, output, clearMode) { - var maskSprite = this._maskSprite; - var tex = maskSprite._texture; - if (!tex.valid) { - return; - } - if (!tex.uvMatrix) { - // margin = 0.0, let it bleed a bit, shader code becomes easier - // assuming that atlas textures were made with 1-pixel padding - tex.uvMatrix = new TextureMatrix(tex, 0.0); - } - tex.uvMatrix.update(); - this.uniforms.npmAlpha = tex.baseTexture.alphaMode ? 0.0 : 1.0; - this.uniforms.mask = tex; - // get _normalized sprite texture coords_ and convert them to _normalized atlas texture coords_ with `prepend` - this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite) - .prepend(tex.uvMatrix.mapCoord); - this.uniforms.alpha = maskSprite.worldAlpha; - this.uniforms.maskClamp = tex.uvMatrix.uClampFrame; - filterManager.applyFilter(this, input, output, clearMode); - }; - return SpriteMaskFilter; - }(Filter)); - - /** - * System plugin to the renderer to manage masks. - * - * There are three built-in types of masking: - * **Scissor Masking**: Scissor masking discards pixels that are outside of a rectangle called the scissor box. It is - * the most performant as the scissor test is inexpensive. However, it can only be used when the mask is rectangular. - * **Stencil Masking**: Stencil masking discards pixels that don't overlap with the pixels rendered into the stencil - * buffer. It is the next fastest option as it does not require rendering into a separate framebuffer. However, it does - * cause the mask to be rendered **twice** for each masking operation; hence, minimize the rendering cost of your masks. - * **Sprite Mask Filtering**: Sprite mask filtering discards pixels based on the red channel of the sprite-mask's - * texture. (Generally, the masking texture is grayscale). Using advanced techniques, you might be able to embed this - * type of masking in a custom shader - and hence, bypassing the masking system fully for performance wins. - * - * The best type of masking is auto-detected when you `push` one. To use scissor masking, you must pass in a `Graphics` - * object with just a rectangle drawn. - * - * ## Mask Stacks - * - * In the scene graph, masks can be applied recursively, i.e. a mask can be applied during a masking operation. The mask - * stack stores the currently applied masks in order. Each {@link PIXI.BaseRenderTexture} holds its own mask stack, i.e. - * when you switch render-textures, the old masks only applied when you switch back to rendering to the old render-target. - * @memberof PIXI - */ - var MaskSystem = /** @class */ (function () { - /** - * @param renderer - The renderer this System works for. - */ - function MaskSystem(renderer) { - this.renderer = renderer; - this.enableScissor = true; - this.alphaMaskPool = []; - this.maskDataPool = []; - this.maskStack = []; - this.alphaMaskIndex = 0; - } - /** - * Changes the mask stack that is used by this System. - * @param maskStack - The mask stack - */ - MaskSystem.prototype.setMaskStack = function (maskStack) { - this.maskStack = maskStack; - this.renderer.scissor.setMaskStack(maskStack); - this.renderer.stencil.setMaskStack(maskStack); - }; - /** - * Enables the mask and appends it to the current mask stack. - * - * NOTE: The batch renderer should be flushed beforehand to prevent pending renders from being masked. - * @param {PIXI.DisplayObject} target - Display Object to push the mask to - * @param {PIXI.MaskData|PIXI.Sprite|PIXI.Graphics|PIXI.DisplayObject} maskDataOrTarget - The masking data. - */ - MaskSystem.prototype.push = function (target, maskDataOrTarget) { - var maskData = maskDataOrTarget; - if (!maskData.isMaskData) { - var d = this.maskDataPool.pop() || new MaskData(); - d.pooled = true; - d.maskObject = maskDataOrTarget; - maskData = d; - } - var maskAbove = this.maskStack.length !== 0 ? this.maskStack[this.maskStack.length - 1] : null; - maskData.copyCountersOrReset(maskAbove); - maskData._colorMask = maskAbove ? maskAbove._colorMask : 0xf; - if (maskData.autoDetect) { - this.detect(maskData); - } - maskData._target = target; - if (maskData.type !== exports.MASK_TYPES.SPRITE) { - this.maskStack.push(maskData); - } - if (maskData.enabled) { - switch (maskData.type) { - case exports.MASK_TYPES.SCISSOR: - this.renderer.scissor.push(maskData); - break; - case exports.MASK_TYPES.STENCIL: - this.renderer.stencil.push(maskData); - break; - case exports.MASK_TYPES.SPRITE: - maskData.copyCountersOrReset(null); - this.pushSpriteMask(maskData); - break; - case exports.MASK_TYPES.COLOR: - this.pushColorMask(maskData); - break; - } - } - if (maskData.type === exports.MASK_TYPES.SPRITE) { - this.maskStack.push(maskData); - } - }; - /** - * Removes the last mask from the mask stack and doesn't return it. - * - * NOTE: The batch renderer should be flushed beforehand to render the masked contents before the mask is removed. - * @param {PIXI.IMaskTarget} target - Display Object to pop the mask from - */ - MaskSystem.prototype.pop = function (target) { - var maskData = this.maskStack.pop(); - if (!maskData || maskData._target !== target) { - // TODO: add an assert when we have it - return; - } - if (maskData.enabled) { - switch (maskData.type) { - case exports.MASK_TYPES.SCISSOR: - this.renderer.scissor.pop(maskData); - break; - case exports.MASK_TYPES.STENCIL: - this.renderer.stencil.pop(maskData.maskObject); - break; - case exports.MASK_TYPES.SPRITE: - this.popSpriteMask(maskData); - break; - case exports.MASK_TYPES.COLOR: - this.popColorMask(maskData); - break; - } - } - maskData.reset(); - if (maskData.pooled) { - this.maskDataPool.push(maskData); - } - if (this.maskStack.length !== 0) { - var maskCurrent = this.maskStack[this.maskStack.length - 1]; - if (maskCurrent.type === exports.MASK_TYPES.SPRITE && maskCurrent._filters) { - maskCurrent._filters[0].maskSprite = maskCurrent.maskObject; - } - } - }; - /** - * Sets type of MaskData based on its maskObject. - * @param maskData - */ - MaskSystem.prototype.detect = function (maskData) { - var maskObject = maskData.maskObject; - if (!maskObject) { - maskData.type = exports.MASK_TYPES.COLOR; - } - else if (maskObject.isSprite) { - maskData.type = exports.MASK_TYPES.SPRITE; - } - else if (this.enableScissor && this.renderer.scissor.testScissor(maskData)) { - maskData.type = exports.MASK_TYPES.SCISSOR; - } - else { - maskData.type = exports.MASK_TYPES.STENCIL; - } - }; - /** - * Applies the Mask and adds it to the current filter stack. - * @param maskData - Sprite to be used as the mask. - */ - MaskSystem.prototype.pushSpriteMask = function (maskData) { - var _a, _b; - var maskObject = maskData.maskObject; - var target = maskData._target; - var alphaMaskFilter = maskData._filters; - if (!alphaMaskFilter) { - alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; - if (!alphaMaskFilter) { - alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new SpriteMaskFilter()]; - } - } - var renderer = this.renderer; - var renderTextureSystem = renderer.renderTexture; - var resolution; - var multisample; - if (renderTextureSystem.current) { - var renderTexture = renderTextureSystem.current; - resolution = maskData.resolution || renderTexture.resolution; - multisample = (_a = maskData.multisample) !== null && _a !== void 0 ? _a : renderTexture.multisample; - } - else { - resolution = maskData.resolution || renderer.resolution; - multisample = (_b = maskData.multisample) !== null && _b !== void 0 ? _b : renderer.multisample; - } - alphaMaskFilter[0].resolution = resolution; - alphaMaskFilter[0].multisample = multisample; - alphaMaskFilter[0].maskSprite = maskObject; - var stashFilterArea = target.filterArea; - target.filterArea = maskObject.getBounds(true); - renderer.filter.push(target, alphaMaskFilter); - target.filterArea = stashFilterArea; - if (!maskData._filters) { - this.alphaMaskIndex++; - } - }; - /** - * Removes the last filter from the filter stack and doesn't return it. - * @param maskData - Sprite to be used as the mask. - */ - MaskSystem.prototype.popSpriteMask = function (maskData) { - this.renderer.filter.pop(); - if (maskData._filters) { - maskData._filters[0].maskSprite = null; - } - else { - this.alphaMaskIndex--; - this.alphaMaskPool[this.alphaMaskIndex][0].maskSprite = null; - } - }; - /** - * Pushes the color mask. - * @param maskData - The mask data - */ - MaskSystem.prototype.pushColorMask = function (maskData) { - var currColorMask = maskData._colorMask; - var nextColorMask = maskData._colorMask = currColorMask & maskData.colorMask; - if (nextColorMask !== currColorMask) { - this.renderer.gl.colorMask((nextColorMask & 0x1) !== 0, (nextColorMask & 0x2) !== 0, (nextColorMask & 0x4) !== 0, (nextColorMask & 0x8) !== 0); - } - }; - /** - * Pops the color mask. - * @param maskData - The mask data - */ - MaskSystem.prototype.popColorMask = function (maskData) { - var currColorMask = maskData._colorMask; - var nextColorMask = this.maskStack.length > 0 - ? this.maskStack[this.maskStack.length - 1]._colorMask : 0xf; - if (nextColorMask !== currColorMask) { - this.renderer.gl.colorMask((nextColorMask & 0x1) !== 0, (nextColorMask & 0x2) !== 0, (nextColorMask & 0x4) !== 0, (nextColorMask & 0x8) !== 0); - } - }; - MaskSystem.prototype.destroy = function () { - this.renderer = null; - }; - return MaskSystem; - }()); - - /** - * System plugin to the renderer to manage specific types of masking operations. - * @memberof PIXI - */ - var AbstractMaskSystem = /** @class */ (function () { - /** - * @param renderer - The renderer this System works for. - */ - function AbstractMaskSystem(renderer) { - this.renderer = renderer; - this.maskStack = []; - this.glConst = 0; - } - /** Gets count of masks of certain type. */ - AbstractMaskSystem.prototype.getStackLength = function () { - return this.maskStack.length; - }; - /** - * Changes the mask stack that is used by this System. - * @param {PIXI.MaskData[]} maskStack - The mask stack - */ - AbstractMaskSystem.prototype.setMaskStack = function (maskStack) { - var gl = this.renderer.gl; - var curStackLen = this.getStackLength(); - this.maskStack = maskStack; - var newStackLen = this.getStackLength(); - if (newStackLen !== curStackLen) { - if (newStackLen === 0) { - gl.disable(this.glConst); - } - else { - gl.enable(this.glConst); - this._useCurrent(); - } - } - }; - /** - * Setup renderer to use the current mask data. - * @private - */ - AbstractMaskSystem.prototype._useCurrent = function () { - // OVERWRITE; - }; - /** Destroys the mask stack. */ - AbstractMaskSystem.prototype.destroy = function () { - this.renderer = null; - this.maskStack = null; - }; - return AbstractMaskSystem; - }()); - - var tempMatrix$1 = new Matrix(); - var rectPool = []; - /** - * System plugin to the renderer to manage scissor masking. - * - * Scissor masking discards pixels outside of a rectangle called the scissor box. The scissor box is in the framebuffer - * viewport's space; however, the mask's rectangle is projected from world-space to viewport space automatically - * by this system. - * @memberof PIXI - */ - var ScissorSystem = /** @class */ (function (_super) { - __extends$i(ScissorSystem, _super); - /** - * @param {PIXI.Renderer} renderer - The renderer this System works for. - */ - function ScissorSystem(renderer) { - var _this = _super.call(this, renderer) || this; - _this.glConst = settings.ADAPTER.getWebGLRenderingContext().SCISSOR_TEST; - return _this; - } - ScissorSystem.prototype.getStackLength = function () { - var maskData = this.maskStack[this.maskStack.length - 1]; - if (maskData) { - return maskData._scissorCounter; - } - return 0; - }; - /** - * evaluates _boundsTransformed, _scissorRect for MaskData - * @param maskData - */ - ScissorSystem.prototype.calcScissorRect = function (maskData) { - var _a; - if (maskData._scissorRectLocal) { - return; - } - var prevData = maskData._scissorRect; - var maskObject = maskData.maskObject; - var renderer = this.renderer; - var renderTextureSystem = renderer.renderTexture; - var rect = maskObject.getBounds(true, (_a = rectPool.pop()) !== null && _a !== void 0 ? _a : new Rectangle()); - this.roundFrameToPixels(rect, renderTextureSystem.current ? renderTextureSystem.current.resolution : renderer.resolution, renderTextureSystem.sourceFrame, renderTextureSystem.destinationFrame, renderer.projection.transform); - if (prevData) { - rect.fit(prevData); - } - maskData._scissorRectLocal = rect; - }; - ScissorSystem.isMatrixRotated = function (matrix) { - if (!matrix) { - return false; - } - var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d; - // Skip if skew/rotation present in matrix, except for multiple of 90° rotation. If rotation - // is a multiple of 90°, then either pair of (b,c) or (a,d) will be (0,0). - return ((Math.abs(b) > 1e-4 || Math.abs(c) > 1e-4) - && (Math.abs(a) > 1e-4 || Math.abs(d) > 1e-4)); - }; - /** - * Test, whether the object can be scissor mask with current renderer projection. - * Calls "calcScissorRect()" if its true. - * @param maskData - mask data - * @returns whether Whether the object can be scissor mask - */ - ScissorSystem.prototype.testScissor = function (maskData) { - var maskObject = maskData.maskObject; - if (!maskObject.isFastRect || !maskObject.isFastRect()) { - return false; - } - if (ScissorSystem.isMatrixRotated(maskObject.worldTransform)) { - return false; - } - if (ScissorSystem.isMatrixRotated(this.renderer.projection.transform)) { - return false; - } - this.calcScissorRect(maskData); - var rect = maskData._scissorRectLocal; - return rect.width > 0 && rect.height > 0; - }; - ScissorSystem.prototype.roundFrameToPixels = function (frame, resolution, bindingSourceFrame, bindingDestinationFrame, transform) { - if (ScissorSystem.isMatrixRotated(transform)) { - return; - } - transform = transform ? tempMatrix$1.copyFrom(transform) : tempMatrix$1.identity(); - // Get forward transform from world space to screen space - transform - .translate(-bindingSourceFrame.x, -bindingSourceFrame.y) - .scale(bindingDestinationFrame.width / bindingSourceFrame.width, bindingDestinationFrame.height / bindingSourceFrame.height) - .translate(bindingDestinationFrame.x, bindingDestinationFrame.y); - // Convert frame to screen space - this.renderer.filter.transformAABB(transform, frame); - frame.fit(bindingDestinationFrame); - frame.x = Math.round(frame.x * resolution); - frame.y = Math.round(frame.y * resolution); - frame.width = Math.round(frame.width * resolution); - frame.height = Math.round(frame.height * resolution); - }; - /** - * Applies the Mask and adds it to the current stencil stack. - * @author alvin - * @param maskData - The mask data. - */ - ScissorSystem.prototype.push = function (maskData) { - if (!maskData._scissorRectLocal) { - this.calcScissorRect(maskData); - } - var gl = this.renderer.gl; - if (!maskData._scissorRect) { - gl.enable(gl.SCISSOR_TEST); - } - maskData._scissorCounter++; - maskData._scissorRect = maskData._scissorRectLocal; - this._useCurrent(); - }; - /** - * This should be called after a mask is popped off the mask stack. It will rebind the scissor box to be latest with the - * last mask in the stack. - * - * This can also be called when you directly modify the scissor box and want to restore PixiJS state. - * @param maskData - The mask data. - */ - ScissorSystem.prototype.pop = function (maskData) { - var gl = this.renderer.gl; - if (maskData) { - rectPool.push(maskData._scissorRectLocal); - } - if (this.getStackLength() > 0) { - this._useCurrent(); - } - else { - gl.disable(gl.SCISSOR_TEST); - } - }; - /** - * Setup renderer to use the current scissor data. - * @private - */ - ScissorSystem.prototype._useCurrent = function () { - var rect = this.maskStack[this.maskStack.length - 1]._scissorRect; - var y; - if (this.renderer.renderTexture.current) { - y = rect.y; - } - else { - // flipY. In future we'll have it over renderTextures as an option - y = this.renderer.height - rect.height - rect.y; - } - this.renderer.gl.scissor(rect.x, y, rect.width, rect.height); - }; - return ScissorSystem; - }(AbstractMaskSystem)); - - /** - * System plugin to the renderer to manage stencils (used for masks). - * @memberof PIXI - */ - var StencilSystem = /** @class */ (function (_super) { - __extends$i(StencilSystem, _super); - /** - * @param renderer - The renderer this System works for. - */ - function StencilSystem(renderer) { - var _this = _super.call(this, renderer) || this; - _this.glConst = settings.ADAPTER.getWebGLRenderingContext().STENCIL_TEST; - return _this; - } - StencilSystem.prototype.getStackLength = function () { - var maskData = this.maskStack[this.maskStack.length - 1]; - if (maskData) { - return maskData._stencilCounter; - } - return 0; - }; - /** - * Applies the Mask and adds it to the current stencil stack. - * @param maskData - The mask data - */ - StencilSystem.prototype.push = function (maskData) { - var maskObject = maskData.maskObject; - var gl = this.renderer.gl; - var prevMaskCount = maskData._stencilCounter; - if (prevMaskCount === 0) { - // force use stencil texture in current framebuffer - this.renderer.framebuffer.forceStencil(); - gl.clearStencil(0); - gl.clear(gl.STENCIL_BUFFER_BIT); - gl.enable(gl.STENCIL_TEST); - } - maskData._stencilCounter++; - var colorMask = maskData._colorMask; - if (colorMask !== 0) { - maskData._colorMask = 0; - gl.colorMask(false, false, false, false); - } - // Increment the reference stencil value where the new mask overlaps with the old ones. - gl.stencilFunc(gl.EQUAL, prevMaskCount, 0xFFFFFFFF); - gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); - maskObject.renderable = true; - maskObject.render(this.renderer); - this.renderer.batch.flush(); - maskObject.renderable = false; - if (colorMask !== 0) { - maskData._colorMask = colorMask; - gl.colorMask((colorMask & 1) !== 0, (colorMask & 2) !== 0, (colorMask & 4) !== 0, (colorMask & 8) !== 0); - } - this._useCurrent(); - }; - /** - * Pops stencil mask. MaskData is already removed from stack - * @param {PIXI.DisplayObject} maskObject - object of popped mask data - */ - StencilSystem.prototype.pop = function (maskObject) { - var gl = this.renderer.gl; - if (this.getStackLength() === 0) { - // the stack is empty! - gl.disable(gl.STENCIL_TEST); - } - else { - var maskData = this.maskStack.length !== 0 ? this.maskStack[this.maskStack.length - 1] : null; - var colorMask = maskData ? maskData._colorMask : 0xf; - if (colorMask !== 0) { - maskData._colorMask = 0; - gl.colorMask(false, false, false, false); - } - // Decrement the reference stencil value where the popped mask overlaps with the other ones - gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); - maskObject.renderable = true; - maskObject.render(this.renderer); - this.renderer.batch.flush(); - maskObject.renderable = false; - if (colorMask !== 0) { - maskData._colorMask = colorMask; - gl.colorMask((colorMask & 0x1) !== 0, (colorMask & 0x2) !== 0, (colorMask & 0x4) !== 0, (colorMask & 0x8) !== 0); - } - this._useCurrent(); - } - }; - /** - * Setup renderer to use the current stencil data. - * @private - */ - StencilSystem.prototype._useCurrent = function () { - var gl = this.renderer.gl; - gl.stencilFunc(gl.EQUAL, this.getStackLength(), 0xFFFFFFFF); - gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); - }; - return StencilSystem; - }(AbstractMaskSystem)); - - /** - * System plugin to the renderer to manage the projection matrix. - * - * The `projectionMatrix` is a global uniform provided to all shaders. It is used to transform points in world space to - * normalized device coordinates. - * @memberof PIXI - */ - var ProjectionSystem = /** @class */ (function () { - /** @param renderer - The renderer this System works for. */ - function ProjectionSystem(renderer) { - this.renderer = renderer; - this.destinationFrame = null; - this.sourceFrame = null; - this.defaultFrame = null; - this.projectionMatrix = new Matrix(); - this.transform = null; - } - /** - * Updates the projection-matrix based on the sourceFrame → destinationFrame mapping provided. - * - * NOTE: It is expected you call `renderer.framebuffer.setViewport(destinationFrame)` after this. This is because - * the framebuffer viewport converts shader vertex output in normalized device coordinates to window coordinates. - * - * NOTE-2: {@link RenderTextureSystem#bind} updates the projection-matrix when you bind a render-texture. It is expected - * that you dirty the current bindings when calling this manually. - * @param destinationFrame - The rectangle in the render-target to render the contents into. If rendering to the canvas, - * the origin is on the top-left; if rendering to a render-texture, the origin is on the bottom-left. - * @param sourceFrame - The rectangle in world space that contains the contents being rendered. - * @param resolution - The resolution of the render-target, which is the ratio of - * world-space (or CSS) pixels to physical pixels. - * @param root - Whether the render-target is the screen. This is required because rendering to textures - * is y-flipped (i.e. upside down relative to the screen). - */ - ProjectionSystem.prototype.update = function (destinationFrame, sourceFrame, resolution, root) { - this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; - this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame; - // Calculate object-space to clip-space projection - this.calculateProjection(this.destinationFrame, this.sourceFrame, resolution, root); - if (this.transform) { - this.projectionMatrix.append(this.transform); - } - var renderer = this.renderer; - renderer.globalUniforms.uniforms.projectionMatrix = this.projectionMatrix; - renderer.globalUniforms.update(); - // this will work for now - // but would be sweet to stick and even on the global uniforms.. - if (renderer.shader.shader) { - renderer.shader.syncUniformGroup(renderer.shader.shader.uniforms.globals); - } - }; - /** - * Calculates the `projectionMatrix` to map points inside `sourceFrame` to inside `destinationFrame`. - * @param _destinationFrame - The destination frame in the render-target. - * @param sourceFrame - The source frame in world space. - * @param _resolution - The render-target's resolution, i.e. ratio of CSS to physical pixels. - * @param root - Whether rendering into the screen. Otherwise, if rendering to a framebuffer, the projection - * is y-flipped. - */ - ProjectionSystem.prototype.calculateProjection = function (_destinationFrame, sourceFrame, _resolution, root) { - var pm = this.projectionMatrix; - var sign = !root ? 1 : -1; - pm.identity(); - pm.a = (1 / sourceFrame.width * 2); - pm.d = sign * (1 / sourceFrame.height * 2); - pm.tx = -1 - (sourceFrame.x * pm.a); - pm.ty = -sign - (sourceFrame.y * pm.d); - }; - /** - * Sets the transform of the active render target to the given matrix. - * @param _matrix - The transformation matrix - */ - ProjectionSystem.prototype.setTransform = function (_matrix) { - // this._activeRenderTarget.transform = matrix; - }; - ProjectionSystem.prototype.destroy = function () { - this.renderer = null; - }; - return ProjectionSystem; - }()); - - // Temporary rectangle for assigned sourceFrame or destinationFrame - var tempRect = new Rectangle(); - // Temporary rectangle for renderTexture destinationFrame - var tempRect2 = new Rectangle(); - /* eslint-disable max-len */ - /** - * System plugin to the renderer to manage render textures. - * - * Should be added after FramebufferSystem - * - * ### Frames - * - * The `RenderTextureSystem` holds a sourceFrame → destinationFrame projection. The following table explains the different - * coordinate spaces used: - * - * | Frame | Description | Coordinate System | - * | ---------------------- | ---------------------------------------------------------------- | ------------------------------------------------------- | - * | sourceFrame | The rectangle inside of which display-objects are being rendered | **World Space**: The origin on the top-left | - * | destinationFrame | The rectangle in the render-target (canvas or texture) into which contents should be rendered | If rendering to the canvas, this is in screen space and the origin is on the top-left. If rendering to a render-texture, this is in its base-texture's space with the origin on the bottom-left. | - * | viewportFrame | The framebuffer viewport corresponding to the destination-frame | **Window Coordinates**: The origin is always on the bottom-left. | - * @memberof PIXI - */ - var RenderTextureSystem = /** @class */ (function () { - /** - * @param renderer - The renderer this System works for. - */ - function RenderTextureSystem(renderer) { - this.renderer = renderer; - this.clearColor = renderer._backgroundColorRgba; - this.defaultMaskStack = []; - this.current = null; - this.sourceFrame = new Rectangle(); - this.destinationFrame = new Rectangle(); - this.viewportFrame = new Rectangle(); - } - /** - * Bind the current render texture. - * @param renderTexture - RenderTexture to bind, by default its `null` - the screen. - * @param sourceFrame - Part of world that is mapped to the renderTexture. - * @param destinationFrame - Part of renderTexture, by default it has the same size as sourceFrame. - */ - RenderTextureSystem.prototype.bind = function (renderTexture, sourceFrame, destinationFrame) { - if (renderTexture === void 0) { renderTexture = null; } - var renderer = this.renderer; - this.current = renderTexture; - var baseTexture; - var framebuffer; - var resolution; - if (renderTexture) { - baseTexture = renderTexture.baseTexture; - resolution = baseTexture.resolution; - if (!sourceFrame) { - tempRect.width = renderTexture.frame.width; - tempRect.height = renderTexture.frame.height; - sourceFrame = tempRect; - } - if (!destinationFrame) { - tempRect2.x = renderTexture.frame.x; - tempRect2.y = renderTexture.frame.y; - tempRect2.width = sourceFrame.width; - tempRect2.height = sourceFrame.height; - destinationFrame = tempRect2; - } - framebuffer = baseTexture.framebuffer; - } - else { - resolution = renderer.resolution; - if (!sourceFrame) { - tempRect.width = renderer.screen.width; - tempRect.height = renderer.screen.height; - sourceFrame = tempRect; - } - if (!destinationFrame) { - destinationFrame = tempRect; - destinationFrame.width = sourceFrame.width; - destinationFrame.height = sourceFrame.height; - } - } - var viewportFrame = this.viewportFrame; - viewportFrame.x = destinationFrame.x * resolution; - viewportFrame.y = destinationFrame.y * resolution; - viewportFrame.width = destinationFrame.width * resolution; - viewportFrame.height = destinationFrame.height * resolution; - if (!renderTexture) { - viewportFrame.y = renderer.view.height - (viewportFrame.y + viewportFrame.height); - } - viewportFrame.ceil(); - this.renderer.framebuffer.bind(framebuffer, viewportFrame); - this.renderer.projection.update(destinationFrame, sourceFrame, resolution, !framebuffer); - if (renderTexture) { - this.renderer.mask.setMaskStack(baseTexture.maskStack); - } - else { - this.renderer.mask.setMaskStack(this.defaultMaskStack); - } - this.sourceFrame.copyFrom(sourceFrame); - this.destinationFrame.copyFrom(destinationFrame); - }; - /** - * Erases the render texture and fills the drawing area with a colour. - * @param clearColor - The color as rgba, default to use the renderer backgroundColor - * @param [mask=BUFFER_BITS.COLOR | BUFFER_BITS.DEPTH] - Bitwise OR of masks - * that indicate the buffers to be cleared, by default COLOR and DEPTH buffers. - */ - RenderTextureSystem.prototype.clear = function (clearColor, mask) { - if (this.current) { - clearColor = clearColor || this.current.baseTexture.clearColor; - } - else { - clearColor = clearColor || this.clearColor; - } - var destinationFrame = this.destinationFrame; - var baseFrame = this.current ? this.current.baseTexture : this.renderer.screen; - var clearMask = destinationFrame.width !== baseFrame.width || destinationFrame.height !== baseFrame.height; - if (clearMask) { - var _a = this.viewportFrame, x = _a.x, y = _a.y, width = _a.width, height = _a.height; - x = Math.round(x); - y = Math.round(y); - width = Math.round(width); - height = Math.round(height); - // TODO: ScissorSystem should cache whether the scissor test is enabled or not. - this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); - this.renderer.gl.scissor(x, y, width, height); - } - this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3], mask); - if (clearMask) { - // Restore the scissor box - this.renderer.scissor.pop(); - } - }; - RenderTextureSystem.prototype.resize = function () { - // resize the root only! - this.bind(null); - }; - /** Resets render-texture state. */ - RenderTextureSystem.prototype.reset = function () { - this.bind(null); - }; - RenderTextureSystem.prototype.destroy = function () { - this.renderer = null; - }; - return RenderTextureSystem; - }()); - - function uboUpdate(_ud, _uv, _renderer, _syncData, buffer) { - _renderer.buffer.update(buffer); - } - // cv = CachedValue - // v = value - // ud = uniformData - // uv = uniformValue - // l = location - var UBO_TO_SINGLE_SETTERS = { - float: "\n data[offset] = v;\n ", - vec2: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n ", - vec3: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n\n ", - vec4: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n data[offset+3] = v[3];\n ", - mat2: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n\n data[offset+4] = v[2];\n data[offset+5] = v[3];\n ", - mat3: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n\n data[offset + 4] = v[3];\n data[offset + 5] = v[4];\n data[offset + 6] = v[5];\n\n data[offset + 8] = v[6];\n data[offset + 9] = v[7];\n data[offset + 10] = v[8];\n ", - mat4: "\n for(var i = 0; i < 16; i++)\n {\n data[offset + i] = v[i];\n }\n " - }; - var GLSL_TO_STD40_SIZE = { - float: 4, - vec2: 8, - vec3: 12, - vec4: 16, - int: 4, - ivec2: 8, - ivec3: 12, - ivec4: 16, - uint: 4, - uvec2: 8, - uvec3: 12, - uvec4: 16, - bool: 4, - bvec2: 8, - bvec3: 12, - bvec4: 16, - mat2: 16 * 2, - mat3: 16 * 3, - mat4: 16 * 4, - }; - /** - * logic originally from here: https://github.com/sketchpunk/FunWithWebGL2/blob/master/lesson_022/Shaders.js - * rewrote it, but this was a great starting point to get a solid understanding of whats going on :) - * @ignore - * @param uniformData - */ - function createUBOElements(uniformData) { - var uboElements = uniformData.map(function (data) { - return ({ - data: data, - offset: 0, - dataLen: 0, - dirty: 0 - }); - }); - var size = 0; - var chunkSize = 0; - var offset = 0; - for (var i = 0; i < uboElements.length; i++) { - var uboElement = uboElements[i]; - size = GLSL_TO_STD40_SIZE[uboElement.data.type]; - if (uboElement.data.size > 1) { - size = Math.max(size, 16) * uboElement.data.size; - } - uboElement.dataLen = size; - // add some size offset.. - // must align to the nearest 16 bytes or internally nearest round size - if (chunkSize % size !== 0 && chunkSize < 16) { - // diff required to line up.. - var lineUpValue = (chunkSize % size) % 16; - chunkSize += lineUpValue; - offset += lineUpValue; - } - if ((chunkSize + size) > 16) { - offset = Math.ceil(offset / 16) * 16; - uboElement.offset = offset; - offset += size; - chunkSize = size; - } - else { - uboElement.offset = offset; - chunkSize += size; - offset += size; - } - } - offset = Math.ceil(offset / 16) * 16; - return { uboElements: uboElements, size: offset }; - } - function getUBOData(uniforms, uniformData) { - var usedUniformDatas = []; - // build.. - for (var i in uniforms) { - if (uniformData[i]) { - usedUniformDatas.push(uniformData[i]); - } - } - // sort them out by index! - usedUniformDatas.sort(function (a, b) { return a.index - b.index; }); - return usedUniformDatas; - } - function generateUniformBufferSync(group, uniformData) { - if (!group.autoManage) { - // if the group is nott automatically managed, we don't need to generate a special function for it... - return { size: 0, syncFunc: uboUpdate }; - } - var usedUniformDatas = getUBOData(group.uniforms, uniformData); - var _a = createUBOElements(usedUniformDatas), uboElements = _a.uboElements, size = _a.size; - var funcFragments = ["\n var v = null;\n var v2 = null;\n var cv = null;\n var t = 0;\n var gl = renderer.gl\n var index = 0;\n var data = buffer.data;\n "]; - for (var i = 0; i < uboElements.length; i++) { - var uboElement = uboElements[i]; - var uniform = group.uniforms[uboElement.data.name]; - var name = uboElement.data.name; - var parsed = false; - for (var j = 0; j < uniformParsers.length; j++) { - var uniformParser = uniformParsers[j]; - if (uniformParser.codeUbo && uniformParser.test(uboElement.data, uniform)) { - funcFragments.push("offset = " + uboElement.offset / 4 + ";", uniformParsers[j].codeUbo(uboElement.data.name, uniform)); - parsed = true; - break; - } - } - if (!parsed) { - if (uboElement.data.size > 1) { - var size_1 = mapSize(uboElement.data.type); - var rowSize = Math.max(GLSL_TO_STD40_SIZE[uboElement.data.type] / 16, 1); - var elementSize = size_1 / rowSize; - var remainder = (4 - (elementSize % 4)) % 4; - funcFragments.push("\n cv = ud." + name + ".value;\n v = uv." + name + ";\n offset = " + uboElement.offset / 4 + ";\n\n t = 0;\n\n for(var i=0; i < " + uboElement.data.size * rowSize + "; i++)\n {\n for(var j = 0; j < " + elementSize + "; j++)\n {\n data[offset++] = v[t++];\n }\n offset += " + remainder + ";\n }\n\n "); - } - else { - var template = UBO_TO_SINGLE_SETTERS[uboElement.data.type]; - funcFragments.push("\n cv = ud." + name + ".value;\n v = uv." + name + ";\n offset = " + uboElement.offset / 4 + ";\n " + template + ";\n "); - } - } - } - funcFragments.push("\n renderer.buffer.update(buffer);\n "); - return { - size: size, - // eslint-disable-next-line no-new-func - syncFunc: new Function('ud', 'uv', 'renderer', 'syncData', 'buffer', funcFragments.join('\n')) - }; - } - - /** - * @private - */ - var IGLUniformData = /** @class */ (function () { - function IGLUniformData() { - } - return IGLUniformData; - }()); - /** - * Helper class to create a WebGL Program - * @memberof PIXI - */ - var GLProgram = /** @class */ (function () { - /** - * Makes a new Pixi program. - * @param program - webgl program - * @param uniformData - uniforms - */ - function GLProgram(program, uniformData) { - this.program = program; - this.uniformData = uniformData; - this.uniformGroups = {}; - this.uniformDirtyGroups = {}; - this.uniformBufferBindings = {}; - } - /** Destroys this program. */ - GLProgram.prototype.destroy = function () { - this.uniformData = null; - this.uniformGroups = null; - this.uniformDirtyGroups = null; - this.uniformBufferBindings = null; - this.program = null; - }; - return GLProgram; - }()); - - /** - * returns the attribute data from the program - * @private - * @param {WebGLProgram} [program] - the WebGL program - * @param {WebGLRenderingContext} [gl] - the WebGL context - * @returns {object} the attribute data for this program - */ - function getAttributeData(program, gl) { - var attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - if (attribData.name.indexOf('gl_') === 0) { - continue; - } - var type = mapType(gl, attribData.type); - var data = { - type: type, - name: attribData.name, - size: mapSize(type), - location: gl.getAttribLocation(program, attribData.name), - }; - attributes[attribData.name] = data; - } - return attributes; - } - - /** - * returns the uniform data from the program - * @private - * @param program - the webgl program - * @param gl - the WebGL context - * @returns {object} the uniform data for this program - */ - function getUniformData(program, gl) { - var uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]$/, ''); - var isArray = !!(uniformData.name.match(/\[.*?\]$/)); - var type = mapType(gl, uniformData.type); - uniforms[name] = { - name: name, - index: i, - type: type, - size: uniformData.size, - isArray: isArray, - value: defaultValue(type, uniformData.size), - }; - } - return uniforms; - } - - /** - * generates a WebGL Program object from a high level Pixi Program. - * @param gl - a rendering context on which to generate the program - * @param program - the high level Pixi Program. - */ - function generateProgram(gl, program) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, program.vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, program.fragmentSrc); - var webGLProgram = gl.createProgram(); - gl.attachShader(webGLProgram, glVertShader); - gl.attachShader(webGLProgram, glFragShader); - gl.linkProgram(webGLProgram); - if (!gl.getProgramParameter(webGLProgram, gl.LINK_STATUS)) { - logProgramError(gl, webGLProgram, glVertShader, glFragShader); - } - program.attributeData = getAttributeData(webGLProgram, gl); - program.uniformData = getUniformData(webGLProgram, gl); - // GLSL 1.00: bind attributes sorted by name in ascending order - // GLSL 3.00: don't change the attribute locations that where chosen by the compiler - // or assigned by the layout specifier in the shader source code - if (!(/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m).test(program.vertexSrc)) { - var keys = Object.keys(program.attributeData); - keys.sort(function (a, b) { return (a > b) ? 1 : -1; }); // eslint-disable-line no-confusing-arrow - for (var i = 0; i < keys.length; i++) { - program.attributeData[keys[i]].location = i; - gl.bindAttribLocation(webGLProgram, i, keys[i]); - } - gl.linkProgram(webGLProgram); - } - gl.deleteShader(glVertShader); - gl.deleteShader(glFragShader); - var uniformData = {}; - for (var i in program.uniformData) { - var data = program.uniformData[i]; - uniformData[i] = { - location: gl.getUniformLocation(webGLProgram, i), - value: defaultValue(data.type, data.size), - }; - } - var glProgram = new GLProgram(webGLProgram, uniformData); - return glProgram; - } - - var UID = 0; - // default sync data so we don't create a new one each time! - var defaultSyncData = { textureCount: 0, uboCount: 0 }; - /** - * System plugin to the renderer to manage shaders. - * @memberof PIXI - */ - var ShaderSystem = /** @class */ (function () { - /** @param renderer - The renderer this System works for. */ - function ShaderSystem(renderer) { - this.destroyed = false; - this.renderer = renderer; - // Validation check that this environment support `new Function` - this.systemCheck(); - this.gl = null; - this.shader = null; - this.program = null; - this.cache = {}; - this._uboCache = {}; - this.id = UID++; - } - /** - * Overrideable function by `@pixi/unsafe-eval` to silence - * throwing an error if platform doesn't support unsafe-evals. - * @private - */ - ShaderSystem.prototype.systemCheck = function () { - if (!unsafeEvalSupported()) { - throw new Error('Current environment does not allow unsafe-eval, ' - + 'please use @pixi/unsafe-eval module to enable support.'); - } - }; - ShaderSystem.prototype.contextChange = function (gl) { - this.gl = gl; - this.reset(); - }; - /** - * Changes the current shader to the one given in parameter. - * @param shader - the new shader - * @param dontSync - false if the shader should automatically sync its uniforms. - * @returns the glProgram that belongs to the shader. - */ - ShaderSystem.prototype.bind = function (shader, dontSync) { - shader.disposeRunner.add(this); - shader.uniforms.globals = this.renderer.globalUniforms; - var program = shader.program; - var glProgram = program.glPrograms[this.renderer.CONTEXT_UID] || this.generateProgram(shader); - this.shader = shader; - // TODO - some current Pixi plugins bypass this.. so it not safe to use yet.. - if (this.program !== program) { - this.program = program; - this.gl.useProgram(glProgram.program); - } - if (!dontSync) { - defaultSyncData.textureCount = 0; - defaultSyncData.uboCount = 0; - this.syncUniformGroup(shader.uniformGroup, defaultSyncData); - } - return glProgram; - }; - /** - * Uploads the uniforms values to the currently bound shader. - * @param uniforms - the uniforms values that be applied to the current shader - */ - ShaderSystem.prototype.setUniforms = function (uniforms) { - var shader = this.shader.program; - var glProgram = shader.glPrograms[this.renderer.CONTEXT_UID]; - shader.syncUniforms(glProgram.uniformData, uniforms, this.renderer); - }; - /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ - /** - * Syncs uniforms on the group - * @param group - the uniform group to sync - * @param syncData - this is data that is passed to the sync function and any nested sync functions - */ - ShaderSystem.prototype.syncUniformGroup = function (group, syncData) { - var glProgram = this.getGlProgram(); - if (!group.static || group.dirtyId !== glProgram.uniformDirtyGroups[group.id]) { - glProgram.uniformDirtyGroups[group.id] = group.dirtyId; - this.syncUniforms(group, glProgram, syncData); - } - }; - /** - * Overrideable by the @pixi/unsafe-eval package to use static syncUniforms instead. - * @param group - * @param glProgram - * @param syncData - */ - ShaderSystem.prototype.syncUniforms = function (group, glProgram, syncData) { - var syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); - syncFunc(glProgram.uniformData, group.uniforms, this.renderer, syncData); - }; - ShaderSystem.prototype.createSyncGroups = function (group) { - var id = this.getSignature(group, this.shader.program.uniformData, 'u'); - if (!this.cache[id]) { - this.cache[id] = generateUniformsSync(group, this.shader.program.uniformData); - } - group.syncUniforms[this.shader.program.id] = this.cache[id]; - return group.syncUniforms[this.shader.program.id]; - }; - /** - * Syncs uniform buffers - * @param group - the uniform buffer group to sync - * @param name - the name of the uniform buffer - */ - ShaderSystem.prototype.syncUniformBufferGroup = function (group, name) { - var glProgram = this.getGlProgram(); - if (!group.static || group.dirtyId !== 0 || !glProgram.uniformGroups[group.id]) { - group.dirtyId = 0; - var syncFunc = glProgram.uniformGroups[group.id] - || this.createSyncBufferGroup(group, glProgram, name); - // TODO wrap update in a cache?? - group.buffer.update(); - syncFunc(glProgram.uniformData, group.uniforms, this.renderer, defaultSyncData, group.buffer); - } - this.renderer.buffer.bindBufferBase(group.buffer, glProgram.uniformBufferBindings[name]); - }; - /** - * Will create a function that uploads a uniform buffer using the STD140 standard. - * The upload function will then be cached for future calls - * If a group is manually managed, then a simple upload function is generated - * @param group - the uniform buffer group to sync - * @param glProgram - the gl program to attach the uniform bindings to - * @param name - the name of the uniform buffer (must exist on the shader) - */ - ShaderSystem.prototype.createSyncBufferGroup = function (group, glProgram, name) { - var gl = this.renderer.gl; - this.renderer.buffer.bind(group.buffer); - // bind them... - var uniformBlockIndex = this.gl.getUniformBlockIndex(glProgram.program, name); - glProgram.uniformBufferBindings[name] = this.shader.uniformBindCount; - gl.uniformBlockBinding(glProgram.program, uniformBlockIndex, this.shader.uniformBindCount); - this.shader.uniformBindCount++; - var id = this.getSignature(group, this.shader.program.uniformData, 'ubo'); - var uboData = this._uboCache[id]; - if (!uboData) { - uboData = this._uboCache[id] = generateUniformBufferSync(group, this.shader.program.uniformData); - } - if (group.autoManage) { - var data = new Float32Array(uboData.size / 4); - group.buffer.update(data); - } - glProgram.uniformGroups[group.id] = uboData.syncFunc; - return glProgram.uniformGroups[group.id]; - }; - /** - * Takes a uniform group and data and generates a unique signature for them. - * @param group - The uniform group to get signature of - * @param group.uniforms - * @param uniformData - Uniform information generated by the shader - * @param preFix - * @returns Unique signature of the uniform group - */ - ShaderSystem.prototype.getSignature = function (group, uniformData, preFix) { - var uniforms = group.uniforms; - var strings = [preFix + "-"]; - for (var i in uniforms) { - strings.push(i); - if (uniformData[i]) { - strings.push(uniformData[i].type); - } - } - return strings.join('-'); - }; - /** - * Returns the underlying GLShade rof the currently bound shader. - * - * This can be handy for when you to have a little more control over the setting of your uniforms. - * @returns The glProgram for the currently bound Shader for this context - */ - ShaderSystem.prototype.getGlProgram = function () { - if (this.shader) { - return this.shader.program.glPrograms[this.renderer.CONTEXT_UID]; - } - return null; - }; - /** - * Generates a glProgram version of the Shader provided. - * @param shader - The shader that the glProgram will be based on. - * @returns A shiny new glProgram! - */ - ShaderSystem.prototype.generateProgram = function (shader) { - var gl = this.gl; - var program = shader.program; - var glProgram = generateProgram(gl, program); - program.glPrograms[this.renderer.CONTEXT_UID] = glProgram; - return glProgram; - }; - /** Resets ShaderSystem state, does not affect WebGL state. */ - ShaderSystem.prototype.reset = function () { - this.program = null; - this.shader = null; - }; - /** - * Disposes shader. - * If disposing one equals with current shader, set current as null. - * @param shader - Shader object - */ - ShaderSystem.prototype.disposeShader = function (shader) { - if (this.shader === shader) { - this.shader = null; - } - }; - /** Destroys this System and removes all its textures. */ - ShaderSystem.prototype.destroy = function () { - this.renderer = null; - // TODO implement destroy method for ShaderSystem - this.destroyed = true; - }; - return ShaderSystem; - }()); - - /** - * Maps gl blend combinations to WebGL. - * @memberof PIXI - * @function mapWebGLBlendModesToPixi - * @private - * @param {WebGLRenderingContext} gl - The rendering context. - * @param {number[][]} [array=[]] - The array to output into. - * @returns {number[][]} Mapped modes. - */ - function mapWebGLBlendModesToPixi(gl, array) { - if (array === void 0) { array = []; } - // TODO - premultiply alpha would be different. - // add a boolean for that! - array[exports.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.ADD] = [gl.ONE, gl.ONE]; - array[exports.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.NONE] = [0, 0]; - // not-premultiplied blend modes - array[exports.BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE]; - array[exports.BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - // composite operations - array[exports.BLEND_MODES.SRC_IN] = [gl.DST_ALPHA, gl.ZERO]; - array[exports.BLEND_MODES.SRC_OUT] = [gl.ONE_MINUS_DST_ALPHA, gl.ZERO]; - array[exports.BLEND_MODES.SRC_ATOP] = [gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.DST_OVER] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE]; - array[exports.BLEND_MODES.DST_IN] = [gl.ZERO, gl.SRC_ALPHA]; - array[exports.BLEND_MODES.DST_OUT] = [gl.ZERO, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.DST_ATOP] = [gl.ONE_MINUS_DST_ALPHA, gl.SRC_ALPHA]; - array[exports.BLEND_MODES.XOR] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA]; - // SUBTRACT from flash - array[exports.BLEND_MODES.SUBTRACT] = [gl.ONE, gl.ONE, gl.ONE, gl.ONE, gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD]; - return array; - } - - var BLEND = 0; - var OFFSET = 1; - var CULLING = 2; - var DEPTH_TEST = 3; - var WINDING = 4; - var DEPTH_MASK = 5; - /** - * System plugin to the renderer to manage WebGL state machines. - * @memberof PIXI - */ - var StateSystem = /** @class */ (function () { - function StateSystem() { - this.gl = null; - this.stateId = 0; - this.polygonOffset = 0; - this.blendMode = exports.BLEND_MODES.NONE; - this._blendEq = false; - // map functions for when we set state.. - this.map = []; - this.map[BLEND] = this.setBlend; - this.map[OFFSET] = this.setOffset; - this.map[CULLING] = this.setCullFace; - this.map[DEPTH_TEST] = this.setDepthTest; - this.map[WINDING] = this.setFrontFace; - this.map[DEPTH_MASK] = this.setDepthMask; - this.checks = []; - this.defaultState = new State(); - this.defaultState.blend = true; - } - StateSystem.prototype.contextChange = function (gl) { - this.gl = gl; - this.blendModes = mapWebGLBlendModesToPixi(gl); - this.set(this.defaultState); - this.reset(); - }; - /** - * Sets the current state - * @param {*} state - The state to set. - */ - StateSystem.prototype.set = function (state) { - state = state || this.defaultState; - // TODO maybe to an object check? ( this.state === state )? - if (this.stateId !== state.data) { - var diff = this.stateId ^ state.data; - var i = 0; - // order from least to most common - while (diff) { - if (diff & 1) { - // state change! - this.map[i].call(this, !!(state.data & (1 << i))); - } - diff = diff >> 1; - i++; - } - this.stateId = state.data; - } - // based on the above settings we check for specific modes.. - // for example if blend is active we check and set the blend modes - // or of polygon offset is active we check the poly depth. - for (var i = 0; i < this.checks.length; i++) { - this.checks[i](this, state); - } - }; - /** - * Sets the state, when previous state is unknown. - * @param {*} state - The state to set - */ - StateSystem.prototype.forceState = function (state) { - state = state || this.defaultState; - for (var i = 0; i < this.map.length; i++) { - this.map[i].call(this, !!(state.data & (1 << i))); - } - for (var i = 0; i < this.checks.length; i++) { - this.checks[i](this, state); - } - this.stateId = state.data; - }; - /** - * Sets whether to enable or disable blending. - * @param value - Turn on or off WebGl blending. - */ - StateSystem.prototype.setBlend = function (value) { - this.updateCheck(StateSystem.checkBlendMode, value); - this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); - }; - /** - * Sets whether to enable or disable polygon offset fill. - * @param value - Turn on or off webgl polygon offset testing. - */ - StateSystem.prototype.setOffset = function (value) { - this.updateCheck(StateSystem.checkPolygonOffset, value); - this.gl[value ? 'enable' : 'disable'](this.gl.POLYGON_OFFSET_FILL); - }; - /** - * Sets whether to enable or disable depth test. - * @param value - Turn on or off webgl depth testing. - */ - StateSystem.prototype.setDepthTest = function (value) { - this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); - }; - /** - * Sets whether to enable or disable depth mask. - * @param value - Turn on or off webgl depth mask. - */ - StateSystem.prototype.setDepthMask = function (value) { - this.gl.depthMask(value); - }; - /** - * Sets whether to enable or disable cull face. - * @param {boolean} value - Turn on or off webgl cull face. - */ - StateSystem.prototype.setCullFace = function (value) { - this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); - }; - /** - * Sets the gl front face. - * @param {boolean} value - true is clockwise and false is counter-clockwise - */ - StateSystem.prototype.setFrontFace = function (value) { - this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); - }; - /** - * Sets the blend mode. - * @param {number} value - The blend mode to set to. - */ - StateSystem.prototype.setBlendMode = function (value) { - if (value === this.blendMode) { - return; - } - this.blendMode = value; - var mode = this.blendModes[value]; - var gl = this.gl; - if (mode.length === 2) { - gl.blendFunc(mode[0], mode[1]); - } - else { - gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]); - } - if (mode.length === 6) { - this._blendEq = true; - gl.blendEquationSeparate(mode[4], mode[5]); - } - else if (this._blendEq) { - this._blendEq = false; - gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); - } - }; - /** - * Sets the polygon offset. - * @param {number} value - the polygon offset - * @param {number} scale - the polygon offset scale - */ - StateSystem.prototype.setPolygonOffset = function (value, scale) { - this.gl.polygonOffset(value, scale); - }; - // used - /** Resets all the logic and disables the VAOs. */ - StateSystem.prototype.reset = function () { - this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); - this.forceState(this.defaultState); - this._blendEq = true; - this.blendMode = -1; - this.setBlendMode(0); - }; - /** - * Checks to see which updates should be checked based on which settings have been activated. - * - * For example, if blend is enabled then we should check the blend modes each time the state is changed - * or if polygon fill is activated then we need to check if the polygon offset changes. - * The idea is that we only check what we have too. - * @param func - the checking function to add or remove - * @param value - should the check function be added or removed. - */ - StateSystem.prototype.updateCheck = function (func, value) { - var index = this.checks.indexOf(func); - if (value && index === -1) { - this.checks.push(func); - } - else if (!value && index !== -1) { - this.checks.splice(index, 1); - } - }; - /** - * A private little wrapper function that we call to check the blend mode. - * @param system - the System to perform the state check on - * @param state - the state that the blendMode will pulled from - */ - StateSystem.checkBlendMode = function (system, state) { - system.setBlendMode(state.blendMode); - }; - /** - * A private little wrapper function that we call to check the polygon offset. - * @param system - the System to perform the state check on - * @param state - the state that the blendMode will pulled from - */ - StateSystem.checkPolygonOffset = function (system, state) { - system.setPolygonOffset(1, state.polygonOffset); - }; - /** - * @ignore - */ - StateSystem.prototype.destroy = function () { - this.gl = null; - }; - return StateSystem; - }()); - - /** - * System plugin to the renderer to manage texture garbage collection on the GPU, - * ensuring that it does not get clogged up with textures that are no longer being used. - * @memberof PIXI - */ - var TextureGCSystem = /** @class */ (function () { - /** @param renderer - The renderer this System works for. */ - function TextureGCSystem(renderer) { - this.renderer = renderer; - this.count = 0; - this.checkCount = 0; - this.maxIdle = settings.GC_MAX_IDLE; - this.checkCountMax = settings.GC_MAX_CHECK_COUNT; - this.mode = settings.GC_MODE; - } - /** - * Checks to see when the last time a texture was used - * if the texture has not been used for a specified amount of time it will be removed from the GPU - */ - TextureGCSystem.prototype.postrender = function () { - if (!this.renderer.renderingToScreen) { - return; - } - this.count++; - if (this.mode === exports.GC_MODES.MANUAL) { - return; - } - this.checkCount++; - if (this.checkCount > this.checkCountMax) { - this.checkCount = 0; - this.run(); - } - }; - /** - * Checks to see when the last time a texture was used - * if the texture has not been used for a specified amount of time it will be removed from the GPU - */ - TextureGCSystem.prototype.run = function () { - var tm = this.renderer.texture; - var managedTextures = tm.managedTextures; - var wasRemoved = false; - for (var i = 0; i < managedTextures.length; i++) { - var texture = managedTextures[i]; - // only supports non generated textures at the moment! - if (!texture.framebuffer && this.count - texture.touched > this.maxIdle) { - tm.destroyTexture(texture, true); - managedTextures[i] = null; - wasRemoved = true; - } - } - if (wasRemoved) { - var j = 0; - for (var i = 0; i < managedTextures.length; i++) { - if (managedTextures[i] !== null) { - managedTextures[j++] = managedTextures[i]; - } - } - managedTextures.length = j; - } - }; - /** - * Removes all the textures within the specified displayObject and its children from the GPU - * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. - */ - TextureGCSystem.prototype.unload = function (displayObject) { - var tm = this.renderer.texture; - var texture = displayObject._texture; - // only destroy non generated textures - if (texture && !texture.framebuffer) { - tm.destroyTexture(texture); - } - for (var i = displayObject.children.length - 1; i >= 0; i--) { - this.unload(displayObject.children[i]); - } - }; - TextureGCSystem.prototype.destroy = function () { - this.renderer = null; - }; - return TextureGCSystem; - }()); - - /** - * Returns a lookup table that maps each type-format pair to a compatible internal format. - * @memberof PIXI - * @function mapTypeAndFormatToInternalFormat - * @private - * @param {WebGLRenderingContext} gl - The rendering context. - * @returns Lookup table. - */ - function mapTypeAndFormatToInternalFormat(gl) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x; - var table; - if ('WebGL2RenderingContext' in globalThis && gl instanceof globalThis.WebGL2RenderingContext) { - table = (_a = {}, - _a[exports.TYPES.UNSIGNED_BYTE] = (_b = {}, - _b[exports.FORMATS.RGBA] = gl.RGBA8, - _b[exports.FORMATS.RGB] = gl.RGB8, - _b[exports.FORMATS.RG] = gl.RG8, - _b[exports.FORMATS.RED] = gl.R8, - _b[exports.FORMATS.RGBA_INTEGER] = gl.RGBA8UI, - _b[exports.FORMATS.RGB_INTEGER] = gl.RGB8UI, - _b[exports.FORMATS.RG_INTEGER] = gl.RG8UI, - _b[exports.FORMATS.RED_INTEGER] = gl.R8UI, - _b[exports.FORMATS.ALPHA] = gl.ALPHA, - _b[exports.FORMATS.LUMINANCE] = gl.LUMINANCE, - _b[exports.FORMATS.LUMINANCE_ALPHA] = gl.LUMINANCE_ALPHA, - _b), - _a[exports.TYPES.BYTE] = (_c = {}, - _c[exports.FORMATS.RGBA] = gl.RGBA8_SNORM, - _c[exports.FORMATS.RGB] = gl.RGB8_SNORM, - _c[exports.FORMATS.RG] = gl.RG8_SNORM, - _c[exports.FORMATS.RED] = gl.R8_SNORM, - _c[exports.FORMATS.RGBA_INTEGER] = gl.RGBA8I, - _c[exports.FORMATS.RGB_INTEGER] = gl.RGB8I, - _c[exports.FORMATS.RG_INTEGER] = gl.RG8I, - _c[exports.FORMATS.RED_INTEGER] = gl.R8I, - _c), - _a[exports.TYPES.UNSIGNED_SHORT] = (_d = {}, - _d[exports.FORMATS.RGBA_INTEGER] = gl.RGBA16UI, - _d[exports.FORMATS.RGB_INTEGER] = gl.RGB16UI, - _d[exports.FORMATS.RG_INTEGER] = gl.RG16UI, - _d[exports.FORMATS.RED_INTEGER] = gl.R16UI, - _d[exports.FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT16, - _d), - _a[exports.TYPES.SHORT] = (_e = {}, - _e[exports.FORMATS.RGBA_INTEGER] = gl.RGBA16I, - _e[exports.FORMATS.RGB_INTEGER] = gl.RGB16I, - _e[exports.FORMATS.RG_INTEGER] = gl.RG16I, - _e[exports.FORMATS.RED_INTEGER] = gl.R16I, - _e), - _a[exports.TYPES.UNSIGNED_INT] = (_f = {}, - _f[exports.FORMATS.RGBA_INTEGER] = gl.RGBA32UI, - _f[exports.FORMATS.RGB_INTEGER] = gl.RGB32UI, - _f[exports.FORMATS.RG_INTEGER] = gl.RG32UI, - _f[exports.FORMATS.RED_INTEGER] = gl.R32UI, - _f[exports.FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT24, - _f), - _a[exports.TYPES.INT] = (_g = {}, - _g[exports.FORMATS.RGBA_INTEGER] = gl.RGBA32I, - _g[exports.FORMATS.RGB_INTEGER] = gl.RGB32I, - _g[exports.FORMATS.RG_INTEGER] = gl.RG32I, - _g[exports.FORMATS.RED_INTEGER] = gl.R32I, - _g), - _a[exports.TYPES.FLOAT] = (_h = {}, - _h[exports.FORMATS.RGBA] = gl.RGBA32F, - _h[exports.FORMATS.RGB] = gl.RGB32F, - _h[exports.FORMATS.RG] = gl.RG32F, - _h[exports.FORMATS.RED] = gl.R32F, - _h[exports.FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT32F, - _h), - _a[exports.TYPES.HALF_FLOAT] = (_j = {}, - _j[exports.FORMATS.RGBA] = gl.RGBA16F, - _j[exports.FORMATS.RGB] = gl.RGB16F, - _j[exports.FORMATS.RG] = gl.RG16F, - _j[exports.FORMATS.RED] = gl.R16F, - _j), - _a[exports.TYPES.UNSIGNED_SHORT_5_6_5] = (_k = {}, - _k[exports.FORMATS.RGB] = gl.RGB565, - _k), - _a[exports.TYPES.UNSIGNED_SHORT_4_4_4_4] = (_l = {}, - _l[exports.FORMATS.RGBA] = gl.RGBA4, - _l), - _a[exports.TYPES.UNSIGNED_SHORT_5_5_5_1] = (_m = {}, - _m[exports.FORMATS.RGBA] = gl.RGB5_A1, - _m), - _a[exports.TYPES.UNSIGNED_INT_2_10_10_10_REV] = (_o = {}, - _o[exports.FORMATS.RGBA] = gl.RGB10_A2, - _o[exports.FORMATS.RGBA_INTEGER] = gl.RGB10_A2UI, - _o), - _a[exports.TYPES.UNSIGNED_INT_10F_11F_11F_REV] = (_p = {}, - _p[exports.FORMATS.RGB] = gl.R11F_G11F_B10F, - _p), - _a[exports.TYPES.UNSIGNED_INT_5_9_9_9_REV] = (_q = {}, - _q[exports.FORMATS.RGB] = gl.RGB9_E5, - _q), - _a[exports.TYPES.UNSIGNED_INT_24_8] = (_r = {}, - _r[exports.FORMATS.DEPTH_STENCIL] = gl.DEPTH24_STENCIL8, - _r), - _a[exports.TYPES.FLOAT_32_UNSIGNED_INT_24_8_REV] = (_s = {}, - _s[exports.FORMATS.DEPTH_STENCIL] = gl.DEPTH32F_STENCIL8, - _s), - _a); - } - else { - table = (_t = {}, - _t[exports.TYPES.UNSIGNED_BYTE] = (_u = {}, - _u[exports.FORMATS.RGBA] = gl.RGBA, - _u[exports.FORMATS.RGB] = gl.RGB, - _u[exports.FORMATS.ALPHA] = gl.ALPHA, - _u[exports.FORMATS.LUMINANCE] = gl.LUMINANCE, - _u[exports.FORMATS.LUMINANCE_ALPHA] = gl.LUMINANCE_ALPHA, - _u), - _t[exports.TYPES.UNSIGNED_SHORT_5_6_5] = (_v = {}, - _v[exports.FORMATS.RGB] = gl.RGB, - _v), - _t[exports.TYPES.UNSIGNED_SHORT_4_4_4_4] = (_w = {}, - _w[exports.FORMATS.RGBA] = gl.RGBA, - _w), - _t[exports.TYPES.UNSIGNED_SHORT_5_5_5_1] = (_x = {}, - _x[exports.FORMATS.RGBA] = gl.RGBA, - _x), - _t); - } - return table; - } - - /** - * Internal texture for WebGL context. - * @memberof PIXI - */ - var GLTexture = /** @class */ (function () { - function GLTexture(texture) { - this.texture = texture; - this.width = -1; - this.height = -1; - this.dirtyId = -1; - this.dirtyStyleId = -1; - this.mipmap = false; - this.wrapMode = 33071; - this.type = exports.TYPES.UNSIGNED_BYTE; - this.internalFormat = exports.FORMATS.RGBA; - this.samplerType = 0; - } - return GLTexture; - }()); - - /** - * System plugin to the renderer to manage textures. - * @memberof PIXI - */ - var TextureSystem = /** @class */ (function () { - /** - * @param renderer - The renderer this system works for. - */ - function TextureSystem(renderer) { - this.renderer = renderer; - // TODO set to max textures... - this.boundTextures = []; - this.currentLocation = -1; - this.managedTextures = []; - this._unknownBoundTextures = false; - this.unknownTexture = new BaseTexture(); - this.hasIntegerTextures = false; - } - /** Sets up the renderer context and necessary buffers. */ - TextureSystem.prototype.contextChange = function () { - var gl = this.gl = this.renderer.gl; - this.CONTEXT_UID = this.renderer.CONTEXT_UID; - this.webGLVersion = this.renderer.context.webGLVersion; - this.internalFormats = mapTypeAndFormatToInternalFormat(gl); - var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); - this.boundTextures.length = maxTextures; - for (var i = 0; i < maxTextures; i++) { - this.boundTextures[i] = null; - } - // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {}; - var emptyTexture2D = new GLTexture(gl.createTexture()); - gl.bindTexture(gl.TEXTURE_2D, emptyTexture2D.texture); - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4)); - this.emptyTextures[gl.TEXTURE_2D] = emptyTexture2D; - this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(gl.createTexture()); - gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); - } - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { - this.bind(null, i); - } - }; - /** - * Bind a texture to a specific location - * - * If you want to unbind something, please use `unbind(texture)` instead of `bind(null, textureLocation)` - * @param texture - Texture to bind - * @param [location=0] - Location to bind at - */ - TextureSystem.prototype.bind = function (texture, location) { - if (location === void 0) { location = 0; } - var gl = this.gl; - texture = texture === null || texture === void 0 ? void 0 : texture.castToBaseTexture(); - // cannot bind partial texture - // TODO: report a warning - if (texture && texture.valid && !texture.parentTextureArray) { - texture.touched = this.renderer.textureGC.count; - var glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); - if (this.boundTextures[location] !== texture) { - if (this.currentLocation !== location) { - this.currentLocation = location; - gl.activeTexture(gl.TEXTURE0 + location); - } - gl.bindTexture(texture.target, glTexture.texture); - } - if (glTexture.dirtyId !== texture.dirtyId) { - if (this.currentLocation !== location) { - this.currentLocation = location; - gl.activeTexture(gl.TEXTURE0 + location); - } - this.updateTexture(texture); - } - else if (glTexture.dirtyStyleId !== texture.dirtyStyleId) { - this.updateTextureStyle(texture); - } - this.boundTextures[location] = texture; - } - else { - if (this.currentLocation !== location) { - this.currentLocation = location; - gl.activeTexture(gl.TEXTURE0 + location); - } - gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[gl.TEXTURE_2D].texture); - this.boundTextures[location] = null; - } - }; - /** Resets texture location and bound textures Actual `bind(null, i)` calls will be performed at next `unbind()` call */ - TextureSystem.prototype.reset = function () { - this._unknownBoundTextures = true; - this.hasIntegerTextures = false; - this.currentLocation = -1; - for (var i = 0; i < this.boundTextures.length; i++) { - this.boundTextures[i] = this.unknownTexture; - } - }; - /** - * Unbind a texture. - * @param texture - Texture to bind - */ - TextureSystem.prototype.unbind = function (texture) { - var _a = this, gl = _a.gl, boundTextures = _a.boundTextures; - if (this._unknownBoundTextures) { - this._unknownBoundTextures = false; - // someone changed webGL state, - // we have to be sure that our texture does not appear in multi-texture renderer samplers - for (var i = 0; i < boundTextures.length; i++) { - if (boundTextures[i] === this.unknownTexture) { - this.bind(null, i); - } - } - } - for (var i = 0; i < boundTextures.length; i++) { - if (boundTextures[i] === texture) { - if (this.currentLocation !== i) { - gl.activeTexture(gl.TEXTURE0 + i); - this.currentLocation = i; - } - gl.bindTexture(texture.target, this.emptyTextures[texture.target].texture); - boundTextures[i] = null; - } - } - }; - /** - * Ensures that current boundTextures all have FLOAT sampler type, - * see {@link PIXI.SAMPLER_TYPES} for explanation. - * @param maxTextures - number of locations to check - */ - TextureSystem.prototype.ensureSamplerType = function (maxTextures) { - var _a = this, boundTextures = _a.boundTextures, hasIntegerTextures = _a.hasIntegerTextures, CONTEXT_UID = _a.CONTEXT_UID; - if (!hasIntegerTextures) { - return; - } - for (var i = maxTextures - 1; i >= 0; --i) { - var tex = boundTextures[i]; - if (tex) { - var glTexture = tex._glTextures[CONTEXT_UID]; - if (glTexture.samplerType !== exports.SAMPLER_TYPES.FLOAT) { - this.renderer.texture.unbind(tex); - } - } - } - }; - /** - * Initialize a texture - * @private - * @param texture - Texture to initialize - */ - TextureSystem.prototype.initTexture = function (texture) { - var glTexture = new GLTexture(this.gl.createTexture()); - // guarantee an update.. - glTexture.dirtyId = -1; - texture._glTextures[this.CONTEXT_UID] = glTexture; - this.managedTextures.push(texture); - texture.on('dispose', this.destroyTexture, this); - return glTexture; - }; - TextureSystem.prototype.initTextureType = function (texture, glTexture) { - var _a, _b; - glTexture.internalFormat = (_b = (_a = this.internalFormats[texture.type]) === null || _a === void 0 ? void 0 : _a[texture.format]) !== null && _b !== void 0 ? _b : texture.format; - if (this.webGLVersion === 2 && texture.type === exports.TYPES.HALF_FLOAT) { - // TYPES.HALF_FLOAT is WebGL1 HALF_FLOAT_OES - // we have to convert it to WebGL HALF_FLOAT - glTexture.type = this.gl.HALF_FLOAT; - } - else { - glTexture.type = texture.type; - } - }; - /** - * Update a texture - * @private - * @param {PIXI.BaseTexture} texture - Texture to initialize - */ - TextureSystem.prototype.updateTexture = function (texture) { - var glTexture = texture._glTextures[this.CONTEXT_UID]; - if (!glTexture) { - return; - } - var renderer = this.renderer; - this.initTextureType(texture, glTexture); - if (texture.resource && texture.resource.upload(renderer, texture, glTexture)) { - // texture is uploaded, dont do anything! - if (glTexture.samplerType !== exports.SAMPLER_TYPES.FLOAT) { - this.hasIntegerTextures = true; - } - } - else { - // default, renderTexture-like logic - var width = texture.realWidth; - var height = texture.realHeight; - var gl = renderer.gl; - if (glTexture.width !== width - || glTexture.height !== height - || glTexture.dirtyId < 0) { - glTexture.width = width; - glTexture.height = height; - gl.texImage2D(texture.target, 0, glTexture.internalFormat, width, height, 0, texture.format, glTexture.type, null); - } - } - // lets only update what changes.. - if (texture.dirtyStyleId !== glTexture.dirtyStyleId) { - this.updateTextureStyle(texture); - } - glTexture.dirtyId = texture.dirtyId; - }; - /** - * Deletes the texture from WebGL - * @private - * @param texture - the texture to destroy - * @param [skipRemove=false] - Whether to skip removing the texture from the TextureManager. - */ - TextureSystem.prototype.destroyTexture = function (texture, skipRemove) { - var gl = this.gl; - texture = texture.castToBaseTexture(); - if (texture._glTextures[this.CONTEXT_UID]) { - this.unbind(texture); - gl.deleteTexture(texture._glTextures[this.CONTEXT_UID].texture); - texture.off('dispose', this.destroyTexture, this); - delete texture._glTextures[this.CONTEXT_UID]; - if (!skipRemove) { - var i = this.managedTextures.indexOf(texture); - if (i !== -1) { - removeItems(this.managedTextures, i, 1); - } - } - } - }; - /** - * Update texture style such as mipmap flag - * @private - * @param {PIXI.BaseTexture} texture - Texture to update - */ - TextureSystem.prototype.updateTextureStyle = function (texture) { - var glTexture = texture._glTextures[this.CONTEXT_UID]; - if (!glTexture) { - return; - } - if ((texture.mipmap === exports.MIPMAP_MODES.POW2 || this.webGLVersion !== 2) && !texture.isPowerOfTwo) { - glTexture.mipmap = false; - } - else { - glTexture.mipmap = texture.mipmap >= 1; - } - if (this.webGLVersion !== 2 && !texture.isPowerOfTwo) { - glTexture.wrapMode = exports.WRAP_MODES.CLAMP; - } - else { - glTexture.wrapMode = texture.wrapMode; - } - if (texture.resource && texture.resource.style(this.renderer, texture, glTexture)) { ; } - else { - this.setStyle(texture, glTexture); - } - glTexture.dirtyStyleId = texture.dirtyStyleId; - }; - /** - * Set style for texture - * @private - * @param texture - Texture to update - * @param glTexture - */ - TextureSystem.prototype.setStyle = function (texture, glTexture) { - var gl = this.gl; - if (glTexture.mipmap && texture.mipmap !== exports.MIPMAP_MODES.ON_MANUAL) { - gl.generateMipmap(texture.target); - } - gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, glTexture.wrapMode); - gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, glTexture.wrapMode); - if (glTexture.mipmap) { - /* eslint-disable max-len */ - gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode === exports.SCALE_MODES.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - /* eslint-disable max-len */ - var anisotropicExt = this.renderer.context.extensions.anisotropicFiltering; - if (anisotropicExt && texture.anisotropicLevel > 0 && texture.scaleMode === exports.SCALE_MODES.LINEAR) { - var level = Math.min(texture.anisotropicLevel, gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT)); - gl.texParameterf(texture.target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, level); - } - } - else { - gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode === exports.SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST); - } - gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode === exports.SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST); - }; - TextureSystem.prototype.destroy = function () { - this.renderer = null; - }; - return TextureSystem; - }()); - - var _systems = { - __proto__: null, - FilterSystem: FilterSystem, - BatchSystem: BatchSystem, - ContextSystem: ContextSystem, - FramebufferSystem: FramebufferSystem, - GeometrySystem: GeometrySystem, - MaskSystem: MaskSystem, - ScissorSystem: ScissorSystem, - StencilSystem: StencilSystem, - ProjectionSystem: ProjectionSystem, - RenderTextureSystem: RenderTextureSystem, - ShaderSystem: ShaderSystem, - StateSystem: StateSystem, - TextureGCSystem: TextureGCSystem, - TextureSystem: TextureSystem - }; - - var tempMatrix = new Matrix(); - /** - * The AbstractRenderer is the base for a PixiJS Renderer. It is extended by the {@link PIXI.CanvasRenderer} - * and {@link PIXI.Renderer} which can be used for rendering a PixiJS scene. - * @abstract - * @class - * @extends PIXI.utils.EventEmitter - * @memberof PIXI - */ - var AbstractRenderer = /** @class */ (function (_super) { - __extends$i(AbstractRenderer, _super); - /** - * @param type - The renderer type. - * @param {PIXI.IRendererOptions} [options] - The optional renderer parameters. - * @param {boolean} [options.antialias=false] - - * **WebGL Only.** Whether to enable anti-aliasing. This may affect performance. - * @param {boolean} [options.autoDensity=false] - - * Whether the CSS dimensions of the renderer's view should be resized automatically. - * @param {number} [options.backgroundAlpha=1] - - * Transparency of the background color, value from `0` (fully transparent) to `1` (fully opaque). - * @param {number} [options.backgroundColor=0x000000] - - * The background color used to clear the canvas. It accepts hex numbers (e.g. `0xff0000`). - * @param {boolean} [options.clearBeforeRender=true] - Whether to clear the canvas before new render passes. - * @param {PIXI.IRenderingContext} [options.context] - **WebGL Only.** User-provided WebGL rendering context object. - * @param {number} [options.height=600] - The height of the renderer's view. - * @param {string} [options.powerPreference] - - * **WebGL Only.** A hint indicating what configuration of GPU is suitable for the WebGL context, - * can be `'default'`, `'high-performance'` or `'low-power'`. - * Setting to `'high-performance'` will prioritize rendering performance over power consumption, - * while setting to `'low-power'` will prioritize power saving over rendering performance. - * @param {boolean} [options.premultipliedAlpha=true] - - * **WebGL Only.** Whether the compositor will assume the drawing buffer contains colors with premultiplied alpha. - * @param {boolean} [options.preserveDrawingBuffer=false] - - * **WebGL Only.** Whether to enable drawing buffer preservation. If enabled, the drawing buffer will preserve - * its value until cleared or overwritten. Enable this if you need to call `toDataUrl` on the WebGL context. - * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - - * The resolution / device pixel ratio of the renderer. - * @param {boolean} [options.transparent] - - * **Deprecated since 6.0.0, Use `backgroundAlpha` instead.** \ - * `true` sets `backgroundAlpha` to `0`, `false` sets `backgroundAlpha` to `1`. - * @param {boolean|'notMultiplied'} [options.useContextAlpha=true] - - * Pass-through value for canvas' context attribute `alpha`. This option is for cases where the - * canvas needs to be opaque, possibly for performance reasons on some older devices. - * If you want to set transparency, please use `backgroundAlpha`. \ - * **WebGL Only:** When set to `'notMultiplied'`, the canvas' context attribute `alpha` will be - * set to `true` and `premultipliedAlpha` will be to `false`. - * @param {HTMLCanvasElement} [options.view=null] - - * The canvas to use as the view. If omitted, a new canvas will be created. - * @param {number} [options.width=800] - The width of the renderer's view. - */ - function AbstractRenderer(type, options) { - if (type === void 0) { type = exports.RENDERER_TYPE.UNKNOWN; } - var _this = _super.call(this) || this; - // Add the default render options - options = Object.assign({}, settings.RENDER_OPTIONS, options); - /** - * The supplied constructor options. - * @member {object} - * @readonly - */ - _this.options = options; - /** - * The type of the renderer. - * @member {number} - * @default PIXI.RENDERER_TYPE.UNKNOWN - * @see PIXI.RENDERER_TYPE - */ - _this.type = type; - /** - * Measurements of the screen. (0, 0, screenWidth, screenHeight). - * - * Its safe to use as filterArea or hitArea for the whole stage. - * @member {PIXI.Rectangle} - */ - _this.screen = new Rectangle(0, 0, options.width, options.height); - /** - * The canvas element that everything is drawn to. - * @member {HTMLCanvasElement} - */ - _this.view = options.view || settings.ADAPTER.createCanvas(); - /** - * The resolution / device pixel ratio of the renderer. - * @member {number} - * @default PIXI.settings.RESOLUTION - */ - _this.resolution = options.resolution || settings.RESOLUTION; - /** - * Pass-thru setting for the canvas' context `alpha` property. This is typically - * not something you need to fiddle with. If you want transparency, use `backgroundAlpha`. - * @member {boolean} - */ - _this.useContextAlpha = options.useContextAlpha; - /** - * Whether CSS dimensions of canvas view should be resized to screen dimensions automatically. - * @member {boolean} - */ - _this.autoDensity = !!options.autoDensity; - /** - * The value of the preserveDrawingBuffer flag affects whether or not the contents of - * the stencil buffer is retained after rendering. - * @member {boolean} - */ - _this.preserveDrawingBuffer = options.preserveDrawingBuffer; - /** - * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. - * If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every - * frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect - * to clear the canvas every frame. Disable this by setting this to false. For example, if - * your game has a canvas filling background image you often don't need this set. - * @member {boolean} - * @default - */ - _this.clearBeforeRender = options.clearBeforeRender; - /** - * The background color as a number. - * @member {number} - * @protected - */ - _this._backgroundColor = 0x000000; - /** - * The background color as an [R, G, B, A] array. - * @member {number[]} - * @protected - */ - _this._backgroundColorRgba = [0, 0, 0, 1]; - /** - * The background color as a string. - * @member {string} - * @protected - */ - _this._backgroundColorString = '#000000'; - _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter - _this.backgroundAlpha = options.backgroundAlpha; - // @deprecated - if (options.transparent !== undefined) { - deprecation('6.0.0', 'Option transparent is deprecated, please use backgroundAlpha instead.'); - _this.useContextAlpha = options.transparent; - _this.backgroundAlpha = options.transparent ? 0 : 1; - } - /** - * The last root object that the renderer tried to render. - * @member {PIXI.DisplayObject} - * @protected - */ - _this._lastObjectRendered = null; - /** - * Collection of plugins. - * @readonly - * @member {object} - */ - _this.plugins = {}; - return _this; - } - /** - * Initialize the plugins. - * @protected - * @param {object} staticMap - The dictionary of statically saved plugins. - */ - AbstractRenderer.prototype.initPlugins = function (staticMap) { - for (var o in staticMap) { - this.plugins[o] = new (staticMap[o])(this); - } - }; - Object.defineProperty(AbstractRenderer.prototype, "width", { - /** - * Same as view.width, actual number of pixels in the canvas by horizontal. - * @member {number} - * @readonly - * @default 800 - */ - get: function () { - return this.view.width; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AbstractRenderer.prototype, "height", { - /** - * Same as view.height, actual number of pixels in the canvas by vertical. - * @member {number} - * @readonly - * @default 600 - */ - get: function () { - return this.view.height; - }, - enumerable: false, - configurable: true - }); - /** - * Resizes the screen and canvas as close as possible to the specified width and height. - * Canvas dimensions are multiplied by resolution and rounded to the nearest integers. - * The new canvas dimensions divided by the resolution become the new screen dimensions. - * @param desiredScreenWidth - The desired width of the screen. - * @param desiredScreenHeight - The desired height of the screen. - */ - AbstractRenderer.prototype.resize = function (desiredScreenWidth, desiredScreenHeight) { - this.view.width = Math.round(desiredScreenWidth * this.resolution); - this.view.height = Math.round(desiredScreenHeight * this.resolution); - var screenWidth = this.view.width / this.resolution; - var screenHeight = this.view.height / this.resolution; - this.screen.width = screenWidth; - this.screen.height = screenHeight; - if (this.autoDensity) { - this.view.style.width = screenWidth + "px"; - this.view.style.height = screenHeight + "px"; - } - /** - * Fired after view has been resized. - * @event PIXI.Renderer#resize - * @param {number} screenWidth - The new width of the screen. - * @param {number} screenHeight - The new height of the screen. - */ - this.emit('resize', screenWidth, screenHeight); - }; - /** - * @ignore - */ - AbstractRenderer.prototype.generateTexture = function (displayObject, options, resolution, region) { - if (options === void 0) { options = {}; } - // @deprecated parameters spread, use options instead - if (typeof options === 'number') { - deprecation('6.1.0', 'generateTexture options (scaleMode, resolution, region) are now object options.'); - options = { scaleMode: options, resolution: resolution, region: region }; - } - var manualRegion = options.region, textureOptions = __rest(options, ["region"]); - region = manualRegion || displayObject.getLocalBounds(null, true); - // minimum texture size is 1x1, 0x0 will throw an error - if (region.width === 0) - { region.width = 1; } - if (region.height === 0) - { region.height = 1; } - var renderTexture = RenderTexture.create(__assign({ width: region.width, height: region.height }, textureOptions)); - tempMatrix.tx = -region.x; - tempMatrix.ty = -region.y; - this.render(displayObject, { - renderTexture: renderTexture, - clear: false, - transform: tempMatrix, - skipUpdateTransform: !!displayObject.parent - }); - return renderTexture; - }; - /** - * Removes everything from the renderer and optionally removes the Canvas DOM element. - * @param [removeView=false] - Removes the Canvas element from the DOM. - */ - AbstractRenderer.prototype.destroy = function (removeView) { - for (var o in this.plugins) { - this.plugins[o].destroy(); - this.plugins[o] = null; - } - if (removeView && this.view.parentNode) { - this.view.parentNode.removeChild(this.view); - } - var thisAny = this; - // null-ing all objects, that's a tradition! - thisAny.plugins = null; - thisAny.type = exports.RENDERER_TYPE.UNKNOWN; - thisAny.view = null; - thisAny.screen = null; - thisAny._tempDisplayObjectParent = null; - thisAny.options = null; - this._backgroundColorRgba = null; - this._backgroundColorString = null; - this._lastObjectRendered = null; - }; - Object.defineProperty(AbstractRenderer.prototype, "backgroundColor", { - /** - * The background color to fill if not transparent - * @member {number} - */ - get: function () { - return this._backgroundColor; - }, - set: function (value) { - this._backgroundColor = value; - this._backgroundColorString = hex2string(value); - hex2rgb(value, this._backgroundColorRgba); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AbstractRenderer.prototype, "backgroundAlpha", { - /** - * The background color alpha. Setting this to 0 will make the canvas transparent. - * @member {number} - */ - get: function () { - return this._backgroundColorRgba[3]; - }, - set: function (value) { - this._backgroundColorRgba[3] = value; - }, - enumerable: false, - configurable: true - }); - return AbstractRenderer; - }(eventemitter3)); - - var GLBuffer = /** @class */ (function () { - function GLBuffer(buffer) { - this.buffer = buffer || null; - this.updateID = -1; - this.byteLength = -1; - this.refCount = 0; - } - return GLBuffer; - }()); - - /** - * System plugin to the renderer to manage buffers. - * - * WebGL uses Buffers as a way to store objects to the GPU. - * This system makes working with them a lot easier. - * - * Buffers are used in three main places in WebGL - * - geometry information - * - Uniform information (via uniform buffer objects - a WebGL 2 only feature) - * - Transform feedback information. (WebGL 2 only feature) - * - * This system will handle the binding of buffers to the GPU as well as uploading - * them. With this system, you never need to work directly with GPU buffers, but instead work with - * the PIXI.Buffer class. - * @class - * @memberof PIXI - */ - var BufferSystem = /** @class */ (function () { - /** - * @param {PIXI.Renderer} renderer - The renderer this System works for. - */ - function BufferSystem(renderer) { - this.renderer = renderer; - this.managedBuffers = {}; - this.boundBufferBases = {}; - } - /** - * @ignore - */ - BufferSystem.prototype.destroy = function () { - this.renderer = null; - }; - /** Sets up the renderer context and necessary buffers. */ - BufferSystem.prototype.contextChange = function () { - this.disposeAll(true); - this.gl = this.renderer.gl; - // TODO fill out... - this.CONTEXT_UID = this.renderer.CONTEXT_UID; - }; - /** - * This binds specified buffer. On first run, it will create the webGL buffers for the context too - * @param buffer - the buffer to bind to the renderer - */ - BufferSystem.prototype.bind = function (buffer) { - var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; - var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer); - gl.bindBuffer(buffer.type, glBuffer.buffer); - }; - /** - * Binds an uniform buffer to at the given index. - * - * A cache is used so a buffer will not be bound again if already bound. - * @param buffer - the buffer to bind - * @param index - the base index to bind it to. - */ - BufferSystem.prototype.bindBufferBase = function (buffer, index) { - var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; - if (this.boundBufferBases[index] !== buffer) { - var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer); - this.boundBufferBases[index] = buffer; - gl.bindBufferBase(gl.UNIFORM_BUFFER, index, glBuffer.buffer); - } - }; - /** - * Binds a buffer whilst also binding its range. - * This will make the buffer start from the offset supplied rather than 0 when it is read. - * @param buffer - the buffer to bind - * @param index - the base index to bind at, defaults to 0 - * @param offset - the offset to bind at (this is blocks of 256). 0 = 0, 1 = 256, 2 = 512 etc - */ - BufferSystem.prototype.bindBufferRange = function (buffer, index, offset) { - var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; - offset = offset || 0; - var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer); - gl.bindBufferRange(gl.UNIFORM_BUFFER, index || 0, glBuffer.buffer, offset * 256, 256); - }; - /** - * Will ensure the data in the buffer is uploaded to the GPU. - * @param {PIXI.Buffer} buffer - the buffer to update - */ - BufferSystem.prototype.update = function (buffer) { - var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; - var glBuffer = buffer._glBuffers[CONTEXT_UID]; - if (buffer._updateID === glBuffer.updateID) { - return; - } - glBuffer.updateID = buffer._updateID; - gl.bindBuffer(buffer.type, glBuffer.buffer); - if (glBuffer.byteLength >= buffer.data.byteLength) { - // offset is always zero for now! - gl.bufferSubData(buffer.type, 0, buffer.data); - } - else { - var drawType = buffer.static ? gl.STATIC_DRAW : gl.DYNAMIC_DRAW; - glBuffer.byteLength = buffer.data.byteLength; - gl.bufferData(buffer.type, buffer.data, drawType); - } - }; - /** - * Disposes buffer - * @param {PIXI.Buffer} buffer - buffer with data - * @param {boolean} [contextLost=false] - If context was lost, we suppress deleteVertexArray - */ - BufferSystem.prototype.dispose = function (buffer, contextLost) { - if (!this.managedBuffers[buffer.id]) { - return; - } - delete this.managedBuffers[buffer.id]; - var glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - var gl = this.gl; - buffer.disposeRunner.remove(this); - if (!glBuffer) { - return; - } - if (!contextLost) { - gl.deleteBuffer(glBuffer.buffer); - } - delete buffer._glBuffers[this.CONTEXT_UID]; - }; - /** - * dispose all WebGL resources of all managed buffers - * @param {boolean} [contextLost=false] - If context was lost, we suppress `gl.delete` calls - */ - BufferSystem.prototype.disposeAll = function (contextLost) { - var all = Object.keys(this.managedBuffers); - for (var i = 0; i < all.length; i++) { - this.dispose(this.managedBuffers[all[i]], contextLost); - } - }; - /** - * creates and attaches a GLBuffer object tied to the current context. - * @param buffer - * @protected - */ - BufferSystem.prototype.createGLBuffer = function (buffer) { - var _a = this, CONTEXT_UID = _a.CONTEXT_UID, gl = _a.gl; - buffer._glBuffers[CONTEXT_UID] = new GLBuffer(gl.createBuffer()); - this.managedBuffers[buffer.id] = buffer; - buffer.disposeRunner.add(this); - return buffer._glBuffers[CONTEXT_UID]; - }; - return BufferSystem; - }()); - - /** - * The Renderer draws the scene and all its content onto a WebGL enabled canvas. - * - * This renderer should be used for browsers that support WebGL. - * - * This renderer works by automatically managing WebGLBatchesm, so no need for Sprite Batches or Sprite Clouds. - * Don't forget to add the view to your DOM or you will not see anything! - * - * Renderer is composed of systems that manage specific tasks. The following systems are added by default - * whenever you create a renderer: - * - * | System | Description | - * | ------------------------------------ | ----------------------------------------------------------------------------- | - * | {@link PIXI.BatchSystem} | This manages object renderers that defer rendering until a flush. | - * | {@link PIXI.ContextSystem} | This manages the WebGL context and extensions. | - * | {@link PIXI.EventSystem} | This manages UI events. | - * | {@link PIXI.FilterSystem} | This manages the filtering pipeline for post-processing effects. | - * | {@link PIXI.FramebufferSystem} | This manages framebuffers, which are used for offscreen rendering. | - * | {@link PIXI.GeometrySystem} | This manages geometries & buffers, which are used to draw object meshes. | - * | {@link PIXI.MaskSystem} | This manages masking operations. | - * | {@link PIXI.ProjectionSystem} | This manages the `projectionMatrix`, used by shaders to get NDC coordinates. | - * | {@link PIXI.RenderTextureSystem} | This manages render-textures, which are an abstraction over framebuffers. | - * | {@link PIXI.ScissorSystem} | This handles scissor masking, and is used internally by {@link MaskSystem} | - * | {@link PIXI.ShaderSystem} | This manages shaders, programs that run on the GPU to calculate 'em pixels. | - * | {@link PIXI.StateSystem} | This manages the WebGL state variables like blend mode, depth testing, etc. | - * | {@link PIXI.StencilSystem} | This handles stencil masking, and is used internally by {@link MaskSystem} | - * | {@link PIXI.TextureSystem} | This manages textures and their resources on the GPU. | - * | {@link PIXI.TextureGCSystem} | This will automatically remove textures from the GPU if they are not used. | - * - * The breadth of the API surface provided by the renderer is contained within these systems. - * @memberof PIXI - */ - var Renderer = /** @class */ (function (_super) { - __extends$i(Renderer, _super); - /** - * @param {PIXI.IRendererOptions} [options] - The optional renderer parameters. - * @param {boolean} [options.antialias=false] - - * **WebGL Only.** Whether to enable anti-aliasing. This may affect performance. - * @param {boolean} [options.autoDensity=false] - - * Whether the CSS dimensions of the renderer's view should be resized automatically. - * @param {number} [options.backgroundAlpha=1] - - * Transparency of the background color, value from `0` (fully transparent) to `1` (fully opaque). - * @param {number} [options.backgroundColor=0x000000] - - * The background color used to clear the canvas. It accepts hex numbers (e.g. `0xff0000`). - * @param {boolean} [options.clearBeforeRender=true] - Whether to clear the canvas before new render passes. - * @param {PIXI.IRenderingContext} [options.context] - **WebGL Only.** User-provided WebGL rendering context object. - * @param {number} [options.height=600] - The height of the renderer's view. - * @param {string} [options.powerPreference] - - * **WebGL Only.** A hint indicating what configuration of GPU is suitable for the WebGL context, - * can be `'default'`, `'high-performance'` or `'low-power'`. - * Setting to `'high-performance'` will prioritize rendering performance over power consumption, - * while setting to `'low-power'` will prioritize power saving over rendering performance. - * @param {boolean} [options.premultipliedAlpha=true] - - * **WebGL Only.** Whether the compositor will assume the drawing buffer contains colors with premultiplied alpha. - * @param {boolean} [options.preserveDrawingBuffer=false] - - * **WebGL Only.** Whether to enable drawing buffer preservation. If enabled, the drawing buffer will preserve - * its value until cleared or overwritten. Enable this if you need to call `toDataUrl` on the WebGL context. - * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - - * The resolution / device pixel ratio of the renderer. - * @param {boolean} [options.transparent] - - * **Deprecated since 6.0.0, Use `backgroundAlpha` instead.** \ - * `true` sets `backgroundAlpha` to `0`, `false` sets `backgroundAlpha` to `1`. - * @param {boolean|'notMultiplied'} [options.useContextAlpha=true] - - * Pass-through value for canvas' context attribute `alpha`. This option is for cases where the - * canvas needs to be opaque, possibly for performance reasons on some older devices. - * If you want to set transparency, please use `backgroundAlpha`. \ - * **WebGL Only:** When set to `'notMultiplied'`, the canvas' context attribute `alpha` will be - * set to `true` and `premultipliedAlpha` will be to `false`. - * @param {HTMLCanvasElement} [options.view=null] - - * The canvas to use as the view. If omitted, a new canvas will be created. - * @param {number} [options.width=800] - The width of the renderer's view. - */ - function Renderer(options) { - var _this = _super.call(this, exports.RENDERER_TYPE.WEBGL, options) || this; - // the options will have been modified here in the super constructor with pixi's default settings.. - options = _this.options; - _this.gl = null; - _this.CONTEXT_UID = 0; - _this.runners = { - destroy: new Runner('destroy'), - contextChange: new Runner('contextChange'), - reset: new Runner('reset'), - update: new Runner('update'), - postrender: new Runner('postrender'), - prerender: new Runner('prerender'), - resize: new Runner('resize'), - }; - _this.runners.contextChange.add(_this); - _this.globalUniforms = new UniformGroup({ - projectionMatrix: new Matrix(), - }, true); - _this.addSystem(MaskSystem, 'mask') - .addSystem(ContextSystem, 'context') - .addSystem(StateSystem, 'state') - .addSystem(ShaderSystem, 'shader') - .addSystem(TextureSystem, 'texture') - .addSystem(BufferSystem, 'buffer') - .addSystem(GeometrySystem, 'geometry') - .addSystem(FramebufferSystem, 'framebuffer') - .addSystem(ScissorSystem, 'scissor') - .addSystem(StencilSystem, 'stencil') - .addSystem(ProjectionSystem, 'projection') - .addSystem(TextureGCSystem, 'textureGC') - .addSystem(FilterSystem, 'filter') - .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem, 'batch'); - _this.initPlugins(Renderer.__plugins); - _this.multisample = undefined; - /* - * The options passed in to create a new WebGL context. - */ - if (options.context) { - _this.context.initFromContext(options.context); - } - else { - _this.context.initFromOptions({ - alpha: !!_this.useContextAlpha, - antialias: options.antialias, - premultipliedAlpha: _this.useContextAlpha && _this.useContextAlpha !== 'notMultiplied', - stencil: true, - preserveDrawingBuffer: options.preserveDrawingBuffer, - powerPreference: _this.options.powerPreference, - }); - } - _this.renderingToScreen = true; - sayHello(_this.context.webGLVersion === 2 ? 'WebGL 2' : 'WebGL 1'); - _this.resize(_this.options.width, _this.options.height); - return _this; - } - /** - * Create renderer if WebGL is available. Overrideable - * by the **@pixi/canvas-renderer** package to allow fallback. - * throws error if WebGL is not available. - * @param options - * @private - */ - Renderer.create = function (options) { - if (isWebGLSupported()) { - return new Renderer(options); - } - throw new Error('WebGL unsupported in this browser, use "pixi.js-legacy" for fallback canvas2d support.'); - }; - Renderer.prototype.contextChange = function () { - var gl = this.gl; - var samples; - if (this.context.webGLVersion === 1) { - var framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - samples = gl.getParameter(gl.SAMPLES); - gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); - } - else { - var framebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING); - gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null); - samples = gl.getParameter(gl.SAMPLES); - gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, framebuffer); - } - if (samples >= exports.MSAA_QUALITY.HIGH) { - this.multisample = exports.MSAA_QUALITY.HIGH; - } - else if (samples >= exports.MSAA_QUALITY.MEDIUM) { - this.multisample = exports.MSAA_QUALITY.MEDIUM; - } - else if (samples >= exports.MSAA_QUALITY.LOW) { - this.multisample = exports.MSAA_QUALITY.LOW; - } - else { - this.multisample = exports.MSAA_QUALITY.NONE; - } - }; - /** - * Add a new system to the renderer. - * @param ClassRef - Class reference - * @param name - Property name for system, if not specified - * will use a static `name` property on the class itself. This - * name will be assigned as s property on the Renderer so make - * sure it doesn't collide with properties on Renderer. - * @returns Return instance of renderer - */ - Renderer.prototype.addSystem = function (ClassRef, name) { - var system = new ClassRef(this); - if (this[name]) { - throw new Error("Whoops! The name \"" + name + "\" is already in use"); - } - this[name] = system; - for (var i in this.runners) { - this.runners[i].add(system); - } - /** - * Fired after rendering finishes. - * @event PIXI.Renderer#postrender - */ - /** - * Fired before rendering starts. - * @event PIXI.Renderer#prerender - */ - /** - * Fired when the WebGL context is set. - * @event PIXI.Renderer#context - * @param {WebGLRenderingContext} gl - WebGL context. - */ - return this; - }; - /** - * @ignore - */ - Renderer.prototype.render = function (displayObject, options) { - var renderTexture; - var clear; - var transform; - var skipUpdateTransform; - if (options) { - if (options instanceof RenderTexture) { - deprecation('6.0.0', 'Renderer#render arguments changed, use options instead.'); - /* eslint-disable prefer-rest-params */ - renderTexture = options; - clear = arguments[2]; - transform = arguments[3]; - skipUpdateTransform = arguments[4]; - /* eslint-enable prefer-rest-params */ - } - else { - renderTexture = options.renderTexture; - clear = options.clear; - transform = options.transform; - skipUpdateTransform = options.skipUpdateTransform; - } - } - // can be handy to know! - this.renderingToScreen = !renderTexture; - this.runners.prerender.emit(); - this.emit('prerender'); - // apply a transform at a GPU level - this.projection.transform = transform; - // no point rendering if our context has been blown up! - if (this.context.isLost) { - return; - } - if (!renderTexture) { - this._lastObjectRendered = displayObject; - } - if (!skipUpdateTransform) { - // update the scene graph - var cacheParent = displayObject.enableTempParent(); - displayObject.updateTransform(); - displayObject.disableTempParent(cacheParent); - // displayObject.hitArea = //TODO add a temp hit area - } - this.renderTexture.bind(renderTexture); - this.batch.currentRenderer.start(); - if (clear !== undefined ? clear : this.clearBeforeRender) { - this.renderTexture.clear(); - } - displayObject.render(this); - // apply transform.. - this.batch.currentRenderer.flush(); - if (renderTexture) { - renderTexture.baseTexture.update(); - } - this.runners.postrender.emit(); - // reset transform after render - this.projection.transform = null; - this.emit('postrender'); - }; - /** - * @override - * @ignore - */ - Renderer.prototype.generateTexture = function (displayObject, options, resolution, region) { - if (options === void 0) { options = {}; } - var renderTexture = _super.prototype.generateTexture.call(this, displayObject, options, resolution, region); - this.framebuffer.blit(); - return renderTexture; - }; - /** - * Resizes the WebGL view to the specified width and height. - * @param desiredScreenWidth - The desired width of the screen. - * @param desiredScreenHeight - The desired height of the screen. - */ - Renderer.prototype.resize = function (desiredScreenWidth, desiredScreenHeight) { - _super.prototype.resize.call(this, desiredScreenWidth, desiredScreenHeight); - this.runners.resize.emit(this.screen.height, this.screen.width); - }; - /** - * Resets the WebGL state so you can render things however you fancy! - * @returns Returns itself. - */ - Renderer.prototype.reset = function () { - this.runners.reset.emit(); - return this; - }; - /** Clear the frame buffer. */ - Renderer.prototype.clear = function () { - this.renderTexture.bind(); - this.renderTexture.clear(); - }; - /** - * Removes everything from the renderer (event listeners, spritebatch, etc...) - * @param [removeView=false] - Removes the Canvas element from the DOM. - * See: https://github.com/pixijs/pixi.js/issues/2233 - */ - Renderer.prototype.destroy = function (removeView) { - this.runners.destroy.emit(); - for (var r in this.runners) { - this.runners[r].destroy(); - } - // call base destroy - _super.prototype.destroy.call(this, removeView); - // TODO nullify all the managers.. - this.gl = null; - }; - Object.defineProperty(Renderer.prototype, "extract", { - /** - * Please use `plugins.extract` instead. - * @member {PIXI.Extract} extract - * @deprecated since 6.0.0 - * @readonly - */ - get: function () { - deprecation('6.0.0', 'Renderer#extract has been deprecated, please use Renderer#plugins.extract instead.'); - return this.plugins.extract; - }, - enumerable: false, - configurable: true - }); - /** - * Use the {@link PIXI.extensions.add} API to register plugins. - * @deprecated since 6.5.0 - * @param pluginName - The name of the plugin. - * @param ctor - The constructor function or class for the plugin. - */ - Renderer.registerPlugin = function (pluginName, ctor) { - deprecation('6.5.0', 'Renderer.registerPlugin() has been deprecated, please use extensions.add() instead.'); - extensions.add({ - name: pluginName, - type: exports.ExtensionType.RendererPlugin, - ref: ctor, - }); - }; - /** - * Collection of installed plugins. These are included by default in PIXI, but can be excluded - * by creating a custom build. Consult the README for more information about creating custom - * builds and excluding plugins. - * @readonly - * @property {PIXI.AccessibilityManager} accessibility Support tabbing interactive elements. - * @property {PIXI.Extract} extract Extract image data from renderer. - * @property {PIXI.InteractionManager} interaction Handles mouse, touch and pointer events. - * @property {PIXI.ParticleRenderer} particle Renderer for ParticleContainer objects. - * @property {PIXI.Prepare} prepare Pre-render display objects. - * @property {PIXI.BatchRenderer} batch Batching of Sprite, Graphics and Mesh objects. - * @property {PIXI.TilingSpriteRenderer} tilingSprite Renderer for TilingSprite objects. - */ - Renderer.__plugins = {}; - return Renderer; - }(AbstractRenderer)); - // Handle registration of extensions - extensions.handleByMap(exports.ExtensionType.RendererPlugin, Renderer.__plugins); - - /** - * This helper function will automatically detect which renderer you should be using. - * WebGL is the preferred renderer as it is a lot faster. If WebGL is not supported by - * the browser then this function will return a canvas renderer. - * @memberof PIXI - * @function autoDetectRenderer - * @param {PIXI.IRendererOptionsAuto} [options] - The optional renderer parameters. - * @param {boolean} [options.antialias=false] - - * **WebGL Only.** Whether to enable anti-aliasing. This may affect performance. - * @param {boolean} [options.autoDensity=false] - - * Whether the CSS dimensions of the renderer's view should be resized automatically. - * @param {number} [options.backgroundAlpha=1] - - * Transparency of the background color, value from `0` (fully transparent) to `1` (fully opaque). - * @param {number} [options.backgroundColor=0x000000] - - * The background color used to clear the canvas. It accepts hex numbers (e.g. `0xff0000`). - * @param {boolean} [options.clearBeforeRender=true] - Whether to clear the canvas before new render passes. - * @param {PIXI.IRenderingContext} [options.context] - **WebGL Only.** User-provided WebGL rendering context object. - * @param {boolean} [options.forceCanvas=false] - - * Force using {@link PIXI.CanvasRenderer}, even if WebGL is available. This option only is available when - * using **pixi.js-legacy** or **@pixi/canvas-renderer** packages, otherwise it is ignored. - * @param {number} [options.height=600] - The height of the renderer's view. - * @param {string} [options.powerPreference] - - * **WebGL Only.** A hint indicating what configuration of GPU is suitable for the WebGL context, - * can be `'default'`, `'high-performance'` or `'low-power'`. - * Setting to `'high-performance'` will prioritize rendering performance over power consumption, - * while setting to `'low-power'` will prioritize power saving over rendering performance. - * @param {boolean} [options.premultipliedAlpha=true] - - * **WebGL Only.** Whether the compositor will assume the drawing buffer contains colors with premultiplied alpha. - * @param {boolean} [options.preserveDrawingBuffer=false] - - * **WebGL Only.** Whether to enable drawing buffer preservation. If enabled, the drawing buffer will preserve - * its value until cleared or overwritten. Enable this if you need to call `toDataUrl` on the WebGL context. - * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - - * The resolution / device pixel ratio of the renderer. - * @param {boolean} [options.transparent] - - * **Deprecated since 6.0.0, Use `backgroundAlpha` instead.** \ - * `true` sets `backgroundAlpha` to `0`, `false` sets `backgroundAlpha` to `1`. - * @param {boolean|'notMultiplied'} [options.useContextAlpha=true] - - * Pass-through value for canvas' context attribute `alpha`. This option is for cases where the - * canvas needs to be opaque, possibly for performance reasons on some older devices. - * If you want to set transparency, please use `backgroundAlpha`. \ - * **WebGL Only:** When set to `'notMultiplied'`, the canvas' context attribute `alpha` will be - * set to `true` and `premultipliedAlpha` will be to `false`. - * @param {HTMLCanvasElement} [options.view=null] - - * The canvas to use as the view. If omitted, a new canvas will be created. - * @param {number} [options.width=800] - The width of the renderer's view. - * @returns {PIXI.Renderer|PIXI.CanvasRenderer} - * Returns {@link PIXI.Renderer} if WebGL is available, otherwise {@link PIXI.CanvasRenderer}. - */ - function autoDetectRenderer(options) { - return Renderer.create(options); - } - - var $defaultVertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}"; - - var $defaultFilterVertex = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"; - - /** - * Default vertex shader - * @memberof PIXI - * @member {string} defaultVertex - */ - /** - * Default filter vertex shader - * @memberof PIXI - * @member {string} defaultFilterVertex - */ - // NOTE: This black magic is so that @microsoft/api-extractor does not complain! This explicitly specifies the types - // of defaultVertex, defaultFilterVertex. - var defaultVertex$1 = $defaultVertex; - var defaultFilterVertex = $defaultFilterVertex; - - /** - * Use the ISystem interface instead. - * @deprecated since 6.1.0 - * @memberof PIXI - */ - var System = /** @class */ (function () { - /** - * @param renderer - Reference to Renderer - */ - function System(renderer) { - deprecation('6.1.0', 'System class is deprecated, implemement ISystem interface instead.'); - this.renderer = renderer; - } - /** Destroy and don't use after this. */ - System.prototype.destroy = function () { - this.renderer = null; - }; - return System; - }()); - - /** - * Used by the batcher to draw batches. - * Each one of these contains all information required to draw a bound geometry. - * @memberof PIXI - */ - var BatchDrawCall = /** @class */ (function () { - function BatchDrawCall() { - this.texArray = null; - this.blend = 0; - this.type = exports.DRAW_MODES.TRIANGLES; - this.start = 0; - this.size = 0; - this.data = null; - } - return BatchDrawCall; - }()); - - /** - * Used by the batcher to build texture batches. - * Holds list of textures and their respective locations. - * @memberof PIXI - */ - var BatchTextureArray = /** @class */ (function () { - function BatchTextureArray() { - this.elements = []; - this.ids = []; - this.count = 0; - } - BatchTextureArray.prototype.clear = function () { - for (var i = 0; i < this.count; i++) { - this.elements[i] = null; - } - this.count = 0; - }; - return BatchTextureArray; - }()); - - /** - * Flexible wrapper around `ArrayBuffer` that also provides typed array views on demand. - * @memberof PIXI - */ - var ViewableBuffer = /** @class */ (function () { - function ViewableBuffer(sizeOrBuffer) { - if (typeof sizeOrBuffer === 'number') { - this.rawBinaryData = new ArrayBuffer(sizeOrBuffer); - } - else if (sizeOrBuffer instanceof Uint8Array) { - this.rawBinaryData = sizeOrBuffer.buffer; - } - else { - this.rawBinaryData = sizeOrBuffer; - } - this.uint32View = new Uint32Array(this.rawBinaryData); - this.float32View = new Float32Array(this.rawBinaryData); - } - Object.defineProperty(ViewableBuffer.prototype, "int8View", { - /** View on the raw binary data as a `Int8Array`. */ - get: function () { - if (!this._int8View) { - this._int8View = new Int8Array(this.rawBinaryData); - } - return this._int8View; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ViewableBuffer.prototype, "uint8View", { - /** View on the raw binary data as a `Uint8Array`. */ - get: function () { - if (!this._uint8View) { - this._uint8View = new Uint8Array(this.rawBinaryData); - } - return this._uint8View; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ViewableBuffer.prototype, "int16View", { - /** View on the raw binary data as a `Int16Array`. */ - get: function () { - if (!this._int16View) { - this._int16View = new Int16Array(this.rawBinaryData); - } - return this._int16View; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ViewableBuffer.prototype, "uint16View", { - /** View on the raw binary data as a `Uint16Array`. */ - get: function () { - if (!this._uint16View) { - this._uint16View = new Uint16Array(this.rawBinaryData); - } - return this._uint16View; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ViewableBuffer.prototype, "int32View", { - /** View on the raw binary data as a `Int32Array`. */ - get: function () { - if (!this._int32View) { - this._int32View = new Int32Array(this.rawBinaryData); - } - return this._int32View; - }, - enumerable: false, - configurable: true - }); - /** - * Returns the view of the given type. - * @param type - One of `int8`, `uint8`, `int16`, - * `uint16`, `int32`, `uint32`, and `float32`. - * @returns - typed array of given type - */ - ViewableBuffer.prototype.view = function (type) { - return this[type + "View"]; - }; - /** Destroys all buffer references. Do not use after calling this. */ - ViewableBuffer.prototype.destroy = function () { - this.rawBinaryData = null; - this._int8View = null; - this._uint8View = null; - this._int16View = null; - this._uint16View = null; - this._int32View = null; - this.uint32View = null; - this.float32View = null; - }; - ViewableBuffer.sizeOf = function (type) { - switch (type) { - case 'int8': - case 'uint8': - return 1; - case 'int16': - case 'uint16': - return 2; - case 'int32': - case 'uint32': - case 'float32': - return 4; - default: - throw new Error(type + " isn't a valid view type"); - } - }; - return ViewableBuffer; - }()); - - /** - * Renderer dedicated to drawing and batching sprites. - * - * This is the default batch renderer. It buffers objects - * with texture-based geometries and renders them in - * batches. It uploads multiple textures to the GPU to - * reduce to the number of draw calls. - * @memberof PIXI - */ - var AbstractBatchRenderer = /** @class */ (function (_super) { - __extends$i(AbstractBatchRenderer, _super); - /** - * This will hook onto the renderer's `contextChange` - * and `prerender` signals. - * @param {PIXI.Renderer} renderer - The renderer this works for. - */ - function AbstractBatchRenderer(renderer) { - var _this = _super.call(this, renderer) || this; - _this.shaderGenerator = null; - _this.geometryClass = null; - _this.vertexSize = null; - _this.state = State.for2d(); - _this.size = settings.SPRITE_BATCH_SIZE * 4; - _this._vertexCount = 0; - _this._indexCount = 0; - _this._bufferedElements = []; - _this._bufferedTextures = []; - _this._bufferSize = 0; - _this._shader = null; - _this._packedGeometries = []; - _this._packedGeometryPoolSize = 2; - _this._flushId = 0; - _this._aBuffers = {}; - _this._iBuffers = {}; - _this.MAX_TEXTURES = 1; - _this.renderer.on('prerender', _this.onPrerender, _this); - renderer.runners.contextChange.add(_this); - _this._dcIndex = 0; - _this._aIndex = 0; - _this._iIndex = 0; - _this._attributeBuffer = null; - _this._indexBuffer = null; - _this._tempBoundTextures = []; - return _this; - } - /** - * Handles the `contextChange` signal. - * - * It calculates `this.MAX_TEXTURES` and allocating the packed-geometry object pool. - */ - AbstractBatchRenderer.prototype.contextChange = function () { - var gl = this.renderer.gl; - if (settings.PREFER_ENV === exports.ENV.WEBGL_LEGACY) { - this.MAX_TEXTURES = 1; - } - else { - // step 1: first check max textures the GPU can handle. - this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), settings.SPRITE_MAX_TEXTURES); - // step 2: check the maximum number of if statements the shader can have too.. - this.MAX_TEXTURES = checkMaxIfStatementsInShader(this.MAX_TEXTURES, gl); - } - this._shader = this.shaderGenerator.generateShader(this.MAX_TEXTURES); - // we use the second shader as the first one depending on your browser - // may omit aTextureId as it is not used by the shader so is optimized out. - for (var i = 0; i < this._packedGeometryPoolSize; i++) { - /* eslint-disable max-len */ - this._packedGeometries[i] = new (this.geometryClass)(); - } - this.initFlushBuffers(); - }; - /** Makes sure that static and dynamic flush pooled objects have correct dimensions. */ - AbstractBatchRenderer.prototype.initFlushBuffers = function () { - var _drawCallPool = AbstractBatchRenderer._drawCallPool, _textureArrayPool = AbstractBatchRenderer._textureArrayPool; - // max draw calls - var MAX_SPRITES = this.size / 4; - // max texture arrays - var MAX_TA = Math.floor(MAX_SPRITES / this.MAX_TEXTURES) + 1; - while (_drawCallPool.length < MAX_SPRITES) { - _drawCallPool.push(new BatchDrawCall()); - } - while (_textureArrayPool.length < MAX_TA) { - _textureArrayPool.push(new BatchTextureArray()); - } - for (var i = 0; i < this.MAX_TEXTURES; i++) { - this._tempBoundTextures[i] = null; - } - }; - /** Handles the `prerender` signal. It ensures that flushes start from the first geometry object again. */ - AbstractBatchRenderer.prototype.onPrerender = function () { - this._flushId = 0; - }; - /** - * Buffers the "batchable" object. It need not be rendered immediately. - * @param {PIXI.DisplayObject} element - the element to render when - * using this renderer - */ - AbstractBatchRenderer.prototype.render = function (element) { - if (!element._texture.valid) { - return; - } - if (this._vertexCount + (element.vertexData.length / 2) > this.size) { - this.flush(); - } - this._vertexCount += element.vertexData.length / 2; - this._indexCount += element.indices.length; - this._bufferedTextures[this._bufferSize] = element._texture.baseTexture; - this._bufferedElements[this._bufferSize++] = element; - }; - AbstractBatchRenderer.prototype.buildTexturesAndDrawCalls = function () { - var _a = this, textures = _a._bufferedTextures, MAX_TEXTURES = _a.MAX_TEXTURES; - var textureArrays = AbstractBatchRenderer._textureArrayPool; - var batch = this.renderer.batch; - var boundTextures = this._tempBoundTextures; - var touch = this.renderer.textureGC.count; - var TICK = ++BaseTexture._globalBatch; - var countTexArrays = 0; - var texArray = textureArrays[0]; - var start = 0; - batch.copyBoundTextures(boundTextures, MAX_TEXTURES); - for (var i = 0; i < this._bufferSize; ++i) { - var tex = textures[i]; - textures[i] = null; - if (tex._batchEnabled === TICK) { - continue; - } - if (texArray.count >= MAX_TEXTURES) { - batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES); - this.buildDrawCalls(texArray, start, i); - start = i; - texArray = textureArrays[++countTexArrays]; - ++TICK; - } - tex._batchEnabled = TICK; - tex.touched = touch; - texArray.elements[texArray.count++] = tex; - } - if (texArray.count > 0) { - batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES); - this.buildDrawCalls(texArray, start, this._bufferSize); - ++countTexArrays; - ++TICK; - } - // Clean-up - for (var i = 0; i < boundTextures.length; i++) { - boundTextures[i] = null; - } - BaseTexture._globalBatch = TICK; - }; - /** - * Populating drawcalls for rendering - * @param texArray - * @param start - * @param finish - */ - AbstractBatchRenderer.prototype.buildDrawCalls = function (texArray, start, finish) { - var _a = this, elements = _a._bufferedElements, _attributeBuffer = _a._attributeBuffer, _indexBuffer = _a._indexBuffer, vertexSize = _a.vertexSize; - var drawCalls = AbstractBatchRenderer._drawCallPool; - var dcIndex = this._dcIndex; - var aIndex = this._aIndex; - var iIndex = this._iIndex; - var drawCall = drawCalls[dcIndex]; - drawCall.start = this._iIndex; - drawCall.texArray = texArray; - for (var i = start; i < finish; ++i) { - var sprite = elements[i]; - var tex = sprite._texture.baseTexture; - var spriteBlendMode = premultiplyBlendMode[tex.alphaMode ? 1 : 0][sprite.blendMode]; - elements[i] = null; - if (start < i && drawCall.blend !== spriteBlendMode) { - drawCall.size = iIndex - drawCall.start; - start = i; - drawCall = drawCalls[++dcIndex]; - drawCall.texArray = texArray; - drawCall.start = iIndex; - } - this.packInterleavedGeometry(sprite, _attributeBuffer, _indexBuffer, aIndex, iIndex); - aIndex += sprite.vertexData.length / 2 * vertexSize; - iIndex += sprite.indices.length; - drawCall.blend = spriteBlendMode; - } - if (start < finish) { - drawCall.size = iIndex - drawCall.start; - ++dcIndex; - } - this._dcIndex = dcIndex; - this._aIndex = aIndex; - this._iIndex = iIndex; - }; - /** - * Bind textures for current rendering - * @param texArray - */ - AbstractBatchRenderer.prototype.bindAndClearTexArray = function (texArray) { - var textureSystem = this.renderer.texture; - for (var j = 0; j < texArray.count; j++) { - textureSystem.bind(texArray.elements[j], texArray.ids[j]); - texArray.elements[j] = null; - } - texArray.count = 0; - }; - AbstractBatchRenderer.prototype.updateGeometry = function () { - var _a = this, packedGeometries = _a._packedGeometries, attributeBuffer = _a._attributeBuffer, indexBuffer = _a._indexBuffer; - if (!settings.CAN_UPLOAD_SAME_BUFFER) { /* Usually on iOS devices, where the browser doesn't - like uploads to the same buffer in a single frame. */ - if (this._packedGeometryPoolSize <= this._flushId) { - this._packedGeometryPoolSize++; - packedGeometries[this._flushId] = new (this.geometryClass)(); - } - packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData); - packedGeometries[this._flushId]._indexBuffer.update(indexBuffer); - this.renderer.geometry.bind(packedGeometries[this._flushId]); - this.renderer.geometry.updateBuffers(); - this._flushId++; - } - else { - // lets use the faster option, always use buffer number 0 - packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData); - packedGeometries[this._flushId]._indexBuffer.update(indexBuffer); - this.renderer.geometry.updateBuffers(); - } - }; - AbstractBatchRenderer.prototype.drawBatches = function () { - var dcCount = this._dcIndex; - var _a = this.renderer, gl = _a.gl, stateSystem = _a.state; - var drawCalls = AbstractBatchRenderer._drawCallPool; - var curTexArray = null; - // Upload textures and do the draw calls - for (var i = 0; i < dcCount; i++) { - var _b = drawCalls[i], texArray = _b.texArray, type = _b.type, size = _b.size, start = _b.start, blend = _b.blend; - if (curTexArray !== texArray) { - curTexArray = texArray; - this.bindAndClearTexArray(texArray); - } - this.state.blendMode = blend; - stateSystem.set(this.state); - gl.drawElements(type, size, gl.UNSIGNED_SHORT, start * 2); - } - }; - /** Renders the content _now_ and empties the current batch. */ - AbstractBatchRenderer.prototype.flush = function () { - if (this._vertexCount === 0) { - return; - } - this._attributeBuffer = this.getAttributeBuffer(this._vertexCount); - this._indexBuffer = this.getIndexBuffer(this._indexCount); - this._aIndex = 0; - this._iIndex = 0; - this._dcIndex = 0; - this.buildTexturesAndDrawCalls(); - this.updateGeometry(); - this.drawBatches(); - // reset elements buffer for the next flush - this._bufferSize = 0; - this._vertexCount = 0; - this._indexCount = 0; - }; - /** Starts a new sprite batch. */ - AbstractBatchRenderer.prototype.start = function () { - this.renderer.state.set(this.state); - this.renderer.texture.ensureSamplerType(this.MAX_TEXTURES); - this.renderer.shader.bind(this._shader); - if (settings.CAN_UPLOAD_SAME_BUFFER) { - // bind buffer #0, we don't need others - this.renderer.geometry.bind(this._packedGeometries[this._flushId]); - } - }; - /** Stops and flushes the current batch. */ - AbstractBatchRenderer.prototype.stop = function () { - this.flush(); - }; - /** Destroys this `AbstractBatchRenderer`. It cannot be used again. */ - AbstractBatchRenderer.prototype.destroy = function () { - for (var i = 0; i < this._packedGeometryPoolSize; i++) { - if (this._packedGeometries[i]) { - this._packedGeometries[i].destroy(); - } - } - this.renderer.off('prerender', this.onPrerender, this); - this._aBuffers = null; - this._iBuffers = null; - this._packedGeometries = null; - this._attributeBuffer = null; - this._indexBuffer = null; - if (this._shader) { - this._shader.destroy(); - this._shader = null; - } - _super.prototype.destroy.call(this); - }; - /** - * Fetches an attribute buffer from `this._aBuffers` that can hold atleast `size` floats. - * @param size - minimum capacity required - * @returns - buffer than can hold atleast `size` floats - */ - AbstractBatchRenderer.prototype.getAttributeBuffer = function (size) { - // 8 vertices is enough for 2 quads - var roundedP2 = nextPow2(Math.ceil(size / 8)); - var roundedSizeIndex = log2(roundedP2); - var roundedSize = roundedP2 * 8; - if (this._aBuffers.length <= roundedSizeIndex) { - this._iBuffers.length = roundedSizeIndex + 1; - } - var buffer = this._aBuffers[roundedSize]; - if (!buffer) { - this._aBuffers[roundedSize] = buffer = new ViewableBuffer(roundedSize * this.vertexSize * 4); - } - return buffer; - }; - /** - * Fetches an index buffer from `this._iBuffers` that can - * have at least `size` capacity. - * @param size - minimum required capacity - * @returns - buffer that can fit `size` indices. - */ - AbstractBatchRenderer.prototype.getIndexBuffer = function (size) { - // 12 indices is enough for 2 quads - var roundedP2 = nextPow2(Math.ceil(size / 12)); - var roundedSizeIndex = log2(roundedP2); - var roundedSize = roundedP2 * 12; - if (this._iBuffers.length <= roundedSizeIndex) { - this._iBuffers.length = roundedSizeIndex + 1; - } - var buffer = this._iBuffers[roundedSizeIndex]; - if (!buffer) { - this._iBuffers[roundedSizeIndex] = buffer = new Uint16Array(roundedSize); - } - return buffer; - }; - /** - * Takes the four batching parameters of `element`, interleaves - * and pushes them into the batching attribute/index buffers given. - * - * It uses these properties: `vertexData` `uvs`, `textureId` and - * `indicies`. It also uses the "tint" of the base-texture, if - * present. - * @param {PIXI.DisplayObject} element - element being rendered - * @param attributeBuffer - attribute buffer. - * @param indexBuffer - index buffer - * @param aIndex - number of floats already in the attribute buffer - * @param iIndex - number of indices already in `indexBuffer` - */ - AbstractBatchRenderer.prototype.packInterleavedGeometry = function (element, attributeBuffer, indexBuffer, aIndex, iIndex) { - var uint32View = attributeBuffer.uint32View, float32View = attributeBuffer.float32View; - var packedVertices = aIndex / this.vertexSize; - var uvs = element.uvs; - var indicies = element.indices; - var vertexData = element.vertexData; - var textureId = element._texture.baseTexture._batchLocation; - var alpha = Math.min(element.worldAlpha, 1.0); - var argb = (alpha < 1.0 - && element._texture.baseTexture.alphaMode) - ? premultiplyTint(element._tintRGB, alpha) - : element._tintRGB + (alpha * 255 << 24); - // lets not worry about tint! for now.. - for (var i = 0; i < vertexData.length; i += 2) { - float32View[aIndex++] = vertexData[i]; - float32View[aIndex++] = vertexData[i + 1]; - float32View[aIndex++] = uvs[i]; - float32View[aIndex++] = uvs[i + 1]; - uint32View[aIndex++] = argb; - float32View[aIndex++] = textureId; - } - for (var i = 0; i < indicies.length; i++) { - indexBuffer[iIndex++] = packedVertices + indicies[i]; - } - }; - /** - * Pool of `BatchDrawCall` objects that `flush` used - * to create "batches" of the objects being rendered. - * - * These are never re-allocated again. - * Shared between all batch renderers because it can be only one "flush" working at the moment. - * @member {PIXI.BatchDrawCall[]} - */ - AbstractBatchRenderer._drawCallPool = []; - /** - * Pool of `BatchDrawCall` objects that `flush` used - * to create "batches" of the objects being rendered. - * - * These are never re-allocated again. - * Shared between all batch renderers because it can be only one "flush" working at the moment. - * @member {PIXI.BatchTextureArray[]} - */ - AbstractBatchRenderer._textureArrayPool = []; - return AbstractBatchRenderer; - }(ObjectRenderer)); - - /** - * Helper that generates batching multi-texture shader. Use it with your new BatchRenderer - * @memberof PIXI - */ - var BatchShaderGenerator = /** @class */ (function () { - /** - * @param vertexSrc - Vertex shader - * @param fragTemplate - Fragment shader template - */ - function BatchShaderGenerator(vertexSrc, fragTemplate) { - this.vertexSrc = vertexSrc; - this.fragTemplate = fragTemplate; - this.programCache = {}; - this.defaultGroupCache = {}; - if (fragTemplate.indexOf('%count%') < 0) { - throw new Error('Fragment template must contain "%count%".'); - } - if (fragTemplate.indexOf('%forloop%') < 0) { - throw new Error('Fragment template must contain "%forloop%".'); - } - } - BatchShaderGenerator.prototype.generateShader = function (maxTextures) { - if (!this.programCache[maxTextures]) { - var sampleValues = new Int32Array(maxTextures); - for (var i = 0; i < maxTextures; i++) { - sampleValues[i] = i; - } - this.defaultGroupCache[maxTextures] = UniformGroup.from({ uSamplers: sampleValues }, true); - var fragmentSrc = this.fragTemplate; - fragmentSrc = fragmentSrc.replace(/%count%/gi, "" + maxTextures); - fragmentSrc = fragmentSrc.replace(/%forloop%/gi, this.generateSampleSrc(maxTextures)); - this.programCache[maxTextures] = new Program(this.vertexSrc, fragmentSrc); - } - var uniforms = { - tint: new Float32Array([1, 1, 1, 1]), - translationMatrix: new Matrix(), - default: this.defaultGroupCache[maxTextures], - }; - return new Shader(this.programCache[maxTextures], uniforms); - }; - BatchShaderGenerator.prototype.generateSampleSrc = function (maxTextures) { - var src = ''; - src += '\n'; - src += '\n'; - for (var i = 0; i < maxTextures; i++) { - if (i > 0) { - src += '\nelse '; - } - if (i < maxTextures - 1) { - src += "if(vTextureId < " + i + ".5)"; - } - src += '\n{'; - src += "\n\tcolor = texture2D(uSamplers[" + i + "], vTextureCoord);"; - src += '\n}'; - } - src += '\n'; - src += '\n'; - return src; - }; - return BatchShaderGenerator; - }()); - - /** - * Geometry used to batch standard PIXI content (e.g. Mesh, Sprite, Graphics objects). - * @memberof PIXI - */ - var BatchGeometry = /** @class */ (function (_super) { - __extends$i(BatchGeometry, _super); - /** - * @param {boolean} [_static=false] - Optimization flag, where `false` - * is updated every frame, `true` doesn't change frame-to-frame. - */ - function BatchGeometry(_static) { - if (_static === void 0) { _static = false; } - var _this = _super.call(this) || this; - _this._buffer = new Buffer(null, _static, false); - _this._indexBuffer = new Buffer(null, _static, true); - _this.addAttribute('aVertexPosition', _this._buffer, 2, false, exports.TYPES.FLOAT) - .addAttribute('aTextureCoord', _this._buffer, 2, false, exports.TYPES.FLOAT) - .addAttribute('aColor', _this._buffer, 4, true, exports.TYPES.UNSIGNED_BYTE) - .addAttribute('aTextureId', _this._buffer, 1, true, exports.TYPES.FLOAT) - .addIndex(_this._indexBuffer); - return _this; - } - return BatchGeometry; - }(Geometry)); - - var defaultVertex = "precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform vec4 tint;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor * tint;\n}\n"; - - var defaultFragment = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\nuniform sampler2D uSamplers[%count%];\n\nvoid main(void){\n vec4 color;\n %forloop%\n gl_FragColor = color * vColor;\n}\n"; - - /** @memberof PIXI */ - var BatchPluginFactory = /** @class */ (function () { - function BatchPluginFactory() { - } - /** - * Create a new BatchRenderer plugin for Renderer. this convenience can provide an easy way - * to extend BatchRenderer with all the necessary pieces. - * @example - * const fragment = ` - * varying vec2 vTextureCoord; - * varying vec4 vColor; - * varying float vTextureId; - * uniform sampler2D uSamplers[%count%]; - * - * void main(void){ - * vec4 color; - * %forloop% - * gl_FragColor = vColor * vec4(color.a - color.rgb, color.a); - * } - * `; - * const InvertBatchRenderer = PIXI.BatchPluginFactory.create({ fragment }); - * PIXI.extensions.add({ - * name: 'invert', - * ref: InvertBatchRenderer, - * type: PIXI.ExtensionType.RendererPlugin, - * }); - * const sprite = new PIXI.Sprite(); - * sprite.pluginName = 'invert'; - * @param {object} [options] - * @param {string} [options.vertex=PIXI.BatchPluginFactory.defaultVertexSrc] - Vertex shader source - * @param {string} [options.fragment=PIXI.BatchPluginFactory.defaultFragmentTemplate] - Fragment shader template - * @param {number} [options.vertexSize=6] - Vertex size - * @param {object} [options.geometryClass=PIXI.BatchGeometry] - * @returns {*} New batch renderer plugin - */ - BatchPluginFactory.create = function (options) { - var _a = Object.assign({ - vertex: defaultVertex, - fragment: defaultFragment, - geometryClass: BatchGeometry, - vertexSize: 6, - }, options), vertex = _a.vertex, fragment = _a.fragment, vertexSize = _a.vertexSize, geometryClass = _a.geometryClass; - return /** @class */ (function (_super) { - __extends$i(BatchPlugin, _super); - function BatchPlugin(renderer) { - var _this = _super.call(this, renderer) || this; - _this.shaderGenerator = new BatchShaderGenerator(vertex, fragment); - _this.geometryClass = geometryClass; - _this.vertexSize = vertexSize; - return _this; - } - return BatchPlugin; - }(AbstractBatchRenderer)); - }; - Object.defineProperty(BatchPluginFactory, "defaultVertexSrc", { - /** - * The default vertex shader source - * @readonly - */ - get: function () { - return defaultVertex; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BatchPluginFactory, "defaultFragmentTemplate", { - /** - * The default fragment shader source - * @readonly - */ - get: function () { - return defaultFragment; - }, - enumerable: false, - configurable: true - }); - return BatchPluginFactory; - }()); - // Setup the default BatchRenderer plugin, this is what - // we'll actually export at the root level - var BatchRenderer = BatchPluginFactory.create(); - Object.assign(BatchRenderer, { - extension: { - name: 'batch', - type: exports.ExtensionType.RendererPlugin, - }, - }); - - /** - * @memberof PIXI - * @namespace resources - * @see PIXI - * @deprecated since 6.0.0 - */ - var resources = {}; - var _loop_1 = function (name) { - Object.defineProperty(resources, name, { - get: function () { - deprecation('6.0.0', "PIXI.systems." + name + " has moved to PIXI." + name); - return _resources[name]; - }, - }); - }; - for (var name in _resources) { - _loop_1(name); - } - /** - * @memberof PIXI - * @namespace systems - * @see PIXI - * @deprecated since 6.0.0 - */ - var systems = {}; - var _loop_2 = function (name) { - Object.defineProperty(systems, name, { - get: function () { - deprecation('6.0.0', "PIXI.resources." + name + " has moved to PIXI." + name); - return _systems[name]; - }, - }); - }; - for (var name in _systems) { - _loop_2(name); - } - - /** - * @namespace PIXI - */ - /** - * String of the current PIXI version. - * @memberof PIXI - */ - var VERSION = '6.5.10'; - - /*! - * @pixi/accessibility - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/accessibility is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Default property values of accessible objects - * used by {@link PIXI.AccessibilityManager}. - * @private - * @function accessibleTarget - * @memberof PIXI - * @type {object} - * @example - * function MyObject() {} - * - * Object.assign( - * MyObject.prototype, - * PIXI.accessibleTarget - * ); - */ - var accessibleTarget = { - /** - * Flag for if the object is accessible. If true AccessibilityManager will overlay a - * shadow div with attributes set - * @member {boolean} - * @memberof PIXI.DisplayObject# - */ - accessible: false, - /** - * Sets the title attribute of the shadow div - * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' - * @member {?string} - * @memberof PIXI.DisplayObject# - */ - accessibleTitle: null, - /** - * Sets the aria-label attribute of the shadow div - * @member {string} - * @memberof PIXI.DisplayObject# - */ - accessibleHint: null, - /** - * @member {number} - * @memberof PIXI.DisplayObject# - * @private - * @todo Needs docs. - */ - tabIndex: 0, - /** - * @member {boolean} - * @memberof PIXI.DisplayObject# - * @todo Needs docs. - */ - _accessibleActive: false, - /** - * @member {boolean} - * @memberof PIXI.DisplayObject# - * @todo Needs docs. - */ - _accessibleDiv: null, - /** - * Specify the type of div the accessible layer is. Screen readers treat the element differently - * depending on this type. Defaults to button. - * @member {string} - * @memberof PIXI.DisplayObject# - * @default 'button' - */ - accessibleType: 'button', - /** - * Specify the pointer-events the accessible div will use - * Defaults to auto. - * @member {string} - * @memberof PIXI.DisplayObject# - * @default 'auto' - */ - accessiblePointerEvents: 'auto', - /** - * Setting to false will prevent any children inside this container to - * be accessible. Defaults to true. - * @member {boolean} - * @memberof PIXI.DisplayObject# - * @default true - */ - accessibleChildren: true, - renderId: -1, - }; - - // add some extra variables to the container.. - DisplayObject.mixin(accessibleTarget); - var KEY_CODE_TAB = 9; - var DIV_TOUCH_SIZE = 100; - var DIV_TOUCH_POS_X = 0; - var DIV_TOUCH_POS_Y = 0; - var DIV_TOUCH_ZINDEX = 2; - var DIV_HOOK_SIZE = 1; - var DIV_HOOK_POS_X = -1000; - var DIV_HOOK_POS_Y = -1000; - var DIV_HOOK_ZINDEX = 2; - /** - * The Accessibility manager recreates the ability to tab and have content read by screen readers. - * This is very important as it can possibly help people with disabilities access PixiJS content. - * - * A DisplayObject can be made accessible just like it can be made interactive. This manager will map the - * events as if the mouse was being used, minimizing the effort required to implement. - * - * An instance of this class is automatically created by default, and can be found at `renderer.plugins.accessibility` - * @class - * @memberof PIXI - */ - var AccessibilityManager = /** @class */ (function () { - /** - * @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer - */ - function AccessibilityManager(renderer) { - /** Setting this to true will visually show the divs. */ - this.debug = false; - /** Internal variable, see isActive getter. */ - this._isActive = false; - /** Internal variable, see isMobileAccessibility getter. */ - this._isMobileAccessibility = false; - /** A simple pool for storing divs. */ - this.pool = []; - /** This is a tick used to check if an object is no longer being rendered. */ - this.renderId = 0; - /** The array of currently active accessible items. */ - this.children = []; - /** Count to throttle div updates on android devices. */ - this.androidUpdateCount = 0; - /** The frequency to update the div elements. */ - this.androidUpdateFrequency = 500; // 2fps - this._hookDiv = null; - if (isMobile.tablet || isMobile.phone) { - this.createTouchHook(); - } - // first we create a div that will sit over the PixiJS element. This is where the div overlays will go. - var div = document.createElement('div'); - div.style.width = DIV_TOUCH_SIZE + "px"; - div.style.height = DIV_TOUCH_SIZE + "px"; - div.style.position = 'absolute'; - div.style.top = DIV_TOUCH_POS_X + "px"; - div.style.left = DIV_TOUCH_POS_Y + "px"; - div.style.zIndex = DIV_TOUCH_ZINDEX.toString(); - this.div = div; - this.renderer = renderer; - /** - * pre-bind the functions - * @type {Function} - * @private - */ - this._onKeyDown = this._onKeyDown.bind(this); - /** - * pre-bind the functions - * @type {Function} - * @private - */ - this._onMouseMove = this._onMouseMove.bind(this); - // let listen for tab.. once pressed we can fire up and show the accessibility layer - globalThis.addEventListener('keydown', this._onKeyDown, false); - } - Object.defineProperty(AccessibilityManager.prototype, "isActive", { - /** - * Value of `true` if accessibility is currently active and accessibility layers are showing. - * @member {boolean} - * @readonly - */ - get: function () { - return this._isActive; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AccessibilityManager.prototype, "isMobileAccessibility", { - /** - * Value of `true` if accessibility is enabled for touch devices. - * @member {boolean} - * @readonly - */ - get: function () { - return this._isMobileAccessibility; - }, - enumerable: false, - configurable: true - }); - /** - * Creates the touch hooks. - * @private - */ - AccessibilityManager.prototype.createTouchHook = function () { - var _this = this; - var hookDiv = document.createElement('button'); - hookDiv.style.width = DIV_HOOK_SIZE + "px"; - hookDiv.style.height = DIV_HOOK_SIZE + "px"; - hookDiv.style.position = 'absolute'; - hookDiv.style.top = DIV_HOOK_POS_X + "px"; - hookDiv.style.left = DIV_HOOK_POS_Y + "px"; - hookDiv.style.zIndex = DIV_HOOK_ZINDEX.toString(); - hookDiv.style.backgroundColor = '#FF0000'; - hookDiv.title = 'select to enable accessibility for this content'; - hookDiv.addEventListener('focus', function () { - _this._isMobileAccessibility = true; - _this.activate(); - _this.destroyTouchHook(); - }); - document.body.appendChild(hookDiv); - this._hookDiv = hookDiv; - }; - /** - * Destroys the touch hooks. - * @private - */ - AccessibilityManager.prototype.destroyTouchHook = function () { - if (!this._hookDiv) { - return; - } - document.body.removeChild(this._hookDiv); - this._hookDiv = null; - }; - /** - * Activating will cause the Accessibility layer to be shown. - * This is called when a user presses the tab key. - * @private - */ - AccessibilityManager.prototype.activate = function () { - var _a; - if (this._isActive) { - return; - } - this._isActive = true; - globalThis.document.addEventListener('mousemove', this._onMouseMove, true); - globalThis.removeEventListener('keydown', this._onKeyDown, false); - this.renderer.on('postrender', this.update, this); - (_a = this.renderer.view.parentNode) === null || _a === void 0 ? void 0 : _a.appendChild(this.div); - }; - /** - * Deactivating will cause the Accessibility layer to be hidden. - * This is called when a user moves the mouse. - * @private - */ - AccessibilityManager.prototype.deactivate = function () { - var _a; - if (!this._isActive || this._isMobileAccessibility) { - return; - } - this._isActive = false; - globalThis.document.removeEventListener('mousemove', this._onMouseMove, true); - globalThis.addEventListener('keydown', this._onKeyDown, false); - this.renderer.off('postrender', this.update); - (_a = this.div.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this.div); - }; - /** - * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer. - * @private - * @param {PIXI.Container} displayObject - The DisplayObject to check. - */ - AccessibilityManager.prototype.updateAccessibleObjects = function (displayObject) { - if (!displayObject.visible || !displayObject.accessibleChildren) { - return; - } - if (displayObject.accessible && displayObject.interactive) { - if (!displayObject._accessibleActive) { - this.addChild(displayObject); - } - displayObject.renderId = this.renderId; - } - var children = displayObject.children; - if (children) { - for (var i = 0; i < children.length; i++) { - this.updateAccessibleObjects(children[i]); - } - } - }; - /** - * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. - * @private - */ - AccessibilityManager.prototype.update = function () { - /* On Android default web browser, tab order seems to be calculated by position rather than tabIndex, - * moving buttons can cause focus to flicker between two buttons making it hard/impossible to navigate, - * so I am just running update every half a second, seems to fix it. - */ - var now = performance.now(); - if (isMobile.android.device && now < this.androidUpdateCount) { - return; - } - this.androidUpdateCount = now + this.androidUpdateFrequency; - if (!this.renderer.renderingToScreen) { - return; - } - // update children... - if (this.renderer._lastObjectRendered) { - this.updateAccessibleObjects(this.renderer._lastObjectRendered); - } - var _a = this.renderer.view.getBoundingClientRect(), left = _a.left, top = _a.top, width = _a.width, height = _a.height; - var _b = this.renderer, viewWidth = _b.width, viewHeight = _b.height, resolution = _b.resolution; - var sx = (width / viewWidth) * resolution; - var sy = (height / viewHeight) * resolution; - var div = this.div; - div.style.left = left + "px"; - div.style.top = top + "px"; - div.style.width = viewWidth + "px"; - div.style.height = viewHeight + "px"; - for (var i = 0; i < this.children.length; i++) { - var child = this.children[i]; - if (child.renderId !== this.renderId) { - child._accessibleActive = false; - removeItems(this.children, i, 1); - this.div.removeChild(child._accessibleDiv); - this.pool.push(child._accessibleDiv); - child._accessibleDiv = null; - i--; - } - else { - // map div to display.. - div = child._accessibleDiv; - var hitArea = child.hitArea; - var wt = child.worldTransform; - if (child.hitArea) { - div.style.left = (wt.tx + (hitArea.x * wt.a)) * sx + "px"; - div.style.top = (wt.ty + (hitArea.y * wt.d)) * sy + "px"; - div.style.width = hitArea.width * wt.a * sx + "px"; - div.style.height = hitArea.height * wt.d * sy + "px"; - } - else { - hitArea = child.getBounds(); - this.capHitArea(hitArea); - div.style.left = hitArea.x * sx + "px"; - div.style.top = hitArea.y * sy + "px"; - div.style.width = hitArea.width * sx + "px"; - div.style.height = hitArea.height * sy + "px"; - // update button titles and hints if they exist and they've changed - if (div.title !== child.accessibleTitle && child.accessibleTitle !== null) { - div.title = child.accessibleTitle; - } - if (div.getAttribute('aria-label') !== child.accessibleHint - && child.accessibleHint !== null) { - div.setAttribute('aria-label', child.accessibleHint); - } - } - // the title or index may have changed, if so lets update it! - if (child.accessibleTitle !== div.title || child.tabIndex !== div.tabIndex) { - div.title = child.accessibleTitle; - div.tabIndex = child.tabIndex; - if (this.debug) - { this.updateDebugHTML(div); } - } - } - } - // increment the render id.. - this.renderId++; - }; - /** - * private function that will visually add the information to the - * accessability div - * @param {HTMLElement} div - - */ - AccessibilityManager.prototype.updateDebugHTML = function (div) { - div.innerHTML = "type: " + div.type + "
title : " + div.title + "
tabIndex: " + div.tabIndex; - }; - /** - * Adjust the hit area based on the bounds of a display object - * @param {PIXI.Rectangle} hitArea - Bounds of the child - */ - AccessibilityManager.prototype.capHitArea = function (hitArea) { - if (hitArea.x < 0) { - hitArea.width += hitArea.x; - hitArea.x = 0; - } - if (hitArea.y < 0) { - hitArea.height += hitArea.y; - hitArea.y = 0; - } - var _a = this.renderer, viewWidth = _a.width, viewHeight = _a.height; - if (hitArea.x + hitArea.width > viewWidth) { - hitArea.width = viewWidth - hitArea.x; - } - if (hitArea.y + hitArea.height > viewHeight) { - hitArea.height = viewHeight - hitArea.y; - } - }; - /** - * Adds a DisplayObject to the accessibility manager - * @private - * @param {PIXI.DisplayObject} displayObject - The child to make accessible. - */ - AccessibilityManager.prototype.addChild = function (displayObject) { - // this.activate(); - var div = this.pool.pop(); - if (!div) { - div = document.createElement('button'); - div.style.width = DIV_TOUCH_SIZE + "px"; - div.style.height = DIV_TOUCH_SIZE + "px"; - div.style.backgroundColor = this.debug ? 'rgba(255,255,255,0.5)' : 'transparent'; - div.style.position = 'absolute'; - div.style.zIndex = DIV_TOUCH_ZINDEX.toString(); - div.style.borderStyle = 'none'; - // ARIA attributes ensure that button title and hint updates are announced properly - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { - // Chrome doesn't need aria-live to work as intended; in fact it just gets more confused. - div.setAttribute('aria-live', 'off'); - } - else { - div.setAttribute('aria-live', 'polite'); - } - if (navigator.userAgent.match(/rv:.*Gecko\//)) { - // FireFox needs this to announce only the new button name - div.setAttribute('aria-relevant', 'additions'); - } - else { - // required by IE, other browsers don't much care - div.setAttribute('aria-relevant', 'text'); - } - div.addEventListener('click', this._onClick.bind(this)); - div.addEventListener('focus', this._onFocus.bind(this)); - div.addEventListener('focusout', this._onFocusOut.bind(this)); - } - // set pointer events - div.style.pointerEvents = displayObject.accessiblePointerEvents; - // set the type, this defaults to button! - div.type = displayObject.accessibleType; - if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null) { - div.title = displayObject.accessibleTitle; - } - else if (!displayObject.accessibleHint - || displayObject.accessibleHint === null) { - div.title = "displayObject " + displayObject.tabIndex; - } - if (displayObject.accessibleHint - && displayObject.accessibleHint !== null) { - div.setAttribute('aria-label', displayObject.accessibleHint); - } - if (this.debug) - { this.updateDebugHTML(div); } - displayObject._accessibleActive = true; - displayObject._accessibleDiv = div; - div.displayObject = displayObject; - this.children.push(displayObject); - this.div.appendChild(displayObject._accessibleDiv); - displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; - }; - /** - * Maps the div button press to pixi's InteractionManager (click) - * @private - * @param {MouseEvent} e - The click event. - */ - AccessibilityManager.prototype._onClick = function (e) { - var interactionManager = this.renderer.plugins.interaction; - var displayObject = e.target.displayObject; - var eventData = interactionManager.eventData; - interactionManager.dispatchEvent(displayObject, 'click', eventData); - interactionManager.dispatchEvent(displayObject, 'pointertap', eventData); - interactionManager.dispatchEvent(displayObject, 'tap', eventData); - }; - /** - * Maps the div focus events to pixi's InteractionManager (mouseover) - * @private - * @param {FocusEvent} e - The focus event. - */ - AccessibilityManager.prototype._onFocus = function (e) { - if (!e.target.getAttribute('aria-live')) { - e.target.setAttribute('aria-live', 'assertive'); - } - var interactionManager = this.renderer.plugins.interaction; - var displayObject = e.target.displayObject; - var eventData = interactionManager.eventData; - interactionManager.dispatchEvent(displayObject, 'mouseover', eventData); - }; - /** - * Maps the div focus events to pixi's InteractionManager (mouseout) - * @private - * @param {FocusEvent} e - The focusout event. - */ - AccessibilityManager.prototype._onFocusOut = function (e) { - if (!e.target.getAttribute('aria-live')) { - e.target.setAttribute('aria-live', 'polite'); - } - var interactionManager = this.renderer.plugins.interaction; - var displayObject = e.target.displayObject; - var eventData = interactionManager.eventData; - interactionManager.dispatchEvent(displayObject, 'mouseout', eventData); - }; - /** - * Is called when a key is pressed - * @private - * @param {KeyboardEvent} e - The keydown event. - */ - AccessibilityManager.prototype._onKeyDown = function (e) { - if (e.keyCode !== KEY_CODE_TAB) { - return; - } - this.activate(); - }; - /** - * Is called when the mouse moves across the renderer element - * @private - * @param {MouseEvent} e - The mouse event. - */ - AccessibilityManager.prototype._onMouseMove = function (e) { - if (e.movementX === 0 && e.movementY === 0) { - return; - } - this.deactivate(); - }; - /** Destroys the accessibility manager */ - AccessibilityManager.prototype.destroy = function () { - this.destroyTouchHook(); - this.div = null; - globalThis.document.removeEventListener('mousemove', this._onMouseMove, true); - globalThis.removeEventListener('keydown', this._onKeyDown); - this.pool = null; - this.children = null; - this.renderer = null; - }; - /** @ignore */ - AccessibilityManager.extension = { - name: 'accessibility', - type: [ - exports.ExtensionType.RendererPlugin, - exports.ExtensionType.CanvasRendererPlugin ], - }; - return AccessibilityManager; - }()); - - /*! - * @pixi/interaction - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/interaction is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Holds all information related to an Interaction event - * @memberof PIXI - */ - var InteractionData = /** @class */ (function () { - function InteractionData() { - /** - * Pressure applied by the pointing device during the event. A Touch's force property - * will be represented by this value. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure - */ - this.pressure = 0; - /** - * From TouchEvents (not PointerEvents triggered by touches), the rotationAngle of the Touch. - * @see https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle - */ - this.rotationAngle = 0; - /** - * Twist of a stylus pointer. - * @see https://w3c.github.io/pointerevents/#pointerevent-interface - */ - this.twist = 0; - /** - * Barrel pressure on a stylus pointer. - * @see https://w3c.github.io/pointerevents/#pointerevent-interface - */ - this.tangentialPressure = 0; - this.global = new Point(); - this.target = null; - this.originalEvent = null; - this.identifier = null; - this.isPrimary = false; - this.button = 0; - this.buttons = 0; - this.width = 0; - this.height = 0; - this.tiltX = 0; - this.tiltY = 0; - this.pointerType = null; - this.pressure = 0; - this.rotationAngle = 0; - this.twist = 0; - this.tangentialPressure = 0; - } - Object.defineProperty(InteractionData.prototype, "pointerId", { - /** - * The unique identifier of the pointer. It will be the same as `identifier`. - * @readonly - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId - */ - get: function () { - return this.identifier; - }, - enumerable: false, - configurable: true - }); - /** - * This will return the local coordinates of the specified displayObject for this InteractionData - * @param displayObject - The DisplayObject that you would like the local - * coords off - * @param point - A Point object in which to store the value, optional (otherwise - * will create a new point) - * @param globalPos - A Point object containing your custom global coords, optional - * (otherwise will use the current global coords) - * @returns - A point containing the coordinates of the InteractionData position relative - * to the DisplayObject - */ - InteractionData.prototype.getLocalPosition = function (displayObject, point, globalPos) { - return displayObject.worldTransform.applyInverse(globalPos || this.global, point); - }; - /** - * Copies properties from normalized event data. - * @param {Touch|MouseEvent|PointerEvent} event - The normalized event data - */ - InteractionData.prototype.copyEvent = function (event) { - // isPrimary should only change on touchstart/pointerdown, so we don't want to overwrite - // it with "false" on later events when our shim for it on touch events might not be - // accurate - if ('isPrimary' in event && event.isPrimary) { - this.isPrimary = true; - } - this.button = 'button' in event && event.button; - // event.buttons is not available in all browsers (ie. Safari), but it does have a non-standard - // event.which property instead, which conveys the same information. - var buttons = 'buttons' in event && event.buttons; - this.buttons = Number.isInteger(buttons) ? buttons : 'which' in event && event.which; - this.width = 'width' in event && event.width; - this.height = 'height' in event && event.height; - this.tiltX = 'tiltX' in event && event.tiltX; - this.tiltY = 'tiltY' in event && event.tiltY; - this.pointerType = 'pointerType' in event && event.pointerType; - this.pressure = 'pressure' in event && event.pressure; - this.rotationAngle = 'rotationAngle' in event && event.rotationAngle; - this.twist = ('twist' in event && event.twist) || 0; - this.tangentialPressure = ('tangentialPressure' in event && event.tangentialPressure) || 0; - }; - /** Resets the data for pooling. */ - InteractionData.prototype.reset = function () { - // isPrimary is the only property that we really need to reset - everything else is - // guaranteed to be overwritten - this.isPrimary = false; - }; - return InteractionData; - }()); - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$h = function(d, b) { - extendStatics$h = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$h(d, b); - }; - - function __extends$h(d, b) { - extendStatics$h(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** - * Event class that mimics native DOM events. - * @memberof PIXI - */ - var InteractionEvent = /** @class */ (function () { - function InteractionEvent() { - this.stopped = false; - this.stopsPropagatingAt = null; - this.stopPropagationHint = false; - this.target = null; - this.currentTarget = null; - this.type = null; - this.data = null; - } - /** Prevents event from reaching any objects other than the current object. */ - InteractionEvent.prototype.stopPropagation = function () { - this.stopped = true; - this.stopPropagationHint = true; - this.stopsPropagatingAt = this.currentTarget; - }; - /** Resets the event. */ - InteractionEvent.prototype.reset = function () { - this.stopped = false; - this.stopsPropagatingAt = null; - this.stopPropagationHint = false; - this.currentTarget = null; - this.target = null; - }; - return InteractionEvent; - }()); - - /** - * DisplayObjects with the {@link PIXI.interactiveTarget} mixin use this class to track interactions - * @class - * @private - * @memberof PIXI - */ - var InteractionTrackingData = /** @class */ (function () { - /** - * @param {number} pointerId - Unique pointer id of the event - * @private - */ - function InteractionTrackingData(pointerId) { - this._pointerId = pointerId; - this._flags = InteractionTrackingData.FLAGS.NONE; - } - /** - * - * @private - * @param {number} flag - The interaction flag to set - * @param {boolean} yn - Should the flag be set or unset - */ - InteractionTrackingData.prototype._doSet = function (flag, yn) { - if (yn) { - this._flags = this._flags | flag; - } - else { - this._flags = this._flags & (~flag); - } - }; - Object.defineProperty(InteractionTrackingData.prototype, "pointerId", { - /** - * Unique pointer id of the event - * @readonly - * @private - * @member {number} - */ - get: function () { - return this._pointerId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(InteractionTrackingData.prototype, "flags", { - /** - * State of the tracking data, expressed as bit flags - * @private - * @member {number} - */ - get: function () { - return this._flags; - }, - set: function (flags) { - this._flags = flags; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(InteractionTrackingData.prototype, "none", { - /** - * Is the tracked event inactive (not over or down)? - * @private - * @member {number} - */ - get: function () { - return this._flags === InteractionTrackingData.FLAGS.NONE; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(InteractionTrackingData.prototype, "over", { - /** - * Is the tracked event over the DisplayObject? - * @private - * @member {boolean} - */ - get: function () { - return (this._flags & InteractionTrackingData.FLAGS.OVER) !== 0; - }, - set: function (yn) { - this._doSet(InteractionTrackingData.FLAGS.OVER, yn); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(InteractionTrackingData.prototype, "rightDown", { - /** - * Did the right mouse button come down in the DisplayObject? - * @private - * @member {boolean} - */ - get: function () { - return (this._flags & InteractionTrackingData.FLAGS.RIGHT_DOWN) !== 0; - }, - set: function (yn) { - this._doSet(InteractionTrackingData.FLAGS.RIGHT_DOWN, yn); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(InteractionTrackingData.prototype, "leftDown", { - /** - * Did the left mouse button come down in the DisplayObject? - * @private - * @member {boolean} - */ - get: function () { - return (this._flags & InteractionTrackingData.FLAGS.LEFT_DOWN) !== 0; - }, - set: function (yn) { - this._doSet(InteractionTrackingData.FLAGS.LEFT_DOWN, yn); - }, - enumerable: false, - configurable: true - }); - InteractionTrackingData.FLAGS = Object.freeze({ - NONE: 0, - OVER: 1 << 0, - LEFT_DOWN: 1 << 1, - RIGHT_DOWN: 1 << 2, - }); - return InteractionTrackingData; - }()); - - /** - * Strategy how to search through stage tree for interactive objects - * @memberof PIXI - */ - var TreeSearch = /** @class */ (function () { - function TreeSearch() { - this._tempPoint = new Point(); - } - /** - * Recursive implementation for findHit - * @private - * @param interactionEvent - event containing the point that - * is tested for collision - * @param displayObject - the displayObject - * that will be hit test (recursively crawls its children) - * @param func - the function that will be called on each interactive object. The - * interactionEvent, displayObject and hit will be passed to the function - * @param hitTest - this indicates if the objects inside should be hit test against the point - * @param interactive - Whether the displayObject is interactive - * @returns - Returns true if the displayObject hit the point - */ - TreeSearch.prototype.recursiveFindHit = function (interactionEvent, displayObject, func, hitTest, interactive) { - var _a; - if (!displayObject || !displayObject.visible) { - return false; - } - var point = interactionEvent.data.global; - // Took a little while to rework this function correctly! But now it is done and nice and optimized! ^_^ - // - // This function will now loop through all objects and then only hit test the objects it HAS - // to, not all of them. MUCH faster.. - // An object will be hit test if the following is true: - // - // 1: It is interactive. - // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. - // - // As another little optimization once an interactive object has been hit we can carry on - // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests - // A final optimization is that an object is not hit test directly if a child has already been hit. - interactive = displayObject.interactive || interactive; - var hit = false; - var interactiveParent = interactive; - // Flag here can set to false if the event is outside the parents hitArea or mask - var hitTestChildren = true; - // If there is a hitArea, no need to test against anything else if the pointer is not within the hitArea - // There is also no longer a need to hitTest children. - if (displayObject.hitArea) { - if (hitTest) { - displayObject.worldTransform.applyInverse(point, this._tempPoint); - if (!displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { - hitTest = false; - hitTestChildren = false; - } - else { - hit = true; - } - } - interactiveParent = false; - } - // If there is a mask, no need to hitTest against anything else if the pointer is not within the mask. - // We still want to hitTestChildren, however, to ensure a mouseout can still be generated. - // https://github.com/pixijs/pixi.js/issues/5135 - else if (displayObject._mask) { - if (hitTest) { - var maskObject = (displayObject._mask.isMaskData - ? displayObject._mask.maskObject : displayObject._mask); - if (maskObject && !((_a = maskObject.containsPoint) === null || _a === void 0 ? void 0 : _a.call(maskObject, point))) { - hitTest = false; - } - } - } - // ** FREE TIP **! If an object is not interactive or has no buttons in it - // (such as a game scene!) set interactiveChildren to false for that displayObject. - // This will allow PixiJS to completely ignore and bypass checking the displayObjects children. - if (hitTestChildren && displayObject.interactiveChildren && displayObject.children) { - var children = displayObject.children; - for (var i = children.length - 1; i >= 0; i--) { - var child = children[i]; - // time to get recursive.. if this function will return if something is hit.. - var childHit = this.recursiveFindHit(interactionEvent, child, func, hitTest, interactiveParent); - if (childHit) { - // 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 (!child.parent) { - continue; - } - // we no longer need to hit test any more objects in this container as we we - // now know the parent has been hit - interactiveParent = false; - // If the child is interactive , that means that the object hit was actually - // interactive and not just the child of an interactive object. - // This means we no longer need to hit test anything else. We still need to run - // through all objects, but we don't need to perform any hit tests. - if (childHit) { - if (interactionEvent.target) { - hitTest = false; - } - hit = true; - } - } - } - } - // no point running this if the item is not interactive or does not have an interactive parent. - if (interactive) { - // if we are hit testing (as in we have no hit any objects yet) - // We also don't need to worry about hit testing if once of the displayObjects children - // has already been hit - but only if it was interactive, otherwise we need to keep - // looking for an interactive child, just in case we hit one - if (hitTest && !interactionEvent.target) { - // already tested against hitArea if it is defined - if (!displayObject.hitArea && displayObject.containsPoint) { - if (displayObject.containsPoint(point)) { - hit = true; - } - } - } - if (displayObject.interactive) { - if (hit && !interactionEvent.target) { - interactionEvent.target = displayObject; - } - if (func) { - func(interactionEvent, displayObject, !!hit); - } - } - } - return hit; - }; - /** - * This function is provides a neat way of crawling through the scene graph and running a - * specified function on all interactive objects it finds. It will also take care of hit - * testing the interactive objects and passes the hit across in the function. - * @private - * @param interactionEvent - event containing the point that - * is tested for collision - * @param displayObject - the displayObject - * that will be hit test (recursively crawls its children) - * @param func - the function that will be called on each interactive object. The - * interactionEvent, displayObject and hit will be passed to the function - * @param hitTest - this indicates if the objects inside should be hit test against the point - * @returns - Returns true if the displayObject hit the point - */ - TreeSearch.prototype.findHit = function (interactionEvent, displayObject, func, hitTest) { - this.recursiveFindHit(interactionEvent, displayObject, func, hitTest, false); - }; - return TreeSearch; - }()); - - /** - * Interface for classes that represent a hit area. - * - * It is implemented by the following classes: - * - {@link PIXI.Circle} - * - {@link PIXI.Ellipse} - * - {@link PIXI.Polygon} - * - {@link PIXI.RoundedRectangle} - * @interface IHitArea - * @memberof PIXI - */ - /** - * Checks whether the x and y coordinates given are contained within this area - * @method - * @name contains - * @memberof PIXI.IHitArea# - * @param {number} x - The X coordinate of the point to test - * @param {number} y - The Y coordinate of the point to test - * @returns {boolean} Whether the x/y coordinates are within this area - */ - /** - * Default property values of interactive objects - * Used by {@link PIXI.InteractionManager} to automatically give all DisplayObjects these properties - * @private - * @name interactiveTarget - * @type {object} - * @memberof PIXI - * @example - * function MyObject() {} - * - * Object.assign( - * DisplayObject.prototype, - * PIXI.interactiveTarget - * ); - */ - var interactiveTarget = { - interactive: false, - interactiveChildren: true, - hitArea: null, - /** - * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive - * Setting this changes the 'cursor' property to `'pointer'`. - * @example - * const sprite = new PIXI.Sprite(texture); - * sprite.interactive = true; - * sprite.buttonMode = true; - * @member {boolean} - * @memberof PIXI.DisplayObject# - */ - get buttonMode() { - return this.cursor === 'pointer'; - }, - set buttonMode(value) { - if (value) { - this.cursor = 'pointer'; - } - else if (this.cursor === 'pointer') { - this.cursor = null; - } - }, - /** - * This defines what cursor mode is used when the mouse cursor - * is hovered over the displayObject. - * @example - * const sprite = new PIXI.Sprite(texture); - * sprite.interactive = true; - * sprite.cursor = 'wait'; - * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor - * @member {string} - * @memberof PIXI.DisplayObject# - */ - cursor: null, - /** - * Internal set of all active pointers, by identifier - * @member {Map} - * @memberof PIXI.DisplayObject# - * @private - */ - get trackedPointers() { - if (this._trackedPointers === undefined) - { this._trackedPointers = {}; } - return this._trackedPointers; - }, - /** - * Map of all tracked pointers, by identifier. Use trackedPointers to access. - * @private - * @type {Map} - */ - _trackedPointers: undefined, - }; - - // Mix interactiveTarget into DisplayObject.prototype - DisplayObject.mixin(interactiveTarget); - var MOUSE_POINTER_ID = 1; - // helpers for hitTest() - only used inside hitTest() - var hitTestEvent = { - target: null, - data: { - global: null, - }, - }; - /** - * The interaction manager deals with mouse, touch and pointer events. - * - * Any DisplayObject can be interactive if its `interactive` property is set to true. - * - * This manager also supports multitouch. - * - * An instance of this class is automatically created by default, and can be found at `renderer.plugins.interaction` - * @memberof PIXI - */ - var InteractionManager = /** @class */ (function (_super) { - __extends$h(InteractionManager, _super); - /** - * @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer - * @param options - The options for the manager. - * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. - * @param {number} [options.interactionFrequency=10] - Maximum frequency (ms) at pointer over/out states will be checked. - * @param {number} [options.useSystemTicker=true] - Whether to add {@link tickerUpdate} to {@link PIXI.Ticker.system}. - */ - function InteractionManager(renderer, options) { - var _this = _super.call(this) || this; - options = options || {}; - _this.renderer = renderer; - _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; - _this.interactionFrequency = options.interactionFrequency || 10; - _this.mouse = new InteractionData(); - _this.mouse.identifier = MOUSE_POINTER_ID; - // setting the mouse to start off far off screen will mean that mouse over does - // not get called before we even move the mouse. - _this.mouse.global.set(-999999); - _this.activeInteractionData = {}; - _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse; - _this.interactionDataPool = []; - _this.eventData = new InteractionEvent(); - _this.interactionDOMElement = null; - _this.moveWhenInside = false; - _this.eventsAdded = false; - _this.tickerAdded = false; - _this.mouseOverRenderer = !('PointerEvent' in globalThis); - _this.supportsTouchEvents = 'ontouchstart' in globalThis; - _this.supportsPointerEvents = !!globalThis.PointerEvent; - // this will make it so that you don't have to call bind all the time - _this.onPointerUp = _this.onPointerUp.bind(_this); - _this.processPointerUp = _this.processPointerUp.bind(_this); - _this.onPointerCancel = _this.onPointerCancel.bind(_this); - _this.processPointerCancel = _this.processPointerCancel.bind(_this); - _this.onPointerDown = _this.onPointerDown.bind(_this); - _this.processPointerDown = _this.processPointerDown.bind(_this); - _this.onPointerMove = _this.onPointerMove.bind(_this); - _this.processPointerMove = _this.processPointerMove.bind(_this); - _this.onPointerOut = _this.onPointerOut.bind(_this); - _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); - _this.onPointerOver = _this.onPointerOver.bind(_this); - _this.cursorStyles = { - default: 'inherit', - pointer: 'pointer', - }; - _this.currentCursorMode = null; - _this.cursor = null; - _this.resolution = 1; - _this.delayedEvents = []; - _this.search = new TreeSearch(); - _this._tempDisplayObject = new TemporaryDisplayObject(); - _this._eventListenerOptions = { capture: true, passive: false }; - /** - * Fired when a pointer device button (usually a mouse left-button) is pressed on the display - * object. - * @event PIXI.InteractionManager#mousedown - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is pressed - * on the display object. - * @event PIXI.InteractionManager#rightdown - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button (usually a mouse left-button) is released over the display - * object. - * @event PIXI.InteractionManager#mouseup - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is released - * over the display object. - * @event PIXI.InteractionManager#rightup - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button (usually a mouse left-button) is pressed and released on - * the display object. - * @event PIXI.InteractionManager#click - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is pressed - * and released on the display object. - * @event PIXI.InteractionManager#rightclick - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button (usually a mouse left-button) is released outside the - * display object that initially registered a - * [mousedown]{@link PIXI.InteractionManager#event:mousedown}. - * @event PIXI.InteractionManager#mouseupoutside - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is released - * outside the display object that initially registered a - * [rightdown]{@link PIXI.InteractionManager#event:rightdown}. - * @event PIXI.InteractionManager#rightupoutside - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device (usually a mouse) is moved while over the display object - * @event PIXI.InteractionManager#mousemove - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device (usually a mouse) is moved onto the display object - * @event PIXI.InteractionManager#mouseover - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device (usually a mouse) is moved off the display object - * @event PIXI.InteractionManager#mouseout - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button is pressed on the display object. - * @event PIXI.InteractionManager#pointerdown - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button is released over the display object. - * Not always fired when some buttons are held down while others are released. In those cases, - * use [mousedown]{@link PIXI.InteractionManager#event:mousedown} and - * [mouseup]{@link PIXI.InteractionManager#event:mouseup} instead. - * @event PIXI.InteractionManager#pointerup - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when the operating system cancels a pointer event - * @event PIXI.InteractionManager#pointercancel - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button is pressed and released on the display object. - * @event PIXI.InteractionManager#pointertap - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button is released outside the display object that initially - * registered a [pointerdown]{@link PIXI.InteractionManager#event:pointerdown}. - * @event PIXI.InteractionManager#pointerupoutside - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device is moved while over the display object - * @event PIXI.InteractionManager#pointermove - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device is moved onto the display object - * @event PIXI.InteractionManager#pointerover - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device is moved off the display object - * @event PIXI.InteractionManager#pointerout - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is placed on the display object. - * @event PIXI.InteractionManager#touchstart - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is removed from the display object. - * @event PIXI.InteractionManager#touchend - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when the operating system cancels a touch - * @event PIXI.InteractionManager#touchcancel - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is placed and removed from the display object. - * @event PIXI.InteractionManager#tap - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is removed outside of the display object that initially - * registered a [touchstart]{@link PIXI.InteractionManager#event:touchstart}. - * @event PIXI.InteractionManager#touchendoutside - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is moved along the display object. - * @event PIXI.InteractionManager#touchmove - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button (usually a mouse left-button) is pressed on the display. - * object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#mousedown - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is pressed - * on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#rightdown - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button (usually a mouse left-button) is released over the display - * object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#mouseup - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is released - * over the display object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#rightup - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button (usually a mouse left-button) is pressed and released on - * the display object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#click - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is pressed - * and released on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#rightclick - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button (usually a mouse left-button) is released outside the - * display object that initially registered a - * [mousedown]{@link PIXI.DisplayObject#event:mousedown}. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#mouseupoutside - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is released - * outside the display object that initially registered a - * [rightdown]{@link PIXI.DisplayObject#event:rightdown}. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#rightupoutside - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device (usually a mouse) is moved while over the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#mousemove - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device (usually a mouse) is moved onto the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#mouseover - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device (usually a mouse) is moved off the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#mouseout - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button is pressed on the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#pointerdown - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button is released over the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#pointerup - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when the operating system cancels a pointer event. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#pointercancel - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button is pressed and released on the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#pointertap - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button is released outside the display object that initially - * registered a [pointerdown]{@link PIXI.DisplayObject#event:pointerdown}. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#pointerupoutside - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device is moved while over the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#pointermove - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device is moved onto the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#pointerover - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device is moved off the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#pointerout - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is placed on the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#touchstart - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is removed from the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#touchend - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when the operating system cancels a touch. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#touchcancel - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is placed and removed from the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#tap - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is removed outside of the display object that initially - * registered a [touchstart]{@link PIXI.DisplayObject#event:touchstart}. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#touchendoutside - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is moved along the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * This comes from the @pixi/interaction package. - * @event PIXI.DisplayObject#touchmove - * @param {PIXI.InteractionEvent} event - Interaction event - */ - _this._useSystemTicker = options.useSystemTicker !== undefined ? options.useSystemTicker : true; - _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); - return _this; - } - Object.defineProperty(InteractionManager.prototype, "useSystemTicker", { - /** - * Should the InteractionManager automatically add {@link tickerUpdate} to {@link PIXI.Ticker.system}. - * @default true - */ - get: function () { - return this._useSystemTicker; - }, - set: function (useSystemTicker) { - this._useSystemTicker = useSystemTicker; - if (useSystemTicker) { - this.addTickerListener(); - } - else { - this.removeTickerListener(); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(InteractionManager.prototype, "lastObjectRendered", { - /** - * Last rendered object or temp object. - * @readonly - * @protected - */ - get: function () { - return this.renderer._lastObjectRendered || this._tempDisplayObject; - }, - enumerable: false, - configurable: true - }); - /** - * Hit tests a point against the display tree, returning the first interactive object that is hit. - * @param globalPoint - A point to hit test with, in global space. - * @param root - The root display object to start from. If omitted, defaults - * to the last rendered root of the associated renderer. - * @returns - The hit display object, if any. - */ - InteractionManager.prototype.hitTest = function (globalPoint, root) { - // clear the target for our hit test - hitTestEvent.target = null; - // assign the global point - hitTestEvent.data.global = globalPoint; - // ensure safety of the root - if (!root) { - root = this.lastObjectRendered; - } - // run the hit test - this.processInteractive(hitTestEvent, root, null, true); - // return our found object - it'll be null if we didn't hit anything - return hitTestEvent.target; - }; - /** - * Sets the DOM element which will receive mouse/touch events. This is useful for when you have - * other DOM elements on top of the renderers Canvas element. With this you'll be bale to delegate - * another DOM element to receive those events. - * @param element - the DOM element which will receive mouse and touch events. - * @param resolution - The resolution / device pixel ratio of the new element (relative to the canvas). - */ - InteractionManager.prototype.setTargetElement = function (element, resolution) { - if (resolution === void 0) { resolution = 1; } - this.removeTickerListener(); - this.removeEvents(); - this.interactionDOMElement = element; - this.resolution = resolution; - this.addEvents(); - this.addTickerListener(); - }; - /** Adds the ticker listener. */ - InteractionManager.prototype.addTickerListener = function () { - if (this.tickerAdded || !this.interactionDOMElement || !this._useSystemTicker) { - return; - } - Ticker.system.add(this.tickerUpdate, this, exports.UPDATE_PRIORITY.INTERACTION); - this.tickerAdded = true; - }; - /** Removes the ticker listener. */ - InteractionManager.prototype.removeTickerListener = function () { - if (!this.tickerAdded) { - return; - } - Ticker.system.remove(this.tickerUpdate, this); - this.tickerAdded = false; - }; - /** Registers all the DOM events. */ - InteractionManager.prototype.addEvents = function () { - if (this.eventsAdded || !this.interactionDOMElement) { - return; - } - var style = this.interactionDOMElement.style; - if (globalThis.navigator.msPointerEnabled) { - style.msContentZooming = 'none'; - style.msTouchAction = 'none'; - } - else if (this.supportsPointerEvents) { - style.touchAction = 'none'; - } - /* - * These events are added first, so that if pointer events are normalized, they are fired - * in the same order as non-normalized events. ie. pointer event 1st, mouse / touch 2nd - */ - if (this.supportsPointerEvents) { - globalThis.document.addEventListener('pointermove', this.onPointerMove, this._eventListenerOptions); - this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, this._eventListenerOptions); - // pointerout is fired in addition to pointerup (for touch events) and pointercancel - // we already handle those, so for the purposes of what we do in onPointerOut, we only - // care about the pointerleave event - this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, this._eventListenerOptions); - this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, this._eventListenerOptions); - globalThis.addEventListener('pointercancel', this.onPointerCancel, this._eventListenerOptions); - globalThis.addEventListener('pointerup', this.onPointerUp, this._eventListenerOptions); - } - else { - globalThis.document.addEventListener('mousemove', this.onPointerMove, this._eventListenerOptions); - this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, this._eventListenerOptions); - this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, this._eventListenerOptions); - this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, this._eventListenerOptions); - globalThis.addEventListener('mouseup', this.onPointerUp, this._eventListenerOptions); - } - // always look directly for touch events so that we can provide original data - // In a future version we should change this to being just a fallback and rely solely on - // PointerEvents whenever available - if (this.supportsTouchEvents) { - this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, this._eventListenerOptions); - this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, this._eventListenerOptions); - this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, this._eventListenerOptions); - this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, this._eventListenerOptions); - } - this.eventsAdded = true; - }; - /** Removes all the DOM events that were previously registered. */ - InteractionManager.prototype.removeEvents = function () { - if (!this.eventsAdded || !this.interactionDOMElement) { - return; - } - var style = this.interactionDOMElement.style; - if (globalThis.navigator.msPointerEnabled) { - style.msContentZooming = ''; - style.msTouchAction = ''; - } - else if (this.supportsPointerEvents) { - style.touchAction = ''; - } - if (this.supportsPointerEvents) { - globalThis.document.removeEventListener('pointermove', this.onPointerMove, this._eventListenerOptions); - this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, this._eventListenerOptions); - this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, this._eventListenerOptions); - this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, this._eventListenerOptions); - globalThis.removeEventListener('pointercancel', this.onPointerCancel, this._eventListenerOptions); - globalThis.removeEventListener('pointerup', this.onPointerUp, this._eventListenerOptions); - } - else { - globalThis.document.removeEventListener('mousemove', this.onPointerMove, this._eventListenerOptions); - this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, this._eventListenerOptions); - this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, this._eventListenerOptions); - this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, this._eventListenerOptions); - globalThis.removeEventListener('mouseup', this.onPointerUp, this._eventListenerOptions); - } - if (this.supportsTouchEvents) { - this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, this._eventListenerOptions); - this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, this._eventListenerOptions); - this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, this._eventListenerOptions); - this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, this._eventListenerOptions); - } - this.interactionDOMElement = null; - this.eventsAdded = false; - }; - /** - * Updates the state of interactive objects if at least {@link interactionFrequency} - * milliseconds have passed since the last invocation. - * - * Invoked by a throttled ticker update from {@link PIXI.Ticker.system}. - * @param deltaTime - time delta since the last call - */ - InteractionManager.prototype.tickerUpdate = function (deltaTime) { - this._deltaTime += deltaTime; - if (this._deltaTime < this.interactionFrequency) { - return; - } - this._deltaTime = 0; - this.update(); - }; - /** Updates the state of interactive objects. */ - InteractionManager.prototype.update = function () { - if (!this.interactionDOMElement) { - return; - } - // if the user move the mouse this check has already been done using the mouse move! - if (this._didMove) { - this._didMove = false; - return; - } - this.cursor = null; - // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, - // but there was a scenario of a display object moving under a static mouse cursor. - // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function - for (var k in this.activeInteractionData) { - // eslint-disable-next-line no-prototype-builtins - if (this.activeInteractionData.hasOwnProperty(k)) { - var interactionData = this.activeInteractionData[k]; - if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData); - this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerOverOut, true); - } - } - } - this.setCursorMode(this.cursor); - }; - /** - * Sets the current cursor mode, handling any callbacks or CSS style changes. - * @param mode - cursor mode, a key from the cursorStyles dictionary - */ - InteractionManager.prototype.setCursorMode = function (mode) { - mode = mode || 'default'; - var applyStyles = true; - // offscreen canvas does not support setting styles, but cursor modes can be functions, - // in order to handle pixi rendered cursors, so we can't bail - if (globalThis.OffscreenCanvas && this.interactionDOMElement instanceof OffscreenCanvas) { - applyStyles = false; - } - // if the mode didn't actually change, bail early - if (this.currentCursorMode === mode) { - return; - } - this.currentCursorMode = mode; - var style = this.cursorStyles[mode]; - // only do things if there is a cursor style for it - if (style) { - switch (typeof style) { - case 'string': - // string styles are handled as cursor CSS - if (applyStyles) { - this.interactionDOMElement.style.cursor = style; - } - break; - case 'function': - // functions are just called, and passed the cursor mode - style(mode); - break; - case 'object': - // if it is an object, assume that it is a dictionary of CSS styles, - // apply it to the interactionDOMElement - if (applyStyles) { - Object.assign(this.interactionDOMElement.style, style); - } - break; - } - } - else if (applyStyles && typeof mode === 'string' && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) { - // if it mode is a string (not a Symbol) and cursorStyles doesn't have any entry - // for the mode, then assume that the dev wants it to be CSS for the cursor. - this.interactionDOMElement.style.cursor = mode; - } - }; - /** - * Dispatches an event on the display object that was interacted with. - * @param displayObject - the display object in question - * @param eventString - the name of the event (e.g, mousedown) - * @param eventData - the event data object - */ - InteractionManager.prototype.dispatchEvent = function (displayObject, eventString, eventData) { - // Even if the event was stopped, at least dispatch any remaining events - // for the same display object. - if (!eventData.stopPropagationHint || displayObject === eventData.stopsPropagatingAt) { - eventData.currentTarget = displayObject; - eventData.type = eventString; - displayObject.emit(eventString, eventData); - if (displayObject[eventString]) { - displayObject[eventString](eventData); - } - } - }; - /** - * Puts a event on a queue to be dispatched later. This is used to guarantee correct - * ordering of over/out events. - * @param displayObject - the display object in question - * @param eventString - the name of the event (e.g, mousedown) - * @param eventData - the event data object - */ - InteractionManager.prototype.delayDispatchEvent = function (displayObject, eventString, eventData) { - this.delayedEvents.push({ displayObject: displayObject, eventString: eventString, eventData: eventData }); - }; - /** - * Maps x and y coords from a DOM object and maps them correctly to the PixiJS view. The - * resulting value is stored in the point. This takes into account the fact that the DOM - * element could be scaled and positioned anywhere on the screen. - * @param point - the point that the result will be stored in - * @param x - the x coord of the position to map - * @param y - the y coord of the position to map - */ - InteractionManager.prototype.mapPositionToPoint = function (point, x, y) { - var rect; - // IE 11 fix - if (!this.interactionDOMElement.parentElement) { - rect = { - x: 0, - y: 0, - width: this.interactionDOMElement.width, - height: this.interactionDOMElement.height, - left: 0, - top: 0 - }; - } - else { - rect = this.interactionDOMElement.getBoundingClientRect(); - } - var resolutionMultiplier = 1.0 / this.resolution; - point.x = ((x - rect.left) * (this.interactionDOMElement.width / rect.width)) * resolutionMultiplier; - point.y = ((y - rect.top) * (this.interactionDOMElement.height / rect.height)) * resolutionMultiplier; - }; - /** - * This function is provides a neat way of crawling through the scene graph and running a - * specified function on all interactive objects it finds. It will also take care of hit - * testing the interactive objects and passes the hit across in the function. - * @protected - * @param interactionEvent - event containing the point that - * is tested for collision - * @param displayObject - the displayObject - * that will be hit test (recursively crawls its children) - * @param func - the function that will be called on each interactive object. The - * interactionEvent, displayObject and hit will be passed to the function - * @param hitTest - indicates whether we want to calculate hits - * or just iterate through all interactive objects - */ - InteractionManager.prototype.processInteractive = function (interactionEvent, displayObject, func, hitTest) { - var hit = this.search.findHit(interactionEvent, displayObject, func, hitTest); - var delayedEvents = this.delayedEvents; - if (!delayedEvents.length) { - return hit; - } - // Reset the propagation hint, because we start deeper in the tree again. - interactionEvent.stopPropagationHint = false; - var delayedLen = delayedEvents.length; - this.delayedEvents = []; - for (var i = 0; i < delayedLen; i++) { - var _a = delayedEvents[i], displayObject_1 = _a.displayObject, eventString = _a.eventString, eventData = _a.eventData; - // When we reach the object we wanted to stop propagating at, - // set the propagation hint. - if (eventData.stopsPropagatingAt === displayObject_1) { - eventData.stopPropagationHint = true; - } - this.dispatchEvent(displayObject_1, eventString, eventData); - } - return hit; - }; - /** - * Is called when the pointer button is pressed down on the renderer element - * @param originalEvent - The DOM event of a pointer button being pressed down - */ - InteractionManager.prototype.onPointerDown = function (originalEvent) { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') - { return; } - var events = this.normalizeToPointerData(originalEvent); - /* - * No need to prevent default on natural pointer events, as there are no side effects - * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, - * so still need to be prevented. - */ - // Guaranteed that there will be at least one event in events, and all events must have the same pointer type - if (this.autoPreventDefault && events[0].isNormalized) { - var cancelable = originalEvent.cancelable || !('cancelable' in originalEvent); - if (cancelable) { - originalEvent.preventDefault(); - } - } - var eventLen = events.length; - for (var i = 0; i < eventLen; i++) { - var event = events[i]; - var interactionData = this.getInteractionDataForPointerId(event); - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); - interactionEvent.data.originalEvent = originalEvent; - this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerDown, true); - this.emit('pointerdown', interactionEvent); - if (event.pointerType === 'touch') { - this.emit('touchstart', interactionEvent); - } - // emit a mouse event for "pen" pointers, the way a browser would emit a fallback event - else if (event.pointerType === 'mouse' || event.pointerType === 'pen') { - var isRightButton = event.button === 2; - this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); - } - } - }; - /** - * Processes the result of the pointer down check and dispatches the event if need be - * @param interactionEvent - The interaction event wrapping the DOM event - * @param displayObject - The display object that was tested - * @param hit - the result of the hit test on the display object - */ - InteractionManager.prototype.processPointerDown = function (interactionEvent, displayObject, hit) { - var data = interactionEvent.data; - var id = interactionEvent.data.identifier; - if (hit) { - if (!displayObject.trackedPointers[id]) { - displayObject.trackedPointers[id] = new InteractionTrackingData(id); - } - this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); - if (data.pointerType === 'touch') { - this.dispatchEvent(displayObject, 'touchstart', interactionEvent); - } - else if (data.pointerType === 'mouse' || data.pointerType === 'pen') { - var isRightButton = data.button === 2; - if (isRightButton) { - displayObject.trackedPointers[id].rightDown = true; - } - else { - displayObject.trackedPointers[id].leftDown = true; - } - this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); - } - } - }; - /** - * Is called when the pointer button is released on the renderer element - * @param originalEvent - The DOM event of a pointer button being released - * @param cancelled - true if the pointer is cancelled - * @param func - Function passed to {@link processInteractive} - */ - InteractionManager.prototype.onPointerComplete = function (originalEvent, cancelled, func) { - var events = this.normalizeToPointerData(originalEvent); - var eventLen = events.length; - // if the event wasn't targeting our canvas, then consider it to be pointerupoutside - // in all cases (unless it was a pointercancel) - var target = originalEvent.target; - // if in shadow DOM use composedPath to access target - if (originalEvent.composedPath && originalEvent.composedPath().length > 0) { - target = originalEvent.composedPath()[0]; - } - var eventAppend = target !== this.interactionDOMElement ? 'outside' : ''; - for (var i = 0; i < eventLen; i++) { - var event = events[i]; - var interactionData = this.getInteractionDataForPointerId(event); - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); - interactionEvent.data.originalEvent = originalEvent; - // perform hit testing for events targeting our canvas or cancel events - this.processInteractive(interactionEvent, this.lastObjectRendered, func, cancelled || !eventAppend); - this.emit(cancelled ? 'pointercancel' : "pointerup" + eventAppend, interactionEvent); - if (event.pointerType === 'mouse' || event.pointerType === 'pen') { - var isRightButton = event.button === 2; - this.emit(isRightButton ? "rightup" + eventAppend : "mouseup" + eventAppend, interactionEvent); - } - else if (event.pointerType === 'touch') { - this.emit(cancelled ? 'touchcancel' : "touchend" + eventAppend, interactionEvent); - this.releaseInteractionDataForPointerId(event.pointerId); - } - } - }; - /** - * Is called when the pointer button is cancelled - * @param event - The DOM event of a pointer button being released - */ - InteractionManager.prototype.onPointerCancel = function (event) { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && event.pointerType === 'touch') - { return; } - this.onPointerComplete(event, true, this.processPointerCancel); - }; - /** - * Processes the result of the pointer cancel check and dispatches the event if need be - * @param interactionEvent - The interaction event wrapping the DOM event - * @param displayObject - The display object that was tested - */ - InteractionManager.prototype.processPointerCancel = function (interactionEvent, displayObject) { - var data = interactionEvent.data; - var id = interactionEvent.data.identifier; - if (displayObject.trackedPointers[id] !== undefined) { - delete displayObject.trackedPointers[id]; - this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); - if (data.pointerType === 'touch') { - this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); - } - } - }; - /** - * Is called when the pointer button is released on the renderer element - * @param event - The DOM event of a pointer button being released - */ - InteractionManager.prototype.onPointerUp = function (event) { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && event.pointerType === 'touch') - { return; } - this.onPointerComplete(event, false, this.processPointerUp); - }; - /** - * Processes the result of the pointer up check and dispatches the event if need be - * @param interactionEvent - The interaction event wrapping the DOM event - * @param displayObject - The display object that was tested - * @param hit - the result of the hit test on the display object - */ - InteractionManager.prototype.processPointerUp = function (interactionEvent, displayObject, hit) { - var data = interactionEvent.data; - var id = interactionEvent.data.identifier; - var trackingData = displayObject.trackedPointers[id]; - var isTouch = data.pointerType === 'touch'; - var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); - // need to track mouse down status in the mouse block so that we can emit - // event in a later block - var isMouseTap = false; - // Mouse only - if (isMouse) { - var isRightButton = data.button === 2; - var flags = InteractionTrackingData.FLAGS; - var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; - var isDown = trackingData !== undefined && (trackingData.flags & test); - if (hit) { - this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); - if (isDown) { - this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); - // because we can confirm that the mousedown happened on this object, flag for later emit of pointertap - isMouseTap = true; - } - } - else if (isDown) { - this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); - } - // update the down state of the tracking data - if (trackingData) { - if (isRightButton) { - trackingData.rightDown = false; - } - else { - trackingData.leftDown = false; - } - } - } - // Pointers and Touches, and Mouse - if (hit) { - this.dispatchEvent(displayObject, 'pointerup', interactionEvent); - if (isTouch) - { this.dispatchEvent(displayObject, 'touchend', interactionEvent); } - if (trackingData) { - // emit pointertap if not a mouse, or if the mouse block decided it was a tap - if (!isMouse || isMouseTap) { - this.dispatchEvent(displayObject, 'pointertap', interactionEvent); - } - if (isTouch) { - this.dispatchEvent(displayObject, 'tap', interactionEvent); - // touches are no longer over (if they ever were) when we get the touchend - // so we should ensure that we don't keep pretending that they are - trackingData.over = false; - } - } - } - else if (trackingData) { - this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); - if (isTouch) - { this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); } - } - // Only remove the tracking data if there is no over/down state still associated with it - if (trackingData && trackingData.none) { - delete displayObject.trackedPointers[id]; - } - }; - /** - * Is called when the pointer moves across the renderer element - * @param originalEvent - The DOM event of a pointer moving - */ - InteractionManager.prototype.onPointerMove = function (originalEvent) { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') - { return; } - var events = this.normalizeToPointerData(originalEvent); - if (events[0].pointerType === 'mouse' || events[0].pointerType === 'pen') { - this._didMove = true; - this.cursor = null; - } - var eventLen = events.length; - for (var i = 0; i < eventLen; i++) { - var event = events[i]; - var interactionData = this.getInteractionDataForPointerId(event); - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); - interactionEvent.data.originalEvent = originalEvent; - this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerMove, true); - this.emit('pointermove', interactionEvent); - if (event.pointerType === 'touch') - { this.emit('touchmove', interactionEvent); } - if (event.pointerType === 'mouse' || event.pointerType === 'pen') - { this.emit('mousemove', interactionEvent); } - } - if (events[0].pointerType === 'mouse') { - this.setCursorMode(this.cursor); - // TODO BUG for parents interactive object (border order issue) - } - }; - /** - * Processes the result of the pointer move check and dispatches the event if need be - * @param interactionEvent - The interaction event wrapping the DOM event - * @param displayObject - The display object that was tested - * @param hit - the result of the hit test on the display object - */ - InteractionManager.prototype.processPointerMove = function (interactionEvent, displayObject, hit) { - var data = interactionEvent.data; - var isTouch = data.pointerType === 'touch'; - var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); - if (isMouse) { - this.processPointerOverOut(interactionEvent, displayObject, hit); - } - if (!this.moveWhenInside || hit) { - this.dispatchEvent(displayObject, 'pointermove', interactionEvent); - if (isTouch) - { this.dispatchEvent(displayObject, 'touchmove', interactionEvent); } - if (isMouse) - { this.dispatchEvent(displayObject, 'mousemove', interactionEvent); } - } - }; - /** - * Is called when the pointer is moved out of the renderer element - * @private - * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out - */ - InteractionManager.prototype.onPointerOut = function (originalEvent) { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') - { return; } - var events = this.normalizeToPointerData(originalEvent); - // Only mouse and pointer can call onPointerOut, so events will always be length 1 - var event = events[0]; - if (event.pointerType === 'mouse') { - this.mouseOverRenderer = false; - this.setCursorMode(null); - } - var interactionData = this.getInteractionDataForPointerId(event); - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); - interactionEvent.data.originalEvent = event; - this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerOverOut, false); - this.emit('pointerout', interactionEvent); - if (event.pointerType === 'mouse' || event.pointerType === 'pen') { - this.emit('mouseout', interactionEvent); - } - else { - // we can get touchleave events after touchend, so we want to make sure we don't - // introduce memory leaks - this.releaseInteractionDataForPointerId(interactionData.identifier); - } - }; - /** - * Processes the result of the pointer over/out check and dispatches the event if need be. - * @param interactionEvent - The interaction event wrapping the DOM event - * @param displayObject - The display object that was tested - * @param hit - the result of the hit test on the display object - */ - InteractionManager.prototype.processPointerOverOut = function (interactionEvent, displayObject, hit) { - var data = interactionEvent.data; - var id = interactionEvent.data.identifier; - var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); - var trackingData = displayObject.trackedPointers[id]; - // if we just moused over the display object, then we need to track that state - if (hit && !trackingData) { - trackingData = displayObject.trackedPointers[id] = new InteractionTrackingData(id); - } - if (trackingData === undefined) - { return; } - if (hit && this.mouseOverRenderer) { - if (!trackingData.over) { - trackingData.over = true; - this.delayDispatchEvent(displayObject, 'pointerover', interactionEvent); - if (isMouse) { - this.delayDispatchEvent(displayObject, 'mouseover', interactionEvent); - } - } - // only change the cursor if it has not already been changed (by something deeper in the - // display tree) - if (isMouse && this.cursor === null) { - this.cursor = displayObject.cursor; - } - } - else if (trackingData.over) { - trackingData.over = false; - this.dispatchEvent(displayObject, 'pointerout', this.eventData); - if (isMouse) { - this.dispatchEvent(displayObject, 'mouseout', interactionEvent); - } - // if there is no mouse down information for the pointer, then it is safe to delete - if (trackingData.none) { - delete displayObject.trackedPointers[id]; - } - } - }; - /** - * Is called when the pointer is moved into the renderer element. - * @param originalEvent - The DOM event of a pointer button being moved into the renderer view. - */ - InteractionManager.prototype.onPointerOver = function (originalEvent) { - if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') - { return; } - var events = this.normalizeToPointerData(originalEvent); - // Only mouse and pointer can call onPointerOver, so events will always be length 1 - var event = events[0]; - var interactionData = this.getInteractionDataForPointerId(event); - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); - interactionEvent.data.originalEvent = event; - if (event.pointerType === 'mouse') { - this.mouseOverRenderer = true; - } - this.emit('pointerover', interactionEvent); - if (event.pointerType === 'mouse' || event.pointerType === 'pen') { - this.emit('mouseover', interactionEvent); - } - }; - /** - * Get InteractionData for a given pointerId. Store that data as well. - * @param event - Normalized pointer event, output from normalizeToPointerData. - * @returns - Interaction data for the given pointer identifier. - */ - InteractionManager.prototype.getInteractionDataForPointerId = function (event) { - var pointerId = event.pointerId; - var interactionData; - if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') { - interactionData = this.mouse; - } - else if (this.activeInteractionData[pointerId]) { - interactionData = this.activeInteractionData[pointerId]; - } - else { - interactionData = this.interactionDataPool.pop() || new InteractionData(); - interactionData.identifier = pointerId; - this.activeInteractionData[pointerId] = interactionData; - } - // copy properties from the event, so that we can make sure that touch/pointer specific - // data is available - interactionData.copyEvent(event); - return interactionData; - }; - /** - * Return unused InteractionData to the pool, for a given pointerId - * @param pointerId - Identifier from a pointer event - */ - InteractionManager.prototype.releaseInteractionDataForPointerId = function (pointerId) { - var interactionData = this.activeInteractionData[pointerId]; - if (interactionData) { - delete this.activeInteractionData[pointerId]; - interactionData.reset(); - this.interactionDataPool.push(interactionData); - } - }; - /** - * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData - * @param interactionEvent - The event to be configured - * @param pointerEvent - The DOM event that will be paired with the InteractionEvent - * @param interactionData - The InteractionData that will be paired - * with the InteractionEvent - * @returns - the interaction event that was passed in - */ - InteractionManager.prototype.configureInteractionEventForDOMEvent = function (interactionEvent, pointerEvent, interactionData) { - interactionEvent.data = interactionData; - this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); - // Not really sure why this is happening, but it's how a previous version handled things - if (pointerEvent.pointerType === 'touch') { - pointerEvent.globalX = interactionData.global.x; - pointerEvent.globalY = interactionData.global.y; - } - interactionData.originalEvent = pointerEvent; - interactionEvent.reset(); - return interactionEvent; - }; - /** - * Ensures that the original event object contains all data that a regular pointer event would have - * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event - * @returns - An array containing a single normalized pointer event, in the case of a pointer - * or mouse event, or a multiple normalized pointer events if there are multiple changed touches - */ - InteractionManager.prototype.normalizeToPointerData = function (event) { - var normalizedEvents = []; - if (this.supportsTouchEvents && event instanceof TouchEvent) { - for (var i = 0, li = event.changedTouches.length; i < li; i++) { - var touch = event.changedTouches[i]; - if (typeof touch.button === 'undefined') - { touch.button = event.touches.length ? 1 : 0; } - if (typeof touch.buttons === 'undefined') - { touch.buttons = event.touches.length ? 1 : 0; } - if (typeof touch.isPrimary === 'undefined') { - touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart'; - } - if (typeof touch.width === 'undefined') - { touch.width = touch.radiusX || 1; } - if (typeof touch.height === 'undefined') - { touch.height = touch.radiusY || 1; } - if (typeof touch.tiltX === 'undefined') - { touch.tiltX = 0; } - if (typeof touch.tiltY === 'undefined') - { touch.tiltY = 0; } - if (typeof touch.pointerType === 'undefined') - { touch.pointerType = 'touch'; } - if (typeof touch.pointerId === 'undefined') - { touch.pointerId = touch.identifier || 0; } - if (typeof touch.pressure === 'undefined') - { touch.pressure = touch.force || 0.5; } - if (typeof touch.twist === 'undefined') - { touch.twist = 0; } - if (typeof touch.tangentialPressure === 'undefined') - { touch.tangentialPressure = 0; } - // TODO: Remove these, as layerX/Y is not a standard, is deprecated, has uneven - // support, and the fill ins are not quite the same - // offsetX/Y might be okay, but is not the same as clientX/Y when the canvas's top - // left is not 0,0 on the page - if (typeof touch.layerX === 'undefined') - { touch.layerX = touch.offsetX = touch.clientX; } - if (typeof touch.layerY === 'undefined') - { touch.layerY = touch.offsetY = touch.clientY; } - // mark the touch as normalized, just so that we know we did it - touch.isNormalized = true; - normalizedEvents.push(touch); - } - } - // apparently PointerEvent subclasses MouseEvent, so yay - else if (!globalThis.MouseEvent - || (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof globalThis.PointerEvent)))) { - var tempEvent = event; - if (typeof tempEvent.isPrimary === 'undefined') - { tempEvent.isPrimary = true; } - if (typeof tempEvent.width === 'undefined') - { tempEvent.width = 1; } - if (typeof tempEvent.height === 'undefined') - { tempEvent.height = 1; } - if (typeof tempEvent.tiltX === 'undefined') - { tempEvent.tiltX = 0; } - if (typeof tempEvent.tiltY === 'undefined') - { tempEvent.tiltY = 0; } - if (typeof tempEvent.pointerType === 'undefined') - { tempEvent.pointerType = 'mouse'; } - if (typeof tempEvent.pointerId === 'undefined') - { tempEvent.pointerId = MOUSE_POINTER_ID; } - if (typeof tempEvent.pressure === 'undefined') - { tempEvent.pressure = 0.5; } - if (typeof tempEvent.twist === 'undefined') - { tempEvent.twist = 0; } - if (typeof tempEvent.tangentialPressure === 'undefined') - { tempEvent.tangentialPressure = 0; } - // mark the mouse event as normalized, just so that we know we did it - tempEvent.isNormalized = true; - normalizedEvents.push(tempEvent); - } - else { - normalizedEvents.push(event); - } - return normalizedEvents; - }; - /** Destroys the interaction manager. */ - InteractionManager.prototype.destroy = function () { - this.removeEvents(); - this.removeTickerListener(); - this.removeAllListeners(); - this.renderer = null; - this.mouse = null; - this.eventData = null; - this.interactionDOMElement = null; - this.onPointerDown = null; - this.processPointerDown = null; - this.onPointerUp = null; - this.processPointerUp = null; - this.onPointerCancel = null; - this.processPointerCancel = null; - this.onPointerMove = null; - this.processPointerMove = null; - this.onPointerOut = null; - this.processPointerOverOut = null; - this.onPointerOver = null; - this.search = null; - }; - /** @ignore */ - InteractionManager.extension = { - name: 'interaction', - type: [ - exports.ExtensionType.RendererPlugin, - exports.ExtensionType.CanvasRendererPlugin ], - }; - return InteractionManager; - }(eventemitter3)); - - /*! - * @pixi/extract - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/extract is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - var TEMP_RECT = new Rectangle(); - var BYTES_PER_PIXEL = 4; - /** - * This class provides renderer-specific plugins for exporting content from a renderer. - * For instance, these plugins can be used for saving an Image, Canvas element or for exporting the raw image data (pixels). - * - * Do not instantiate these plugins directly. It is available from the `renderer.plugins` property. - * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. - * @example - * // Create a new app (will auto-add extract plugin to renderer) - * const app = new PIXI.Application(); - * - * // Draw a red circle - * const graphics = new PIXI.Graphics() - * .beginFill(0xFF0000) - * .drawCircle(0, 0, 50); - * - * // Render the graphics as an HTMLImageElement - * const image = app.renderer.plugins.extract.image(graphics); - * document.body.appendChild(image); - * @memberof PIXI - */ - var Extract = /** @class */ (function () { - /** - * @param renderer - A reference to the current renderer - */ - function Extract(renderer) { - this.renderer = renderer; - } - /** - * Will return a HTML Image of the target - * @param target - A displayObject or renderTexture - * to convert. If left empty will use the main renderer - * @param format - Image format, e.g. "image/jpeg" or "image/webp". - * @param quality - JPEG or Webp compression from 0 to 1. Default is 0.92. - * @returns - HTML Image of the target - */ - Extract.prototype.image = function (target, format, quality) { - var image = new Image(); - image.src = this.base64(target, format, quality); - return image; - }; - /** - * Will return a base64 encoded string of this target. It works by calling - * `Extract.getCanvas` and then running toDataURL on that. - * @param target - A displayObject or renderTexture - * to convert. If left empty will use the main renderer - * @param format - Image format, e.g. "image/jpeg" or "image/webp". - * @param quality - JPEG or Webp compression from 0 to 1. Default is 0.92. - * @returns - A base64 encoded string of the texture. - */ - Extract.prototype.base64 = function (target, format, quality) { - return this.canvas(target).toDataURL(format, quality); - }; - /** - * Creates a Canvas element, renders this target to it and then returns it. - * @param target - A displayObject or renderTexture - * to convert. If left empty will use the main renderer - * @param frame - The frame the extraction is restricted to. - * @returns - A Canvas element with the texture rendered on. - */ - Extract.prototype.canvas = function (target, frame) { - var _a = this._rawPixels(target, frame), pixels = _a.pixels, width = _a.width, height = _a.height, flipY = _a.flipY; - var canvasBuffer = new CanvasRenderTarget(width, height, 1); - // Add the pixels to the canvas - var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); - Extract.arrayPostDivide(pixels, canvasData.data); - canvasBuffer.context.putImageData(canvasData, 0, 0); - // Flipping pixels - if (flipY) { - var target_1 = new CanvasRenderTarget(canvasBuffer.width, canvasBuffer.height, 1); - target_1.context.scale(1, -1); - // We can't render to itself because we should be empty before render. - target_1.context.drawImage(canvasBuffer.canvas, 0, -height); - canvasBuffer.destroy(); - canvasBuffer = target_1; - } - // Send the canvas back - return canvasBuffer.canvas; - }; - /** - * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA - * order, with integer values between 0 and 255 (included). - * @param target - A displayObject or renderTexture - * to convert. If left empty will use the main renderer - * @param frame - The frame the extraction is restricted to. - * @returns - One-dimensional array containing the pixel data of the entire texture - */ - Extract.prototype.pixels = function (target, frame) { - var pixels = this._rawPixels(target, frame).pixels; - Extract.arrayPostDivide(pixels, pixels); - return pixels; - }; - Extract.prototype._rawPixels = function (target, frame) { - var renderer = this.renderer; - var resolution; - var flipY = false; - var renderTexture; - var generated = false; - if (target) { - if (target instanceof RenderTexture) { - renderTexture = target; - } - else { - var multisample = renderer.context.webGLVersion >= 2 ? renderer.multisample : exports.MSAA_QUALITY.NONE; - renderTexture = this.renderer.generateTexture(target, { multisample: multisample }); - if (multisample !== exports.MSAA_QUALITY.NONE) { - // Resolve the multisampled texture to a non-multisampled texture - var resolvedTexture = RenderTexture.create({ - width: renderTexture.width, - height: renderTexture.height, - }); - renderer.framebuffer.bind(renderTexture.framebuffer); - renderer.framebuffer.blit(resolvedTexture.framebuffer); - renderer.framebuffer.bind(null); - renderTexture.destroy(true); - renderTexture = resolvedTexture; - } - generated = true; - } - } - if (renderTexture) { - resolution = renderTexture.baseTexture.resolution; - frame = frame !== null && frame !== void 0 ? frame : renderTexture.frame; - flipY = false; - renderer.renderTexture.bind(renderTexture); - } - else { - resolution = renderer.resolution; - if (!frame) { - frame = TEMP_RECT; - frame.width = renderer.width; - frame.height = renderer.height; - } - flipY = true; - renderer.renderTexture.bind(null); - } - var width = Math.round(frame.width * resolution); - var height = Math.round(frame.height * resolution); - var pixels = new Uint8Array(BYTES_PER_PIXEL * width * height); - // Read pixels to the array - var gl = renderer.gl; - gl.readPixels(Math.round(frame.x * resolution), Math.round(frame.y * resolution), width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels); - if (generated) { - renderTexture.destroy(true); - } - return { pixels: pixels, width: width, height: height, flipY: flipY }; - }; - /** Destroys the extract. */ - Extract.prototype.destroy = function () { - this.renderer = null; - }; - /** - * Takes premultiplied pixel data and produces regular pixel data - * @private - * @param pixels - array of pixel data - * @param out - output array - */ - Extract.arrayPostDivide = function (pixels, out) { - for (var i = 0; i < pixels.length; i += 4) { - var alpha = out[i + 3] = pixels[i + 3]; - if (alpha !== 0) { - out[i] = Math.round(Math.min(pixels[i] * 255.0 / alpha, 255.0)); - out[i + 1] = Math.round(Math.min(pixels[i + 1] * 255.0 / alpha, 255.0)); - out[i + 2] = Math.round(Math.min(pixels[i + 2] * 255.0 / alpha, 255.0)); - } - else { - out[i] = pixels[i]; - out[i + 1] = pixels[i + 1]; - out[i + 2] = pixels[i + 2]; - } - } - }; - /** @ignore */ - Extract.extension = { - name: 'extract', - type: exports.ExtensionType.RendererPlugin, - }; - return Extract; - }()); - - /*! - * @pixi/loaders - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/loaders is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /* jshint -W097 */ - /** - * @memberof PIXI - */ - var SignalBinding = /** @class */ (function () { - /** - * SignalBinding constructor. - * @constructs SignalBinding - * @param {Function} fn - Event handler to be called. - * @param {boolean} [once=false] - Should this listener be removed after dispatch - * @param {object} [thisArg] - The context of the callback function. - * @api private - */ - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types - function SignalBinding(fn, once, thisArg) { - if (once === void 0) { once = false; } - this._fn = fn; - this._once = once; - this._thisArg = thisArg; - this._next = this._prev = this._owner = null; - } - SignalBinding.prototype.detach = function () { - if (this._owner === null) - { return false; } - this._owner.detach(this); - return true; - }; - return SignalBinding; - }()); - /** - * @param self - * @param node - * @private - */ - function _addSignalBinding(self, node) { - if (!self._head) { - self._head = node; - self._tail = node; - } - else { - self._tail._next = node; - node._prev = self._tail; - self._tail = node; - } - node._owner = self; - return node; - } - /** - * @memberof PIXI - */ - var Signal = /** @class */ (function () { - /** - * MiniSignal constructor. - * @example - * let mySignal = new Signal(); - * let binding = mySignal.add(onSignal); - * mySignal.dispatch('foo', 'bar'); - * mySignal.detach(binding); - */ - function Signal() { - this._head = this._tail = undefined; - } - /** - * Return an array of attached SignalBinding. - * @param {boolean} [exists=false] - We only need to know if there are handlers. - * @returns {PIXI.SignalBinding[] | boolean} Array of attached SignalBinding or Boolean if called with exists = true - * @api public - */ - Signal.prototype.handlers = function (exists) { - if (exists === void 0) { exists = false; } - var node = this._head; - if (exists) - { return !!node; } - var ee = []; - while (node) { - ee.push(node); - node = node._next; - } - return ee; - }; - /** - * Return true if node is a SignalBinding attached to this MiniSignal - * @param {PIXI.SignalBinding} node - Node to check. - * @returns {boolean} True if node is attache to mini-signal - */ - Signal.prototype.has = function (node) { - if (!(node instanceof SignalBinding)) { - throw new Error('MiniSignal#has(): First arg must be a SignalBinding object.'); - } - return node._owner === this; - }; - /** - * Dispaches a signal to all registered listeners. - * @param {...any} args - * @returns {boolean} Indication if we've emitted an event. - */ - Signal.prototype.dispatch = function () { - var arguments$1 = arguments; - - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments$1[_i]; - } - var node = this._head; - if (!node) - { return false; } - while (node) { - if (node._once) - { this.detach(node); } - node._fn.apply(node._thisArg, args); - node = node._next; - } - return true; - }; - /** - * Register a new listener. - * @param {Function} fn - Callback function. - * @param {object} [thisArg] - The context of the callback function. - * @returns {PIXI.SignalBinding} The SignalBinding node that was added. - */ - Signal.prototype.add = function (fn, thisArg) { - if (thisArg === void 0) { thisArg = null; } - if (typeof fn !== 'function') { - throw new Error('MiniSignal#add(): First arg must be a Function.'); - } - return _addSignalBinding(this, new SignalBinding(fn, false, thisArg)); - }; - /** - * Register a new listener that will be executed only once. - * @param {Function} fn - Callback function. - * @param {object} [thisArg] - The context of the callback function. - * @returns {PIXI.SignalBinding} The SignalBinding node that was added. - */ - Signal.prototype.once = function (fn, thisArg) { - if (thisArg === void 0) { thisArg = null; } - if (typeof fn !== 'function') { - throw new Error('MiniSignal#once(): First arg must be a Function.'); - } - return _addSignalBinding(this, new SignalBinding(fn, true, thisArg)); - }; - /** - * Remove binding object. - * @param {PIXI.SignalBinding} node - The binding node that will be removed. - * @returns {Signal} The instance on which this method was called. - @api public */ - Signal.prototype.detach = function (node) { - if (!(node instanceof SignalBinding)) { - throw new Error('MiniSignal#detach(): First arg must be a SignalBinding object.'); - } - if (node._owner !== this) - { return this; } // todo: or error? - if (node._prev) - { node._prev._next = node._next; } - if (node._next) - { node._next._prev = node._prev; } - if (node === this._head) { // first node - this._head = node._next; - if (node._next === null) { - this._tail = null; - } - } - else if (node === this._tail) { // last node - this._tail = node._prev; - this._tail._next = null; - } - node._owner = null; - return this; - }; - /** - * Detach all listeners. - * @returns {Signal} The instance on which this method was called. - */ - Signal.prototype.detachAll = function () { - var node = this._head; - if (!node) - { return this; } - this._head = this._tail = null; - while (node) { - node._owner = null; - node = node._next; - } - return this; - }; - return Signal; - }()); - - /** - * function from npm package `parseUri`, converted to TS to avoid leftpad incident - * @param {string} str - * @param [opts] - options - * @param {boolean} [opts.strictMode] - type of parser - */ - function parseUri(str, opts) { - opts = opts || {}; - var o = { - // eslint-disable-next-line max-len - key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], - q: { - name: 'queryKey', - parser: /(?:^|&)([^&=]*)=?([^&]*)/g - }, - parser: { - // eslint-disable-next-line max-len - strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, - // eslint-disable-next-line max-len - loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ - } - }; - var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str); - var uri = {}; - var i = 14; - while (i--) - { uri[o.key[i]] = m[i] || ''; } - uri[o.q.name] = {}; - uri[o.key[12]].replace(o.q.parser, function (_t0, t1, t2) { - if (t1) - { uri[o.q.name][t1] = t2; } - }); - return uri; - } - - // tests if CORS is supported in XHR, if not we need to use XDR - var useXdr; - var tempAnchor = null; - // some status constants - var STATUS_NONE = 0; - var STATUS_OK = 200; - var STATUS_EMPTY = 204; - var STATUS_IE_BUG_EMPTY = 1223; - var STATUS_TYPE_OK = 2; - // noop - function _noop$1() { } - /** - * Quick helper to set a value on one of the extension maps. Ensures there is no - * dot at the start of the extension. - * @ignore - * @param map - The map to set on. - * @param extname - The extension (or key) to set. - * @param val - The value to set. - */ - function setExtMap(map, extname, val) { - if (extname && extname.indexOf('.') === 0) { - extname = extname.substring(1); - } - if (!extname) { - return; - } - map[extname] = val; - } - /** - * Quick helper to get string xhr type. - * @ignore - * @param xhr - The request to check. - * @returns The type. - */ - function reqType(xhr) { - return xhr.toString().replace('object ', ''); - } - /** - * Manages the state and loading of a resource and all child resources. - * - * Can be extended in `GlobalMixins.LoaderResource`. - * @memberof PIXI - */ - exports.LoaderResource = /** @class */ (function () { - /** - * @param {string} name - The name of the resource to load. - * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass - * an array of sources. - * @param {object} [options] - The options for the load. - * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to - * determine automatically. - * @param {number} [options.timeout=0] - A timeout in milliseconds for the load. If the load takes - * longer than this time it is cancelled and the load is considered a failure. If this value is - * set to `0` then there is no explicit timeout. - * @param {PIXI.LoaderResource.LOAD_TYPE} [options.loadType=LOAD_TYPE.XHR] - How should this resource - * be loaded? - * @param {PIXI.LoaderResource.XHR_RESPONSE_TYPE} [options.xhrType=XHR_RESPONSE_TYPE.DEFAULT] - How - * should the data being loaded be interpreted when using XHR? - * @param {PIXI.LoaderResource.IMetadata} [options.metadata] - Extra configuration for middleware - * and the Resource object. - */ - function LoaderResource(name, url, options) { - /** - * The `dequeue` method that will be used a storage place for the async queue dequeue method - * used privately by the loader. - * @private - * @member {Function} - */ - this._dequeue = _noop$1; - /** - * Used a storage place for the on load binding used privately by the loader. - * @private - * @member {Function} - */ - this._onLoadBinding = null; - /** - * The timer for element loads to check if they timeout. - * @private - */ - this._elementTimer = 0; - /** - * The `complete` function bound to this resource's context. - * @private - * @type {Function} - */ - this._boundComplete = null; - /** - * The `_onError` function bound to this resource's context. - * @private - * @type {Function} - */ - this._boundOnError = null; - /** - * The `_onProgress` function bound to this resource's context. - * @private - * @type {Function} - */ - this._boundOnProgress = null; - /** - * The `_onTimeout` function bound to this resource's context. - * @private - * @type {Function} - */ - this._boundOnTimeout = null; - this._boundXhrOnError = null; - this._boundXhrOnTimeout = null; - this._boundXhrOnAbort = null; - this._boundXhrOnLoad = null; - if (typeof name !== 'string' || typeof url !== 'string') { - throw new Error('Both name and url are required for constructing a resource.'); - } - options = options || {}; - this._flags = 0; - // set data url flag, needs to be set early for some _determineX checks to work. - this._setFlag(LoaderResource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0); - this.name = name; - this.url = url; - this.extension = this._getExtension(); - this.data = null; - this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; - this.timeout = options.timeout || 0; - this.loadType = options.loadType || this._determineLoadType(); - // The type used to load the resource via XHR. If unset, determined automatically. - this.xhrType = options.xhrType; - // Extra info for middleware, and controlling specifics about how the resource loads. - // Note that if you pass in a `loadElement`, the Resource class takes ownership of it. - // Meaning it will modify it as it sees fit. - this.metadata = options.metadata || {}; - // The error that occurred while loading (if any). - this.error = null; - // The XHR object that was used to load this resource. This is only set - // when `loadType` is `LoaderResource.LOAD_TYPE.XHR`. - this.xhr = null; - // The child resources this resource owns. - this.children = []; - // The resource type. - this.type = LoaderResource.TYPE.UNKNOWN; - // The progress chunk owned by this resource. - this.progressChunk = 0; - // The `dequeue` method that will be used a storage place for the async queue dequeue method - // used privately by the loader. - this._dequeue = _noop$1; - // Used a storage place for the on load binding used privately by the loader. - this._onLoadBinding = null; - // The timer for element loads to check if they timeout. - this._elementTimer = 0; - this._boundComplete = this.complete.bind(this); - this._boundOnError = this._onError.bind(this); - this._boundOnProgress = this._onProgress.bind(this); - this._boundOnTimeout = this._onTimeout.bind(this); - // xhr callbacks - this._boundXhrOnError = this._xhrOnError.bind(this); - this._boundXhrOnTimeout = this._xhrOnTimeout.bind(this); - this._boundXhrOnAbort = this._xhrOnAbort.bind(this); - this._boundXhrOnLoad = this._xhrOnLoad.bind(this); - // Dispatched when the resource beings to load. - this.onStart = new Signal(); - // Dispatched each time progress of this resource load updates. - // Not all resources types and loader systems can support this event - // so sometimes it may not be available. If the resource - // is being loaded on a modern browser, using XHR, and the remote server - // properly sets Content-Length headers, then this will be available. - this.onProgress = new Signal(); - // Dispatched once this resource has loaded, if there was an error it will - // be in the `error` property. - this.onComplete = new Signal(); - // Dispatched after this resource has had all the *after* middleware run on it. - this.onAfterMiddleware = new Signal(); - } - /** - * Sets the load type to be used for a specific extension. - * @static - * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" - * @param {PIXI.LoaderResource.LOAD_TYPE} loadType - The load type to set it to. - */ - LoaderResource.setExtensionLoadType = function (extname, loadType) { - setExtMap(LoaderResource._loadTypeMap, extname, loadType); - }; - /** - * Sets the load type to be used for a specific extension. - * @static - * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" - * @param {PIXI.LoaderResource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. - */ - LoaderResource.setExtensionXhrType = function (extname, xhrType) { - setExtMap(LoaderResource._xhrTypeMap, extname, xhrType); - }; - Object.defineProperty(LoaderResource.prototype, "isDataUrl", { - /** - * When the resource starts to load. - * @memberof PIXI.LoaderResource - * @callback OnStartSignal - * @param {PIXI.Resource} resource - The resource that the event happened on. - */ - /** - * When the resource reports loading progress. - * @memberof PIXI.LoaderResource - * @callback OnProgressSignal - * @param {PIXI.Resource} resource - The resource that the event happened on. - * @param {number} percentage - The progress of the load in the range [0, 1]. - */ - /** - * When the resource finishes loading. - * @memberof PIXI.LoaderResource - * @callback OnCompleteSignal - * @param {PIXI.Resource} resource - The resource that the event happened on. - */ - /** - * @memberof PIXI.LoaderResource - * @typedef {object} IMetadata - * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The - * element to use for loading, instead of creating one. - * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This - * is useful if you want to pass in a `loadElement` that you already added load sources to. - * @property {string|string[]} [mimeType] - The mime type to use for the source element - * of a video/audio elment. If the urls are an array, you can pass this as an array as well - * where each index is the mime type to use for the corresponding url index. - */ - /** - * Stores whether or not this url is a data url. - * @readonly - * @member {boolean} - */ - get: function () { - return this._hasFlag(LoaderResource.STATUS_FLAGS.DATA_URL); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(LoaderResource.prototype, "isComplete", { - /** - * Describes if this resource has finished loading. Is true when the resource has completely - * loaded. - * @readonly - * @member {boolean} - */ - get: function () { - return this._hasFlag(LoaderResource.STATUS_FLAGS.COMPLETE); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(LoaderResource.prototype, "isLoading", { - /** - * Describes if this resource is currently loading. Is true when the resource starts loading, - * and is false again when complete. - * @readonly - * @member {boolean} - */ - get: function () { - return this._hasFlag(LoaderResource.STATUS_FLAGS.LOADING); - }, - enumerable: false, - configurable: true - }); - /** Marks the resource as complete. */ - LoaderResource.prototype.complete = function () { - this._clearEvents(); - this._finish(); - }; - /** - * Aborts the loading of this resource, with an optional message. - * @param {string} message - The message to use for the error - */ - LoaderResource.prototype.abort = function (message) { - // abort can be called multiple times, ignore subsequent calls. - if (this.error) { - return; - } - // store error - this.error = new Error(message); - // clear events before calling aborts - this._clearEvents(); - // abort the actual loading - if (this.xhr) { - this.xhr.abort(); - } - else if (this.xdr) { - this.xdr.abort(); - } - else if (this.data) { - // single source - if (this.data.src) { - this.data.src = LoaderResource.EMPTY_GIF; - } - // multi-source - else { - while (this.data.firstChild) { - this.data.removeChild(this.data.firstChild); - } - } - } - // done now. - this._finish(); - }; - /** - * Kicks off loading of this resource. This method is asynchronous. - * @param {PIXI.LoaderResource.OnCompleteSignal} [cb] - Optional callback to call once the resource is loaded. - */ - LoaderResource.prototype.load = function (cb) { - var _this = this; - if (this.isLoading) { - return; - } - if (this.isComplete) { - if (cb) { - setTimeout(function () { return cb(_this); }, 1); - } - return; - } - else if (cb) { - this.onComplete.once(cb); - } - this._setFlag(LoaderResource.STATUS_FLAGS.LOADING, true); - this.onStart.dispatch(this); - // if unset, determine the value - if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { - this.crossOrigin = this._determineCrossOrigin(this.url); - } - switch (this.loadType) { - case LoaderResource.LOAD_TYPE.IMAGE: - this.type = LoaderResource.TYPE.IMAGE; - this._loadElement('image'); - break; - case LoaderResource.LOAD_TYPE.AUDIO: - this.type = LoaderResource.TYPE.AUDIO; - this._loadSourceElement('audio'); - break; - case LoaderResource.LOAD_TYPE.VIDEO: - this.type = LoaderResource.TYPE.VIDEO; - this._loadSourceElement('video'); - break; - case LoaderResource.LOAD_TYPE.XHR: - /* falls through */ - default: - if (typeof useXdr === 'undefined') { - useXdr = !!(globalThis.XDomainRequest && !('withCredentials' in (new XMLHttpRequest()))); - } - if (useXdr && this.crossOrigin) { - this._loadXdr(); - } - else { - this._loadXhr(); - } - break; - } - }; - /** - * Checks if the flag is set. - * @param flag - The flag to check. - * @returns True if the flag is set. - */ - LoaderResource.prototype._hasFlag = function (flag) { - return (this._flags & flag) !== 0; - }; - /** - * (Un)Sets the flag. - * @param flag - The flag to (un)set. - * @param value - Whether to set or (un)set the flag. - */ - LoaderResource.prototype._setFlag = function (flag, value) { - this._flags = value ? (this._flags | flag) : (this._flags & ~flag); - }; - /** Clears all the events from the underlying loading source. */ - LoaderResource.prototype._clearEvents = function () { - clearTimeout(this._elementTimer); - if (this.data && this.data.removeEventListener) { - this.data.removeEventListener('error', this._boundOnError, false); - this.data.removeEventListener('load', this._boundComplete, false); - this.data.removeEventListener('progress', this._boundOnProgress, false); - this.data.removeEventListener('canplaythrough', this._boundComplete, false); - } - if (this.xhr) { - if (this.xhr.removeEventListener) { - this.xhr.removeEventListener('error', this._boundXhrOnError, false); - this.xhr.removeEventListener('timeout', this._boundXhrOnTimeout, false); - this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); - this.xhr.removeEventListener('progress', this._boundOnProgress, false); - this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); - } - else { - this.xhr.onerror = null; - this.xhr.ontimeout = null; - this.xhr.onprogress = null; - this.xhr.onload = null; - } - } - }; - /** Finalizes the load. */ - LoaderResource.prototype._finish = function () { - if (this.isComplete) { - throw new Error('Complete called again for an already completed resource.'); - } - this._setFlag(LoaderResource.STATUS_FLAGS.COMPLETE, true); - this._setFlag(LoaderResource.STATUS_FLAGS.LOADING, false); - this.onComplete.dispatch(this); - }; - /** - * Loads this resources using an element that has a single source, - * like an HTMLImageElement. - * @private - * @param type - The type of element to use. - */ - LoaderResource.prototype._loadElement = function (type) { - if (this.metadata.loadElement) { - this.data = this.metadata.loadElement; - } - else if (type === 'image' && typeof globalThis.Image !== 'undefined') { - this.data = new Image(); - } - else { - this.data = document.createElement(type); - } - if (this.crossOrigin) { - this.data.crossOrigin = this.crossOrigin; - } - if (!this.metadata.skipSource) { - this.data.src = this.url; - } - this.data.addEventListener('error', this._boundOnError, false); - this.data.addEventListener('load', this._boundComplete, false); - this.data.addEventListener('progress', this._boundOnProgress, false); - if (this.timeout) { - this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout); - } - }; - /** - * Loads this resources using an element that has multiple sources, - * like an HTMLAudioElement or HTMLVideoElement. - * @param type - The type of element to use. - */ - LoaderResource.prototype._loadSourceElement = function (type) { - if (this.metadata.loadElement) { - this.data = this.metadata.loadElement; - } - else if (type === 'audio' && typeof globalThis.Audio !== 'undefined') { - this.data = new Audio(); - } - else { - this.data = document.createElement(type); - } - if (this.data === null) { - this.abort("Unsupported element: " + type); - return; - } - if (this.crossOrigin) { - this.data.crossOrigin = this.crossOrigin; - } - if (!this.metadata.skipSource) { - // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') - if (navigator.isCocoonJS) { - this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; - } - else if (Array.isArray(this.url)) { - var mimeTypes = this.metadata.mimeType; - for (var i = 0; i < this.url.length; ++i) { - this.data.appendChild(this._createSource(type, this.url[i], Array.isArray(mimeTypes) ? mimeTypes[i] : mimeTypes)); - } - } - else { - var mimeTypes = this.metadata.mimeType; - this.data.appendChild(this._createSource(type, this.url, Array.isArray(mimeTypes) ? mimeTypes[0] : mimeTypes)); - } - } - this.data.addEventListener('error', this._boundOnError, false); - this.data.addEventListener('load', this._boundComplete, false); - this.data.addEventListener('progress', this._boundOnProgress, false); - this.data.addEventListener('canplaythrough', this._boundComplete, false); - this.data.load(); - if (this.timeout) { - this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout); - } - }; - /** Loads this resources using an XMLHttpRequest. */ - LoaderResource.prototype._loadXhr = function () { - // if unset, determine the value - if (typeof this.xhrType !== 'string') { - this.xhrType = this._determineXhrType(); - } - var xhr = this.xhr = new XMLHttpRequest(); - // send credentials when crossOrigin with credentials requested - if (this.crossOrigin === 'use-credentials') { - xhr.withCredentials = true; - } - // set the request type and url - xhr.open('GET', this.url, true); - xhr.timeout = this.timeout; - // load json as text and parse it ourselves. We do this because some browsers - // *cough* safari *cough* can't deal with it. - if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.JSON - || this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT) { - xhr.responseType = LoaderResource.XHR_RESPONSE_TYPE.TEXT; - } - else { - xhr.responseType = this.xhrType; - } - xhr.addEventListener('error', this._boundXhrOnError, false); - xhr.addEventListener('timeout', this._boundXhrOnTimeout, false); - xhr.addEventListener('abort', this._boundXhrOnAbort, false); - xhr.addEventListener('progress', this._boundOnProgress, false); - xhr.addEventListener('load', this._boundXhrOnLoad, false); - xhr.send(); - }; - /** Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). */ - LoaderResource.prototype._loadXdr = function () { - // if unset, determine the value - if (typeof this.xhrType !== 'string') { - this.xhrType = this._determineXhrType(); - } - var xdr = this.xhr = new globalThis.XDomainRequest(); // eslint-disable-line no-undef - // XDomainRequest has a few quirks. Occasionally it will abort requests - // A way to avoid this is to make sure ALL callbacks are set even if not used - // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 - xdr.timeout = this.timeout || 5000; // XDR needs a timeout value or it breaks in IE9 - xdr.onerror = this._boundXhrOnError; - xdr.ontimeout = this._boundXhrOnTimeout; - xdr.onprogress = this._boundOnProgress; - xdr.onload = this._boundXhrOnLoad; - xdr.open('GET', this.url, true); - // Note: The xdr.send() call is wrapped in a timeout to prevent an - // issue with the interface where some requests are lost if multiple - // XDomainRequests are being sent at the same time. - // Some info here: https://github.com/photonstorm/phaser/issues/1248 - setTimeout(function () { return xdr.send(); }, 1); - }; - /** - * Creates a source used in loading via an element. - * @param type - The element type (video or audio). - * @param url - The source URL to load from. - * @param [mime] - The mime type of the video - * @returns The source element. - */ - LoaderResource.prototype._createSource = function (type, url, mime) { - if (!mime) { - mime = type + "/" + this._getExtension(url); - } - var source = document.createElement('source'); - source.src = url; - source.type = mime; - return source; - }; - /** - * Called if a load errors out. - * @param event - The error event from the element that emits it. - */ - LoaderResource.prototype._onError = function (event) { - this.abort("Failed to load element using: " + event.target.nodeName); - }; - /** - * Called if a load progress event fires for an element or xhr/xdr. - * @param event - Progress event. - */ - LoaderResource.prototype._onProgress = function (event) { - if (event && event.lengthComputable) { - this.onProgress.dispatch(this, event.loaded / event.total); - } - }; - /** Called if a timeout event fires for an element. */ - LoaderResource.prototype._onTimeout = function () { - this.abort("Load timed out."); - }; - /** Called if an error event fires for xhr/xdr. */ - LoaderResource.prototype._xhrOnError = function () { - var xhr = this.xhr; - this.abort(reqType(xhr) + " Request failed. Status: " + xhr.status + ", text: \"" + xhr.statusText + "\""); - }; - /** Called if an error event fires for xhr/xdr. */ - LoaderResource.prototype._xhrOnTimeout = function () { - var xhr = this.xhr; - this.abort(reqType(xhr) + " Request timed out."); - }; - /** Called if an abort event fires for xhr/xdr. */ - LoaderResource.prototype._xhrOnAbort = function () { - var xhr = this.xhr; - this.abort(reqType(xhr) + " Request was aborted by the user."); - }; - /** Called when data successfully loads from an xhr/xdr request. */ - LoaderResource.prototype._xhrOnLoad = function () { - var xhr = this.xhr; - var text = ''; - var status = typeof xhr.status === 'undefined' ? STATUS_OK : xhr.status; // XDR has no `.status`, assume 200. - // responseText is accessible only if responseType is '' or 'text' and on older browsers - if (xhr.responseType === '' || xhr.responseType === 'text' || typeof xhr.responseType === 'undefined') { - text = xhr.responseText; - } - // status can be 0 when using the `file://` protocol so we also check if a response is set. - // If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request. - if (status === STATUS_NONE && (text.length > 0 || xhr.responseType === LoaderResource.XHR_RESPONSE_TYPE.BUFFER)) { - status = STATUS_OK; - } - // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request - else if (status === STATUS_IE_BUG_EMPTY) { - status = STATUS_EMPTY; - } - var statusType = (status / 100) | 0; - if (statusType === STATUS_TYPE_OK) { - // if text, just return it - if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.TEXT) { - this.data = text; - this.type = LoaderResource.TYPE.TEXT; - } - // if json, parse into json object - else if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.JSON) { - try { - this.data = JSON.parse(text); - this.type = LoaderResource.TYPE.JSON; - } - catch (e) { - this.abort("Error trying to parse loaded json: " + e); - return; - } - } - // if xml, parse into an xml document or div element - else if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT) { - try { - if (globalThis.DOMParser) { - var domparser = new DOMParser(); - this.data = domparser.parseFromString(text, 'text/xml'); - } - else { - var div = document.createElement('div'); - div.innerHTML = text; - this.data = div; - } - this.type = LoaderResource.TYPE.XML; - } - catch (e$1) { - this.abort("Error trying to parse loaded xml: " + e$1); - return; - } - } - // other types just return the response - else { - this.data = xhr.response || text; - } - } - else { - this.abort("[" + xhr.status + "] " + xhr.statusText + ": " + xhr.responseURL); - return; - } - this.complete(); - }; - /** - * Sets the `crossOrigin` property for this resource based on if the url - * for this resource is cross-origin. If crossOrigin was manually set, this - * function does nothing. - * @private - * @param url - The url to test. - * @param [loc=globalThis.location] - The location object to test against. - * @returns The crossOrigin value to use (or empty string for none). - */ - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types - LoaderResource.prototype._determineCrossOrigin = function (url, loc) { - // data: and javascript: urls are considered same-origin - if (url.indexOf('data:') === 0) { - return ''; - } - // A sandboxed iframe without the 'allow-same-origin' attribute will have a special - // origin designed not to match globalThis.location.origin, and will always require - // crossOrigin requests regardless of whether the location matches. - if (globalThis.origin !== globalThis.location.origin) { - return 'anonymous'; - } - // default is globalThis.location - loc = loc || globalThis.location; - if (!tempAnchor) { - tempAnchor = document.createElement('a'); - } - // let the browser determine the full href for the url of this resource and then - // parse with the node url lib, we can't use the properties of the anchor element - // because they don't work in IE9 :( - tempAnchor.href = url; - var parsedUrl = parseUri(tempAnchor.href, { strictMode: true }); - var samePort = (!parsedUrl.port && loc.port === '') || (parsedUrl.port === loc.port); - var protocol = parsedUrl.protocol ? parsedUrl.protocol + ":" : ''; - // if cross origin - if (parsedUrl.host !== loc.hostname || !samePort || protocol !== loc.protocol) { - return 'anonymous'; - } - return ''; - }; - /** - * Determines the responseType of an XHR request based on the extension of the - * resource being loaded. - * @private - * @returns {PIXI.LoaderResource.XHR_RESPONSE_TYPE} The responseType to use. - */ - LoaderResource.prototype._determineXhrType = function () { - return LoaderResource._xhrTypeMap[this.extension] || LoaderResource.XHR_RESPONSE_TYPE.TEXT; - }; - /** - * Determines the loadType of a resource based on the extension of the - * resource being loaded. - * @private - * @returns {PIXI.LoaderResource.LOAD_TYPE} The loadType to use. - */ - LoaderResource.prototype._determineLoadType = function () { - return LoaderResource._loadTypeMap[this.extension] || LoaderResource.LOAD_TYPE.XHR; - }; - /** - * Extracts the extension (sans '.') of the file being loaded by the resource. - * @param [url] - url to parse, `this.url` by default. - * @returns The extension. - */ - LoaderResource.prototype._getExtension = function (url) { - if (url === void 0) { url = this.url; } - var ext = ''; - if (this.isDataUrl) { - var slashIndex = url.indexOf('/'); - ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); - } - else { - var queryStart = url.indexOf('?'); - var hashStart = url.indexOf('#'); - var index = Math.min(queryStart > -1 ? queryStart : url.length, hashStart > -1 ? hashStart : url.length); - url = url.substring(0, index); - ext = url.substring(url.lastIndexOf('.') + 1); - } - return ext.toLowerCase(); - }; - /** - * Determines the mime type of an XHR request based on the responseType of - * resource being loaded. - * @param type - The type to get a mime type for. - * @private - * @returns The mime type to use. - */ - LoaderResource.prototype._getMimeFromXhrType = function (type) { - switch (type) { - case LoaderResource.XHR_RESPONSE_TYPE.BUFFER: - return 'application/octet-binary'; - case LoaderResource.XHR_RESPONSE_TYPE.BLOB: - return 'application/blob'; - case LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT: - return 'application/xml'; - case LoaderResource.XHR_RESPONSE_TYPE.JSON: - return 'application/json'; - case LoaderResource.XHR_RESPONSE_TYPE.DEFAULT: - case LoaderResource.XHR_RESPONSE_TYPE.TEXT: - /* falls through */ - default: - return 'text/plain'; - } - }; - return LoaderResource; - }()); - // eslint-disable-next-line @typescript-eslint/no-namespace - (function (LoaderResource) { - (function (STATUS_FLAGS) { - /** None */ - STATUS_FLAGS[STATUS_FLAGS["NONE"] = 0] = "NONE"; - /** Data URL */ - STATUS_FLAGS[STATUS_FLAGS["DATA_URL"] = 1] = "DATA_URL"; - /** Complete */ - STATUS_FLAGS[STATUS_FLAGS["COMPLETE"] = 2] = "COMPLETE"; - /** Loading */ - STATUS_FLAGS[STATUS_FLAGS["LOADING"] = 4] = "LOADING"; - })(LoaderResource.STATUS_FLAGS || (LoaderResource.STATUS_FLAGS = {})); - (function (TYPE) { - /** Unknown */ - TYPE[TYPE["UNKNOWN"] = 0] = "UNKNOWN"; - /** JSON */ - TYPE[TYPE["JSON"] = 1] = "JSON"; - /** XML */ - TYPE[TYPE["XML"] = 2] = "XML"; - /** Image */ - TYPE[TYPE["IMAGE"] = 3] = "IMAGE"; - /** Audio */ - TYPE[TYPE["AUDIO"] = 4] = "AUDIO"; - /** Video */ - TYPE[TYPE["VIDEO"] = 5] = "VIDEO"; - /** Plain text */ - TYPE[TYPE["TEXT"] = 6] = "TEXT"; - })(LoaderResource.TYPE || (LoaderResource.TYPE = {})); - (function (LOAD_TYPE) { - /** Uses XMLHttpRequest to load the resource. */ - LOAD_TYPE[LOAD_TYPE["XHR"] = 1] = "XHR"; - /** Uses an `Image` object to load the resource. */ - LOAD_TYPE[LOAD_TYPE["IMAGE"] = 2] = "IMAGE"; - /** Uses an `Audio` object to load the resource. */ - LOAD_TYPE[LOAD_TYPE["AUDIO"] = 3] = "AUDIO"; - /** Uses a `Video` object to load the resource. */ - LOAD_TYPE[LOAD_TYPE["VIDEO"] = 4] = "VIDEO"; - })(LoaderResource.LOAD_TYPE || (LoaderResource.LOAD_TYPE = {})); - (function (XHR_RESPONSE_TYPE) { - /** string */ - XHR_RESPONSE_TYPE["DEFAULT"] = "text"; - /** ArrayBuffer */ - XHR_RESPONSE_TYPE["BUFFER"] = "arraybuffer"; - /** Blob */ - XHR_RESPONSE_TYPE["BLOB"] = "blob"; - /** Document */ - XHR_RESPONSE_TYPE["DOCUMENT"] = "document"; - /** Object */ - XHR_RESPONSE_TYPE["JSON"] = "json"; - /** String */ - XHR_RESPONSE_TYPE["TEXT"] = "text"; - })(LoaderResource.XHR_RESPONSE_TYPE || (LoaderResource.XHR_RESPONSE_TYPE = {})); - LoaderResource._loadTypeMap = { - // images - gif: LoaderResource.LOAD_TYPE.IMAGE, - png: LoaderResource.LOAD_TYPE.IMAGE, - bmp: LoaderResource.LOAD_TYPE.IMAGE, - jpg: LoaderResource.LOAD_TYPE.IMAGE, - jpeg: LoaderResource.LOAD_TYPE.IMAGE, - tif: LoaderResource.LOAD_TYPE.IMAGE, - tiff: LoaderResource.LOAD_TYPE.IMAGE, - webp: LoaderResource.LOAD_TYPE.IMAGE, - tga: LoaderResource.LOAD_TYPE.IMAGE, - avif: LoaderResource.LOAD_TYPE.IMAGE, - svg: LoaderResource.LOAD_TYPE.IMAGE, - 'svg+xml': LoaderResource.LOAD_TYPE.IMAGE, - // audio - mp3: LoaderResource.LOAD_TYPE.AUDIO, - ogg: LoaderResource.LOAD_TYPE.AUDIO, - wav: LoaderResource.LOAD_TYPE.AUDIO, - // videos - mp4: LoaderResource.LOAD_TYPE.VIDEO, - webm: LoaderResource.LOAD_TYPE.VIDEO, - }; - LoaderResource._xhrTypeMap = { - // xml - xhtml: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, - html: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, - htm: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, - xml: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, - tmx: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, - svg: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, - // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. - // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, - // this should probably be fine. - tsx: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, - // images - gif: LoaderResource.XHR_RESPONSE_TYPE.BLOB, - png: LoaderResource.XHR_RESPONSE_TYPE.BLOB, - bmp: LoaderResource.XHR_RESPONSE_TYPE.BLOB, - jpg: LoaderResource.XHR_RESPONSE_TYPE.BLOB, - jpeg: LoaderResource.XHR_RESPONSE_TYPE.BLOB, - tif: LoaderResource.XHR_RESPONSE_TYPE.BLOB, - tiff: LoaderResource.XHR_RESPONSE_TYPE.BLOB, - webp: LoaderResource.XHR_RESPONSE_TYPE.BLOB, - tga: LoaderResource.XHR_RESPONSE_TYPE.BLOB, - avif: LoaderResource.XHR_RESPONSE_TYPE.BLOB, - // json - json: LoaderResource.XHR_RESPONSE_TYPE.JSON, - // text - text: LoaderResource.XHR_RESPONSE_TYPE.TEXT, - txt: LoaderResource.XHR_RESPONSE_TYPE.TEXT, - // fonts - ttf: LoaderResource.XHR_RESPONSE_TYPE.BUFFER, - otf: LoaderResource.XHR_RESPONSE_TYPE.BUFFER, - }; - // We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif - LoaderResource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; - })(exports.LoaderResource || (exports.LoaderResource = {})); - - /** - * Smaller version of the async library constructs. - * @ignore - */ - function _noop() { - } - /** - * Ensures a function is only called once. - * @ignore - * @param {Function} fn - The function to wrap. - * @returns {Function} The wrapping function. - */ - function onlyOnce(fn) { - return function onceWrapper() { - var arguments$1 = arguments; - - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments$1[_i]; - } - if (fn === null) { - throw new Error('Callback was already called.'); - } - var callFn = fn; - fn = null; - callFn.apply(this, args); - }; - } - /** - * @private - * @memberof PIXI - */ - var AsyncQueueItem = /** @class */ (function () { - /** - * @param data - * @param callback - * @private - */ - function AsyncQueueItem(data, callback) { - this.data = data; - this.callback = callback; - } - return AsyncQueueItem; - }()); - /** - * @private - * @memberof PIXI - */ - var AsyncQueue = /** @class */ (function () { - /** - * @param worker - * @param concurrency - * @private - */ - function AsyncQueue(worker, concurrency) { - var _this = this; - if (concurrency === void 0) { concurrency = 1; } - this.workers = 0; - this.saturated = _noop; - this.unsaturated = _noop; - this.empty = _noop; - this.drain = _noop; - this.error = _noop; - this.started = false; - this.paused = false; - this._tasks = []; - this._insert = function (data, insertAtFront, callback) { - if (callback && typeof callback !== 'function') { - throw new Error('task callback must be a function'); - } - _this.started = true; - // eslint-disable-next-line no-eq-null,eqeqeq - if (data == null && _this.idle()) { - // call drain immediately if there are no tasks - setTimeout(function () { return _this.drain(); }, 1); - return; - } - var item = new AsyncQueueItem(data, typeof callback === 'function' ? callback : _noop); - if (insertAtFront) { - _this._tasks.unshift(item); - } - else { - _this._tasks.push(item); - } - setTimeout(_this.process, 1); - }; - this.process = function () { - while (!_this.paused && _this.workers < _this.concurrency && _this._tasks.length) { - var task = _this._tasks.shift(); - if (_this._tasks.length === 0) { - _this.empty(); - } - _this.workers += 1; - if (_this.workers === _this.concurrency) { - _this.saturated(); - } - _this._worker(task.data, onlyOnce(_this._next(task))); - } - }; - this._worker = worker; - if (concurrency === 0) { - throw new Error('Concurrency must not be zero'); - } - this.concurrency = concurrency; - this.buffer = concurrency / 4.0; - } - /** - * @param task - * @private - */ - AsyncQueue.prototype._next = function (task) { - var _this = this; - return function () { - var arguments$1 = arguments; - - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments$1[_i]; - } - _this.workers -= 1; - task.callback.apply(task, args); - // eslint-disable-next-line no-eq-null,eqeqeq - if (args[0] != null) { - _this.error(args[0], task.data); - } - if (_this.workers <= (_this.concurrency - _this.buffer)) { - _this.unsaturated(); - } - if (_this.idle()) { - _this.drain(); - } - _this.process(); - }; - }; - // That was in object - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types - AsyncQueue.prototype.push = function (data, callback) { - this._insert(data, false, callback); - }; - AsyncQueue.prototype.kill = function () { - this.workers = 0; - this.drain = _noop; - this.started = false; - this._tasks = []; - }; - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types - AsyncQueue.prototype.unshift = function (data, callback) { - this._insert(data, true, callback); - }; - AsyncQueue.prototype.length = function () { - return this._tasks.length; - }; - AsyncQueue.prototype.running = function () { - return this.workers; - }; - AsyncQueue.prototype.idle = function () { - return this._tasks.length + this.workers === 0; - }; - AsyncQueue.prototype.pause = function () { - if (this.paused === true) { - return; - } - this.paused = true; - }; - AsyncQueue.prototype.resume = function () { - if (this.paused === false) { - return; - } - this.paused = false; - // Need to call this.process once per concurrent - // worker to preserve full concurrency after pause - for (var w = 1; w <= this.concurrency; w++) { - this.process(); - } - }; - /** - * Iterates an array in series. - * @param {Array.<*>} array - Array to iterate. - * @param {Function} iterator - Function to call for each element. - * @param {Function} callback - Function to call when done, or on error. - * @param {boolean} [deferNext=false] - Break synchronous each loop by calling next with a setTimeout of 1. - */ - AsyncQueue.eachSeries = function (array, iterator, callback, deferNext) { - var i = 0; - var len = array.length; - function next(err) { - if (err || i === len) { - if (callback) { - callback(err); - } - return; - } - if (deferNext) { - setTimeout(function () { - iterator(array[i++], next); - }, 1); - } - else { - iterator(array[i++], next); - } - } - next(); - }; - /** - * Async queue implementation, - * @param {Function} worker - The worker function to call for each task. - * @param {number} concurrency - How many workers to run in parrallel. - * @returns {*} The async queue object. - */ - AsyncQueue.queue = function (worker, concurrency) { - return new AsyncQueue(worker, concurrency); - }; - return AsyncQueue; - }()); - - // some constants - var MAX_PROGRESS = 100; - var rgxExtractUrlHash = /(#[\w-]+)?$/; - /** - * The new loader, forked from Resource Loader by Chad Engler: https://github.com/englercj/resource-loader - * - * ```js - * const loader = PIXI.Loader.shared; // PixiJS exposes a premade instance for you to use. - * // or - * const loader = new PIXI.Loader(); // You can also create your own if you want - * - * const sprites = {}; - * - * // Chainable `add` to enqueue a resource - * loader.add('bunny', 'data/bunny.png') - * .add('spaceship', 'assets/spritesheet.json'); - * loader.add('scoreFont', 'assets/score.fnt'); - * - * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource. - * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc). - * loader.pre(cachingMiddleware); - * - * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource. - * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc). - * loader.use(parsingMiddleware); - * - * // The `load` method loads the queue of resources, and calls the passed in callback called once all - * // resources have loaded. - * loader.load((loader, resources) => { - * // resources is an object where the key is the name of the resource loaded and the value is the resource object. - * // They have a couple default properties: - * // - `url`: The URL that the resource was loaded from - * // - `error`: The error that happened when trying to load (if any) - * // - `data`: The raw data that was loaded - * // also may contain other properties based on the middleware that runs. - * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture); - * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture); - * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture); - * }); - * - * // throughout the process multiple signals can be dispatched. - * loader.onProgress.add(() => {}); // called once per loaded/errored file - * loader.onError.add(() => {}); // called once per errored file - * loader.onLoad.add(() => {}); // called once per loaded file - * loader.onComplete.add(() => {}); // called once when the queued resources all load. - * ``` - * @memberof PIXI - */ - var Loader = /** @class */ (function () { - /** - * @param baseUrl - The base url for all resources loaded by this loader. - * @param concurrency - The number of resources to load concurrently. - */ - function Loader(baseUrl, concurrency) { - var _this = this; - if (baseUrl === void 0) { baseUrl = ''; } - if (concurrency === void 0) { concurrency = 10; } - /** The progress percent of the loader going through the queue. */ - this.progress = 0; - /** Loading state of the loader, true if it is currently loading resources. */ - this.loading = false; - /** - * A querystring to append to every URL added to the loader. - * - * This should be a valid query string *without* the question-mark (`?`). The loader will - * also *not* escape values for you. Make sure to escape your parameters with - * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. - * @example - * const loader = new Loader(); - * - * loader.defaultQueryString = 'user=me&password=secret'; - * - * // This will request 'image.png?user=me&password=secret' - * loader.add('image.png').load(); - * - * loader.reset(); - * - * // This will request 'image.png?v=1&user=me&password=secret' - * loader.add('iamge.png?v=1').load(); - */ - this.defaultQueryString = ''; - /** The middleware to run before loading each resource. */ - this._beforeMiddleware = []; - /** The middleware to run after loading each resource. */ - this._afterMiddleware = []; - /** The tracks the resources we are currently completing parsing for. */ - this._resourcesParsing = []; - /** - * The `_loadResource` function bound with this object context. - * @param r - The resource to load - * @param d - The dequeue function - */ - this._boundLoadResource = function (r, d) { return _this._loadResource(r, d); }; - /** All the resources for this loader keyed by name. */ - this.resources = {}; - this.baseUrl = baseUrl; - this._beforeMiddleware = []; - this._afterMiddleware = []; - this._resourcesParsing = []; - this._boundLoadResource = function (r, d) { return _this._loadResource(r, d); }; - this._queue = AsyncQueue.queue(this._boundLoadResource, concurrency); - this._queue.pause(); - this.resources = {}; - this.onProgress = new Signal(); - this.onError = new Signal(); - this.onLoad = new Signal(); - this.onStart = new Signal(); - this.onComplete = new Signal(); - for (var i = 0; i < Loader._plugins.length; ++i) { - var plugin = Loader._plugins[i]; - var pre = plugin.pre, use = plugin.use; - if (pre) { - this.pre(pre); - } - if (use) { - this.use(use); - } - } - this._protected = false; - } - /** - * Same as add, params have strict order - * @private - * @param name - The name of the resource to load. - * @param url - The url for this resource, relative to the baseUrl of this loader. - * @param options - The options for the load. - * @param callback - Function to call when this specific resource completes loading. - * @returns The loader itself. - */ - Loader.prototype._add = function (name, url, options, callback) { - // if loading already you can only add resources that have a parent. - if (this.loading && (!options || !options.parentResource)) { - throw new Error('Cannot add resources while the loader is running.'); - } - // check if resource already exists. - if (this.resources[name]) { - throw new Error("Resource named \"" + name + "\" already exists."); - } - // add base url if this isn't an absolute url - url = this._prepareUrl(url); - // create the store the resource - this.resources[name] = new exports.LoaderResource(name, url, options); - if (typeof callback === 'function') { - this.resources[name].onAfterMiddleware.once(callback); - } - // if actively loading, make sure to adjust progress chunks for that parent and its children - if (this.loading) { - var parent = options.parentResource; - var incompleteChildren = []; - for (var i = 0; i < parent.children.length; ++i) { - if (!parent.children[i].isComplete) { - incompleteChildren.push(parent.children[i]); - } - } - var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent - var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child - parent.children.push(this.resources[name]); - parent.progressChunk = eachChunk; - for (var i = 0; i < incompleteChildren.length; ++i) { - incompleteChildren[i].progressChunk = eachChunk; - } - this.resources[name].progressChunk = eachChunk; - } - // add the resource to the queue - this._queue.push(this.resources[name]); - return this; - }; - /* eslint-enable require-jsdoc,valid-jsdoc */ - /** - * Sets up a middleware function that will run *before* the - * resource is loaded. - * @param fn - The middleware function to register. - * @returns The loader itself. - */ - Loader.prototype.pre = function (fn) { - this._beforeMiddleware.push(fn); - return this; - }; - /** - * Sets up a middleware function that will run *after* the - * resource is loaded. - * @param fn - The middleware function to register. - * @returns The loader itself. - */ - Loader.prototype.use = function (fn) { - this._afterMiddleware.push(fn); - return this; - }; - /** - * Resets the queue of the loader to prepare for a new load. - * @returns The loader itself. - */ - Loader.prototype.reset = function () { - this.progress = 0; - this.loading = false; - this._queue.kill(); - this._queue.pause(); - // abort all resource loads - for (var k in this.resources) { - var res = this.resources[k]; - if (res._onLoadBinding) { - res._onLoadBinding.detach(); - } - if (res.isLoading) { - res.abort('loader reset'); - } - } - this.resources = {}; - return this; - }; - /** - * Starts loading the queued resources. - * @param cb - Optional callback that will be bound to the `complete` event. - * @returns The loader itself. - */ - Loader.prototype.load = function (cb) { - deprecation('6.5.0', '@pixi/loaders is being replaced with @pixi/assets in the next major release.'); - // register complete callback if they pass one - if (typeof cb === 'function') { - this.onComplete.once(cb); - } - // if the queue has already started we are done here - if (this.loading) { - return this; - } - if (this._queue.idle()) { - this._onStart(); - this._onComplete(); - } - else { - // distribute progress chunks - var numTasks = this._queue._tasks.length; - var chunk = MAX_PROGRESS / numTasks; - for (var i = 0; i < this._queue._tasks.length; ++i) { - this._queue._tasks[i].data.progressChunk = chunk; - } - // notify we are starting - this._onStart(); - // start loading - this._queue.resume(); - } - return this; - }; - Object.defineProperty(Loader.prototype, "concurrency", { - /** - * The number of resources to load concurrently. - * @default 10 - */ - get: function () { - return this._queue.concurrency; - }, - set: function (concurrency) { - this._queue.concurrency = concurrency; - }, - enumerable: false, - configurable: true - }); - /** - * Prepares a url for usage based on the configuration of this object - * @param url - The url to prepare. - * @returns The prepared url. - */ - Loader.prototype._prepareUrl = function (url) { - var parsedUrl = parseUri(url, { strictMode: true }); - var result; - // absolute url, just use it as is. - if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) { - result = url; - } - // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween - else if (this.baseUrl.length - && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 - && url.charAt(0) !== '/') { - result = this.baseUrl + "/" + url; - } - else { - result = this.baseUrl + url; - } - // if we need to add a default querystring, there is a bit more work - if (this.defaultQueryString) { - var hash = rgxExtractUrlHash.exec(result)[0]; - result = result.slice(0, result.length - hash.length); - if (result.indexOf('?') !== -1) { - result += "&" + this.defaultQueryString; - } - else { - result += "?" + this.defaultQueryString; - } - result += hash; - } - return result; - }; - /** - * Loads a single resource. - * @param resource - The resource to load. - * @param dequeue - The function to call when we need to dequeue this item. - */ - Loader.prototype._loadResource = function (resource, dequeue) { - var _this = this; - resource._dequeue = dequeue; - // run before middleware - AsyncQueue.eachSeries(this._beforeMiddleware, function (fn, next) { - fn.call(_this, resource, function () { - // if the before middleware marks the resource as complete, - // break and don't process any more before middleware - next(resource.isComplete ? {} : null); - }); - }, function () { - if (resource.isComplete) { - _this._onLoad(resource); - } - else { - resource._onLoadBinding = resource.onComplete.once(_this._onLoad, _this); - resource.load(); - } - }, true); - }; - /** Called once loading has started. */ - Loader.prototype._onStart = function () { - this.progress = 0; - this.loading = true; - this.onStart.dispatch(this); - }; - /** Called once each resource has loaded. */ - Loader.prototype._onComplete = function () { - this.progress = MAX_PROGRESS; - this.loading = false; - this.onComplete.dispatch(this, this.resources); - }; - /** - * Called each time a resources is loaded. - * @param resource - The resource that was loaded - */ - Loader.prototype._onLoad = function (resource) { - var _this = this; - resource._onLoadBinding = null; - // remove this resource from the async queue, and add it to our list of resources that are being parsed - this._resourcesParsing.push(resource); - resource._dequeue(); - // run all the after middleware for this resource - AsyncQueue.eachSeries(this._afterMiddleware, function (fn, next) { - fn.call(_this, resource, next); - }, function () { - resource.onAfterMiddleware.dispatch(resource); - _this.progress = Math.min(MAX_PROGRESS, _this.progress + resource.progressChunk); - _this.onProgress.dispatch(_this, resource); - if (resource.error) { - _this.onError.dispatch(resource.error, _this, resource); - } - else { - _this.onLoad.dispatch(_this, resource); - } - _this._resourcesParsing.splice(_this._resourcesParsing.indexOf(resource), 1); - // do completion check - if (_this._queue.idle() && _this._resourcesParsing.length === 0) { - _this._onComplete(); - } - }, true); - }; - /** Destroy the loader, removes references. */ - Loader.prototype.destroy = function () { - if (!this._protected) { - this.reset(); - } - }; - Object.defineProperty(Loader, "shared", { - /** A premade instance of the loader that can be used to load resources. */ - get: function () { - var shared = Loader._shared; - if (!shared) { - shared = new Loader(); - shared._protected = true; - Loader._shared = shared; - } - return shared; - }, - enumerable: false, - configurable: true - }); - /** - * Use the {@link PIXI.extensions.add} API to register plugins. - * @deprecated since 6.5.0 - * @param plugin - The plugin to add - * @returns Reference to PIXI.Loader for chaining - */ - Loader.registerPlugin = function (plugin) { - deprecation('6.5.0', 'Loader.registerPlugin() is deprecated, use extensions.add() instead.'); - extensions.add({ - type: exports.ExtensionType.Loader, - ref: plugin, - }); - return Loader; - }; - Loader._plugins = []; - return Loader; - }()); - extensions.handleByList(exports.ExtensionType.Loader, Loader._plugins); - Loader.prototype.add = function add(name, url, options, callback) { - // special case of an array of objects or urls - if (Array.isArray(name)) { - for (var i = 0; i < name.length; ++i) { - this.add(name[i]); - } - return this; - } - // if an object is passed instead of params - if (typeof name === 'object') { - options = name; - callback = url || options.callback || options.onComplete; - url = options.url; - name = options.name || options.key || options.url; - } - // case where no name is passed shift all args over by one. - if (typeof url !== 'string') { - callback = options; - options = url; - url = name; - } - // now that we shifted make sure we have a proper url. - if (typeof url !== 'string') { - throw new Error('No url passed to add resource to loader.'); - } - // options are optional so people might pass a function and no options - if (typeof options === 'function') { - callback = options; - options = null; - } - return this._add(name, url, options, callback); - }; - - /** - * Application plugin for supporting loader option. Installing the LoaderPlugin - * is not necessary if using **pixi.js** or **pixi.js-legacy**. - * @example - * import {AppLoaderPlugin} from '@pixi/loaders'; - * import {extensions} from '@pixi/core'; - * extensions.add(AppLoaderPlugin); - * @memberof PIXI - */ - var AppLoaderPlugin = /** @class */ (function () { - function AppLoaderPlugin() { - } - /** - * Called on application constructor - * @param options - * @private - */ - AppLoaderPlugin.init = function (options) { - options = Object.assign({ - sharedLoader: false, - }, options); - this.loader = options.sharedLoader ? Loader.shared : new Loader(); - }; - /** - * Called when application destroyed - * @private - */ - AppLoaderPlugin.destroy = function () { - if (this.loader) { - this.loader.destroy(); - this.loader = null; - } - }; - /** @ignore */ - AppLoaderPlugin.extension = exports.ExtensionType.Application; - return AppLoaderPlugin; - }()); - - /** - * Loader plugin for handling Texture resources. - * @memberof PIXI - */ - var TextureLoader = /** @class */ (function () { - function TextureLoader() { - } - /** Handle SVG elements a text, render with SVGResource. */ - TextureLoader.add = function () { - exports.LoaderResource.setExtensionLoadType('svg', exports.LoaderResource.LOAD_TYPE.XHR); - exports.LoaderResource.setExtensionXhrType('svg', exports.LoaderResource.XHR_RESPONSE_TYPE.TEXT); - }; - /** - * Called after a resource is loaded. - * @see PIXI.Loader.loaderMiddleware - * @param resource - * @param {Function} next - */ - TextureLoader.use = function (resource, next) { - // create a new texture if the data is an Image object - if (resource.data && (resource.type === exports.LoaderResource.TYPE.IMAGE || resource.extension === 'svg')) { - var data = resource.data, url = resource.url, name = resource.name, metadata = resource.metadata; - Texture.fromLoader(data, url, name, metadata).then(function (texture) { - resource.texture = texture; - next(); - }) - // TODO: handle errors in Texture.fromLoader - // so we can pass them to the Loader - .catch(next); - } - else { - next(); - } - }; - /** @ignore */ - TextureLoader.extension = exports.ExtensionType.Loader; - return TextureLoader; - }()); - - var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - /** - * Encodes binary into base64. - * @function encodeBinary - * @param {string} input - The input data to encode. - * @returns {string} The encoded base64 string - */ - function encodeBinary(input) { - var output = ''; - var inx = 0; - while (inx < input.length) { - // Fill byte buffer array - var bytebuffer = [0, 0, 0]; - var encodedCharIndexes = [0, 0, 0, 0]; - for (var jnx = 0; jnx < bytebuffer.length; ++jnx) { - if (inx < input.length) { - // throw away high-order byte, as documented at: - // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data - bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; - } - else { - bytebuffer[jnx] = 0; - } - } - // Get each encoded character, 6 bits at a time - // index 1: first 6 bits - encodedCharIndexes[0] = bytebuffer[0] >> 2; - // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) - encodedCharIndexes[1] = ((bytebuffer[0] & 0x3) << 4) | (bytebuffer[1] >> 4); - // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) - encodedCharIndexes[2] = ((bytebuffer[1] & 0x0f) << 2) | (bytebuffer[2] >> 6); - // index 3: forth 6 bits (6 least significant bits from input byte 3) - encodedCharIndexes[3] = bytebuffer[2] & 0x3f; - // Determine whether padding happened, and adjust accordingly - var paddingBytes = inx - (input.length - 1); - switch (paddingBytes) { - case 2: - // Set last 2 characters to padding char - encodedCharIndexes[3] = 64; - encodedCharIndexes[2] = 64; - break; - case 1: - // Set last character to padding char - encodedCharIndexes[3] = 64; - break; - } - // Now we will grab each appropriate character out of our keystring - // based on our index array and append it to the output string - for (var jnx = 0; jnx < encodedCharIndexes.length; ++jnx) { - output += _keyStr.charAt(encodedCharIndexes[jnx]); - } - } - return output; - } - - /** - * A middleware for transforming XHR loaded Blobs into more useful objects - * @ignore - * @function parsing - * @example - * import { Loader, middleware } from 'resource-loader'; - * const loader = new Loader(); - * loader.use(middleware.parsing); - * @param resource - Current Resource - * @param next - Callback when complete - */ - function parsing(resource, next) { - if (!resource.data) { - next(); - return; - } - // if this was an XHR load of a blob - if (resource.xhr && resource.xhrType === exports.LoaderResource.XHR_RESPONSE_TYPE.BLOB) { - // if there is no blob support we probably got a binary string back - if (!self.Blob || typeof resource.data === 'string') { - var type = resource.xhr.getResponseHeader('content-type'); - // this is an image, convert the binary string into a data url - if (type && type.indexOf('image') === 0) { - resource.data = new Image(); - resource.data.src = "data:" + type + ";base64," + encodeBinary(resource.xhr.responseText); - resource.type = exports.LoaderResource.TYPE.IMAGE; - // wait until the image loads and then callback - resource.data.onload = function () { - resource.data.onload = null; - next(); - }; - // next will be called on load - return; - } - } - // if content type says this is an image, then we should transform the blob into an Image object - else if (resource.data.type.indexOf('image') === 0) { - var Url_1 = globalThis.URL || globalThis.webkitURL; - var src_1 = Url_1.createObjectURL(resource.data); - resource.blob = resource.data; - resource.data = new Image(); - resource.data.src = src_1; - resource.type = exports.LoaderResource.TYPE.IMAGE; - // cleanup the no longer used blob after the image loads - // TODO: Is this correct? Will the image be invalid after revoking? - resource.data.onload = function () { - Url_1.revokeObjectURL(src_1); - resource.data.onload = null; - next(); - }; - // next will be called on load. - return; - } - } - next(); - } - - /** - * Parse any blob into more usable objects (e.g. Image). - * @memberof PIXI - */ - var ParsingLoader = /** @class */ (function () { - function ParsingLoader() { - } - /** @ignore */ - ParsingLoader.extension = exports.ExtensionType.Loader; - ParsingLoader.use = parsing; - return ParsingLoader; - }()); - - extensions.add(TextureLoader, ParsingLoader); - - /*! - * @pixi/compressed-textures - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/compressed-textures is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - var _a$2; - /** - * WebGL internal formats, including compressed texture formats provided by extensions - * @memberof PIXI - * @static - * @name INTERNAL_FORMATS - * @enum {number} - * @property {number} [COMPRESSED_RGB_S3TC_DXT1_EXT=0x83F0] - - * @property {number} [COMPRESSED_RGBA_S3TC_DXT1_EXT=0x83F1] - - * @property {number} [COMPRESSED_RGBA_S3TC_DXT3_EXT=0x83F2] - - * @property {number} [COMPRESSED_RGBA_S3TC_DXT5_EXT=0x83F3] - - * @property {number} [COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917] - - * @property {number} [COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918] - - * @property {number} [COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919] - - * @property {number} [COMPRESSED_SRGB_S3TC_DXT1_EXT=35916] - - * @property {number} [COMPRESSED_R11_EAC=0x9270] - - * @property {number} [COMPRESSED_SIGNED_R11_EAC=0x9271] - - * @property {number} [COMPRESSED_RG11_EAC=0x9272] - - * @property {number} [COMPRESSED_SIGNED_RG11_EAC=0x9273] - - * @property {number} [COMPRESSED_RGB8_ETC2=0x9274] - - * @property {number} [COMPRESSED_RGBA8_ETC2_EAC=0x9278] - - * @property {number} [COMPRESSED_SRGB8_ETC2=0x9275] - - * @property {number} [COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=0x9279] - - * @property {number} [COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=0x9276] - - * @property {number} [COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=0x9277] - - * @property {number} [COMPRESSED_RGB_PVRTC_4BPPV1_IMG=0x8C00] - - * @property {number} [COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=0x8C02] - - * @property {number} [COMPRESSED_RGB_PVRTC_2BPPV1_IMG=0x8C01] - - * @property {number} [COMPRESSED_RGBA_PVRTC_2BPPV1_IMG=0x8C03] - - * @property {number} [COMPRESSED_RGB_ETC1_WEBGL=0x8D64] - - * @property {number} [COMPRESSED_RGB_ATC_WEBGL=0x8C92] - - * @property {number} [COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL=0x8C92] - - * @property {number} [COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL=0x87EE] - - * @property {number} [COMPRESSED_RGBA_ASTC_4x4_KHR=0x93B0] - - */ - exports.INTERNAL_FORMATS = void 0; - (function (INTERNAL_FORMATS) { - // WEBGL_compressed_texture_s3tc - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_S3TC_DXT1_EXT"] = 33776] = "COMPRESSED_RGB_S3TC_DXT1_EXT"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT1_EXT"] = 33777] = "COMPRESSED_RGBA_S3TC_DXT1_EXT"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT3_EXT"] = 33778] = "COMPRESSED_RGBA_S3TC_DXT3_EXT"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT5_EXT"] = 33779] = "COMPRESSED_RGBA_S3TC_DXT5_EXT"; - // WEBGL_compressed_texture_s3tc_srgb - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"] = 35917] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"] = 35918] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"] = 35919] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_S3TC_DXT1_EXT"] = 35916] = "COMPRESSED_SRGB_S3TC_DXT1_EXT"; - // WEBGL_compressed_texture_etc - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_R11_EAC"] = 37488] = "COMPRESSED_R11_EAC"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SIGNED_R11_EAC"] = 37489] = "COMPRESSED_SIGNED_R11_EAC"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RG11_EAC"] = 37490] = "COMPRESSED_RG11_EAC"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SIGNED_RG11_EAC"] = 37491] = "COMPRESSED_SIGNED_RG11_EAC"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB8_ETC2"] = 37492] = "COMPRESSED_RGB8_ETC2"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA8_ETC2_EAC"] = 37496] = "COMPRESSED_RGBA8_ETC2_EAC"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_ETC2"] = 37493] = "COMPRESSED_SRGB8_ETC2"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"] = 37497] = "COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37494] = "COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37495] = "COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"; - // WEBGL_compressed_texture_pvrtc - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_PVRTC_4BPPV1_IMG"] = 35840] = "COMPRESSED_RGB_PVRTC_4BPPV1_IMG"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"] = 35842] = "COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_PVRTC_2BPPV1_IMG"] = 35841] = "COMPRESSED_RGB_PVRTC_2BPPV1_IMG"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"] = 35843] = "COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"; - // WEBGL_compressed_texture_etc1 - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_ETC1_WEBGL"] = 36196] = "COMPRESSED_RGB_ETC1_WEBGL"; - // WEBGL_compressed_texture_atc - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_ATC_WEBGL"] = 35986] = "COMPRESSED_RGB_ATC_WEBGL"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL"] = 35986] = "COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL"; - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL"] = 34798] = "COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL"; - // WEBGL_compressed_texture_astc - /* eslint-disable-next-line camelcase */ - INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_ASTC_4x4_KHR"] = 37808] = "COMPRESSED_RGBA_ASTC_4x4_KHR"; - })(exports.INTERNAL_FORMATS || (exports.INTERNAL_FORMATS = {})); - /** - * Maps the compressed texture formats in {@link PIXI.INTERNAL_FORMATS} to the number of bytes taken by - * each texel. - * @memberof PIXI - * @static - * @ignore - */ - var INTERNAL_FORMAT_TO_BYTES_PER_PIXEL = (_a$2 = {}, - // WEBGL_compressed_texture_s3tc - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_S3TC_DXT1_EXT] = 0.5, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT] = 0.5, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT] = 1, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT] = 1, - // WEBGL_compressed_texture_s3tc - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_S3TC_DXT1_EXT] = 0.5, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT] = 0.5, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT] = 1, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT] = 1, - // WEBGL_compressed_texture_etc - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_R11_EAC] = 0.5, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SIGNED_R11_EAC] = 0.5, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RG11_EAC] = 1, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SIGNED_RG11_EAC] = 1, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB8_ETC2] = 0.5, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA8_ETC2_EAC] = 1, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB8_ETC2] = 0.5, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC] = 1, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2] = 0.5, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2] = 0.5, - // WEBGL_compressed_texture_pvrtc - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_PVRTC_4BPPV1_IMG] = 0.5, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG] = 0.5, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_PVRTC_2BPPV1_IMG] = 0.25, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG] = 0.25, - // WEBGL_compressed_texture_etc1 - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_ETC1_WEBGL] = 0.5, - // @see https://www.khronos.org/registry/OpenGL/extensions/AMD/AMD_compressed_ATC_texture.txt - // WEBGL_compressed_texture_atc - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_ATC_WEBGL] = 0.5, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL] = 1, - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL] = 1, - // @see https://registry.khronos.org/OpenGL/extensions/KHR/KHR_texture_compression_astc_hdr.txt - // WEBGL_compressed_texture_astc - /* eslint-disable-next-line camelcase */ - _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_ASTC_4x4_KHR] = 1, - _a$2); - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$g = function(d, b) { - extendStatics$g = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$g(d, b); - }; - - function __extends$g(d, b) { - extendStatics$g(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - } - - function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) { throw t[1]; } return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) { throw new TypeError("Generator is already executing."); } - while (_) { try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) { return t; } - if (y = 0, t) { op = [op[0] & 2, t.value]; } - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) { _.ops.pop(); } - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } } - if (op[0] & 5) { throw op[1]; } return { value: op[0] ? op[1] : void 0, done: true }; - } - } - - /** - * Resource that fetches texture data over the network and stores it in a buffer. - * @class - * @extends PIXI.Resource - * @memberof PIXI - */ - var BlobResource = /** @class */ (function (_super) { - __extends$g(BlobResource, _super); - /** - * @param {string} source - the URL of the texture file - * @param {PIXI.IBlobOptions} options - * @param {boolean}[options.autoLoad] - whether to fetch the data immediately; - * you can fetch it later via {@link BlobResource#load} - * @param {boolean}[options.width] - the width in pixels. - * @param {boolean}[options.height] - the height in pixels. - */ - function BlobResource(source, options) { - if (options === void 0) { options = { width: 1, height: 1, autoLoad: true }; } - var _this = this; - var origin; - var data; - if (typeof source === 'string') { - origin = source; - data = new Uint8Array(); - } - else { - origin = null; - data = source; - } - _this = _super.call(this, data, options) || this; - /** - * The URL of the texture file - * @member {string} - */ - _this.origin = origin; - /** - * The viewable buffer on the data - * @member {ViewableBuffer} - */ - // HINT: BlobResource allows "null" sources, assuming the child class provides an alternative - _this.buffer = data ? new ViewableBuffer(data) : null; - // Allow autoLoad = "undefined" still load the resource by default - if (_this.origin && options.autoLoad !== false) { - _this.load(); - } - if (data && data.length) { - _this.loaded = true; - _this.onBlobLoaded(_this.buffer.rawBinaryData); - } - return _this; - } - BlobResource.prototype.onBlobLoaded = function (_data) { - // TODO: Override this method - }; - /** Loads the blob */ - BlobResource.prototype.load = function () { - return __awaiter(this, void 0, Promise, function () { - var response, blob, arrayBuffer; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, fetch(this.origin)]; - case 1: - response = _a.sent(); - return [4 /*yield*/, response.blob()]; - case 2: - blob = _a.sent(); - return [4 /*yield*/, blob.arrayBuffer()]; - case 3: - arrayBuffer = _a.sent(); - this.data = new Uint32Array(arrayBuffer); - this.buffer = new ViewableBuffer(arrayBuffer); - this.loaded = true; - this.onBlobLoaded(arrayBuffer); - this.update(); - return [2 /*return*/, this]; - } - }); - }); - }; - return BlobResource; - }(BufferResource)); - - /** - * Resource for compressed texture formats, as follows: S3TC/DXTn (& their sRGB formats), ATC, ASTC, ETC 1/2, PVRTC. - * - * Compressed textures improve performance when rendering is texture-bound. The texture data stays compressed in - * graphics memory, increasing memory locality and speeding up texture fetches. These formats can also be used to store - * more detail in the same amount of memory. - * - * For most developers, container file formats are a better abstraction instead of directly handling raw texture - * data. PixiJS provides native support for the following texture file formats (via {@link PIXI.Loader}): - * - * **.dds** - the DirectDraw Surface file format stores DXTn (DXT-1,3,5) data. See {@link PIXI.DDSLoader} - * **.ktx** - the Khronos Texture Container file format supports storing all the supported WebGL compression formats. - * See {@link PIXI.KTXLoader}. - * **.basis** - the BASIS supercompressed file format stores texture data in an internal format that is transcoded - * to the compression format supported on the device at _runtime_. It also supports transcoding into a uncompressed - * format as a fallback; you must install the `@pixi/basis-loader`, `@pixi/basis-transcoder` packages separately to - * use these files. See {@link PIXI.BasisLoader}. - * - * The loaders for the aforementioned formats use `CompressedTextureResource` internally. It is strongly suggested that - * they be used instead. - * - * ## Working directly with CompressedTextureResource - * - * Since `CompressedTextureResource` inherits `BlobResource`, you can provide it a URL pointing to a file containing - * the raw texture data (with no file headers!): - * - * ```js - * // The resource backing the texture data for your textures. - * // NOTE: You can also provide a ArrayBufferView instead of a URL. This is used when loading data from a container file - * // format such as KTX, DDS, or BASIS. - * const compressedResource = new PIXI.CompressedTextureResource("bunny.dxt5", { - * format: PIXI.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT, - * width: 256, - * height: 256 - * }); - * - * // You can create a base-texture to the cache, so that future `Texture`s can be created using the `Texture.from` API. - * const baseTexture = new PIXI.BaseTexture(compressedResource, { pmaMode: PIXI.ALPHA_MODES.NPM }); - * - * // Create a Texture to add to the TextureCache - * const texture = new PIXI.Texture(baseTexture); - * - * // Add baseTexture & texture to the global texture cache - * PIXI.BaseTexture.addToCache(baseTexture, "bunny.dxt5"); - * PIXI.Texture.addToCache(texture, "bunny.dxt5"); - * ``` - * @memberof PIXI - */ - var CompressedTextureResource = /** @class */ (function (_super) { - __extends$g(CompressedTextureResource, _super); - /** - * @param source - the buffer/URL holding the compressed texture data - * @param options - * @param {PIXI.INTERNAL_FORMATS} options.format - the compression format - * @param {number} options.width - the image width in pixels. - * @param {number} options.height - the image height in pixels. - * @param {number} [options.level=1] - the mipmap levels stored in the compressed texture, including level 0. - * @param {number} [options.levelBuffers] - the buffers for each mipmap level. `CompressedTextureResource` can allows you - * to pass `null` for `source`, for cases where each level is stored in non-contiguous memory. - */ - function CompressedTextureResource(source, options) { - var _this = _super.call(this, source, options) || this; - _this.format = options.format; - _this.levels = options.levels || 1; - _this._width = options.width; - _this._height = options.height; - _this._extension = CompressedTextureResource._formatToExtension(_this.format); - if (options.levelBuffers || _this.buffer) { - // ViewableBuffer doesn't support byteOffset :-( so allow source to be Uint8Array - _this._levelBuffers = options.levelBuffers - || CompressedTextureResource._createLevelBuffers(source instanceof Uint8Array ? source : _this.buffer.uint8View, _this.format, _this.levels, 4, 4, // PVRTC has 8x4 blocks in 2bpp mode - _this.width, _this.height); - } - return _this; - } - /** - * @override - * @param renderer - A reference to the current renderer - * @param _texture - the texture - * @param _glTexture - texture instance for this webgl context - */ - CompressedTextureResource.prototype.upload = function (renderer, _texture, _glTexture) { - var gl = renderer.gl; - var extension = renderer.context.extensions[this._extension]; - if (!extension) { - throw new Error(this._extension + " textures are not supported on the current machine"); - } - if (!this._levelBuffers) { - // Do not try to upload data before BlobResource loads, unless the levelBuffers were provided directly! - return false; - } - for (var i = 0, j = this.levels; i < j; i++) { - var _a = this._levelBuffers[i], levelID = _a.levelID, levelWidth = _a.levelWidth, levelHeight = _a.levelHeight, levelBuffer = _a.levelBuffer; - gl.compressedTexImage2D(gl.TEXTURE_2D, levelID, this.format, levelWidth, levelHeight, 0, levelBuffer); - } - return true; - }; - /** @protected */ - CompressedTextureResource.prototype.onBlobLoaded = function () { - this._levelBuffers = CompressedTextureResource._createLevelBuffers(this.buffer.uint8View, this.format, this.levels, 4, 4, // PVRTC has 8x4 blocks in 2bpp mode - this.width, this.height); - }; - /** - * Returns the key (to ContextSystem#extensions) for the WebGL extension supporting the compression format - * @private - * @param format - the compression format to get the extension for. - */ - CompressedTextureResource._formatToExtension = function (format) { - if (format >= 0x83F0 && format <= 0x83F3) { - return 's3tc'; - } - else if (format >= 0x9270 && format <= 0x9279) { - return 'etc'; - } - else if (format >= 0x8C00 && format <= 0x8C03) { - return 'pvrtc'; - } - else if (format >= 0x8D64) { - return 'etc1'; - } - else if (format >= 0x8C92 && format <= 0x87EE) { - return 'atc'; - } - throw new Error('Invalid (compressed) texture format given!'); - }; - /** - * Pre-creates buffer views for each mipmap level - * @private - * @param buffer - - * @param format - compression formats - * @param levels - mipmap levels - * @param blockWidth - - * @param blockHeight - - * @param imageWidth - width of the image in pixels - * @param imageHeight - height of the image in pixels - */ - CompressedTextureResource._createLevelBuffers = function (buffer, format, levels, blockWidth, blockHeight, imageWidth, imageHeight) { - // The byte-size of the first level buffer - var buffers = new Array(levels); - var offset = buffer.byteOffset; - var levelWidth = imageWidth; - var levelHeight = imageHeight; - var alignedLevelWidth = (levelWidth + blockWidth - 1) & ~(blockWidth - 1); - var alignedLevelHeight = (levelHeight + blockHeight - 1) & ~(blockHeight - 1); - var levelSize = alignedLevelWidth * alignedLevelHeight * INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[format]; - for (var i = 0; i < levels; i++) { - buffers[i] = { - levelID: i, - levelWidth: levels > 1 ? levelWidth : alignedLevelWidth, - levelHeight: levels > 1 ? levelHeight : alignedLevelHeight, - levelBuffer: new Uint8Array(buffer.buffer, offset, levelSize) - }; - offset += levelSize; - // Calculate levelBuffer dimensions for next iteration - levelWidth = (levelWidth >> 1) || 1; - levelHeight = (levelHeight >> 1) || 1; - alignedLevelWidth = (levelWidth + blockWidth - 1) & ~(blockWidth - 1); - alignedLevelHeight = (levelHeight + blockHeight - 1) & ~(blockHeight - 1); - levelSize = alignedLevelWidth * alignedLevelHeight * INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[format]; - } - return buffers; - }; - return CompressedTextureResource; - }(BlobResource)); - - /* eslint-enable camelcase */ - /** - * Loader plugin for handling compressed textures for all platforms. - * @class - * @memberof PIXI - * @implements {PIXI.ILoaderPlugin} - */ - var CompressedTextureLoader = /** @class */ (function () { - function CompressedTextureLoader() { - } - /** - * Called after a compressed-textures manifest is loaded. - * - * This will then load the correct compression format for the device. Your manifest should adhere - * to the following schema: - * - * ```js - * import { INTERNAL_FORMATS } from '@pixi/constants'; - * - * type CompressedTextureManifest = { - * textures: Array<{ src: string, format?: keyof INTERNAL_FORMATS}>, - * cacheID: string; - * }; - * ``` - * - * This is an example of a .json manifest file - * - * ```json - * { - * "cacheID":"asset", - * "textures":[ - * { "src":"asset.fallback.png" }, - * { "format":"COMPRESSED_RGBA_S3TC_DXT5_EXT", "src":"asset.s3tc.ktx" }, - * { "format":"COMPRESSED_RGBA8_ETC2_EAC", "src":"asset.etc.ktx" }, - * { "format":"RGBA_PVRTC_4BPPV1_IMG", "src":"asset.pvrtc.ktx" } - * ] - * } - * ``` - */ - CompressedTextureLoader.use = function (resource, next) { - var data = resource.data; - var loader = this; - if (resource.type === exports.LoaderResource.TYPE.JSON - && data - && data.cacheID - && data.textures) { - var textures = data.textures; - var textureURL = void 0; - var fallbackURL = void 0; - // Search for an extension that holds one the formats - for (var i = 0, j = textures.length; i < j; i++) { - var texture = textures[i]; - var url_1 = texture.src; - var format = texture.format; - if (!format) { - fallbackURL = url_1; - } - if (CompressedTextureLoader.textureFormats[format]) { - textureURL = url_1; - break; - } - } - textureURL = textureURL || fallbackURL; - // Make sure we have a URL - if (!textureURL) { - next(new Error("Cannot load compressed-textures in " + resource.url + ", make sure you provide a fallback")); - return; - } - if (textureURL === resource.url) { - // Prevent infinite loops - next(new Error('URL of compressed texture cannot be the same as the manifest\'s URL')); - return; - } - var loadOptions = { - crossOrigin: resource.crossOrigin, - metadata: resource.metadata.imageMetadata, - parentResource: resource - }; - var resourcePath = url.resolve(resource.url.replace(loader.baseUrl, ''), textureURL); - var resourceName = data.cacheID; - // The appropriate loader should register the texture - loader.add(resourceName, resourcePath, loadOptions, function (res) { - if (res.error) { - next(res.error); - return; - } - var _a = res.texture, texture = _a === void 0 ? null : _a, _b = res.textures, textures = _b === void 0 ? {} : _b; - // Make sure texture/textures is assigned to parent resource - Object.assign(resource, { texture: texture, textures: textures }); - // Pass along any error - next(); - }); - } - else { - next(); - } - }; - Object.defineProperty(CompressedTextureLoader, "textureExtensions", { - /** Map of available texture extensions. */ - get: function () { - if (!CompressedTextureLoader._textureExtensions) { - // Auto-detect WebGL compressed-texture extensions - var canvas = settings.ADAPTER.createCanvas(); - var gl = canvas.getContext('webgl'); - if (!gl) { - console.warn('WebGL not available for compressed textures. Silently failing.'); - return {}; - } - var extensions = { - s3tc: gl.getExtension('WEBGL_compressed_texture_s3tc'), - s3tc_sRGB: gl.getExtension('WEBGL_compressed_texture_s3tc_srgb'), - etc: gl.getExtension('WEBGL_compressed_texture_etc'), - etc1: gl.getExtension('WEBGL_compressed_texture_etc1'), - pvrtc: gl.getExtension('WEBGL_compressed_texture_pvrtc') - || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'), - atc: gl.getExtension('WEBGL_compressed_texture_atc'), - astc: gl.getExtension('WEBGL_compressed_texture_astc') - }; - CompressedTextureLoader._textureExtensions = extensions; - } - return CompressedTextureLoader._textureExtensions; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CompressedTextureLoader, "textureFormats", { - /** Map of available texture formats. */ - get: function () { - if (!CompressedTextureLoader._textureFormats) { - var extensions = CompressedTextureLoader.textureExtensions; - CompressedTextureLoader._textureFormats = {}; - // Assign all available compressed-texture formats - for (var extensionName in extensions) { - var extension = extensions[extensionName]; - if (!extension) { - continue; - } - Object.assign(CompressedTextureLoader._textureFormats, Object.getPrototypeOf(extension)); - } - } - return CompressedTextureLoader._textureFormats; - }, - enumerable: false, - configurable: true - }); - /** @ignore */ - CompressedTextureLoader.extension = exports.ExtensionType.Loader; - return CompressedTextureLoader; - }()); - - /** - * Creates base-textures and textures for each compressed-texture resource and adds them into the global - * texture cache. The first texture has two IDs - `${url}`, `${url}-1`; while the rest have an ID of the - * form `${url}-i`. - * @param url - the original address of the resources - * @param resources - the resources backing texture data - * @ignore - */ - function registerCompressedTextures(url, resources, metadata) { - var result = { - textures: {}, - texture: null, - }; - if (!resources) { - return result; - } - var textures = resources.map(function (resource) { - return (new Texture(new BaseTexture(resource, Object.assign({ - mipmap: exports.MIPMAP_MODES.OFF, - alphaMode: exports.ALPHA_MODES.NO_PREMULTIPLIED_ALPHA - }, metadata)))); - }); - textures.forEach(function (texture, i) { - var baseTexture = texture.baseTexture; - var cacheID = url + "-" + (i + 1); - BaseTexture.addToCache(baseTexture, cacheID); - Texture.addToCache(texture, cacheID); - if (i === 0) { - BaseTexture.addToCache(baseTexture, url); - Texture.addToCache(texture, url); - result.texture = texture; - } - result.textures[cacheID] = texture; - }); - return result; - } - - var _a$1, _b$1; - var DDS_MAGIC_SIZE = 4; - var DDS_HEADER_SIZE = 124; - var DDS_HEADER_PF_SIZE = 32; - var DDS_HEADER_DX10_SIZE = 20; - // DDS file format magic word - var DDS_MAGIC = 0x20534444; - /** - * DWORD offsets of the DDS file header fields (relative to file start). - * @ignore - */ - var DDS_FIELDS = { - SIZE: 1, - FLAGS: 2, - HEIGHT: 3, - WIDTH: 4, - MIPMAP_COUNT: 7, - PIXEL_FORMAT: 19, - }; - /** - * DWORD offsets of the DDS PIXEL_FORMAT fields. - * @ignore - */ - var DDS_PF_FIELDS = { - SIZE: 0, - FLAGS: 1, - FOURCC: 2, - RGB_BITCOUNT: 3, - R_BIT_MASK: 4, - G_BIT_MASK: 5, - B_BIT_MASK: 6, - A_BIT_MASK: 7 - }; - /** - * DWORD offsets of the DDS_HEADER_DX10 fields. - * @ignore - */ - var DDS_DX10_FIELDS = { - DXGI_FORMAT: 0, - RESOURCE_DIMENSION: 1, - MISC_FLAG: 2, - ARRAY_SIZE: 3, - MISC_FLAGS2: 4 - }; - /** - * @see https://docs.microsoft.com/en-us/windows/win32/api/dxgiformat/ne-dxgiformat-dxgi_format - * @ignore - */ - // This is way over-blown for us! Lend us a hand, and remove the ones that aren't used (but set the remaining - // ones to their correct value) - var DXGI_FORMAT; - (function (DXGI_FORMAT) { - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_UNKNOWN"] = 0] = "DXGI_FORMAT_UNKNOWN"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_TYPELESS"] = 1] = "DXGI_FORMAT_R32G32B32A32_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_FLOAT"] = 2] = "DXGI_FORMAT_R32G32B32A32_FLOAT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_UINT"] = 3] = "DXGI_FORMAT_R32G32B32A32_UINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_SINT"] = 4] = "DXGI_FORMAT_R32G32B32A32_SINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_TYPELESS"] = 5] = "DXGI_FORMAT_R32G32B32_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_FLOAT"] = 6] = "DXGI_FORMAT_R32G32B32_FLOAT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_UINT"] = 7] = "DXGI_FORMAT_R32G32B32_UINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_SINT"] = 8] = "DXGI_FORMAT_R32G32B32_SINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_TYPELESS"] = 9] = "DXGI_FORMAT_R16G16B16A16_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_FLOAT"] = 10] = "DXGI_FORMAT_R16G16B16A16_FLOAT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_UNORM"] = 11] = "DXGI_FORMAT_R16G16B16A16_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_UINT"] = 12] = "DXGI_FORMAT_R16G16B16A16_UINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_SNORM"] = 13] = "DXGI_FORMAT_R16G16B16A16_SNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_SINT"] = 14] = "DXGI_FORMAT_R16G16B16A16_SINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_TYPELESS"] = 15] = "DXGI_FORMAT_R32G32_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_FLOAT"] = 16] = "DXGI_FORMAT_R32G32_FLOAT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_UINT"] = 17] = "DXGI_FORMAT_R32G32_UINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_SINT"] = 18] = "DXGI_FORMAT_R32G32_SINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G8X24_TYPELESS"] = 19] = "DXGI_FORMAT_R32G8X24_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D32_FLOAT_S8X24_UINT"] = 20] = "DXGI_FORMAT_D32_FLOAT_S8X24_UINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS"] = 21] = "DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_X32_TYPELESS_G8X24_UINT"] = 22] = "DXGI_FORMAT_X32_TYPELESS_G8X24_UINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_TYPELESS"] = 23] = "DXGI_FORMAT_R10G10B10A2_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_UNORM"] = 24] = "DXGI_FORMAT_R10G10B10A2_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_UINT"] = 25] = "DXGI_FORMAT_R10G10B10A2_UINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R11G11B10_FLOAT"] = 26] = "DXGI_FORMAT_R11G11B10_FLOAT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_TYPELESS"] = 27] = "DXGI_FORMAT_R8G8B8A8_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UNORM"] = 28] = "DXGI_FORMAT_R8G8B8A8_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UNORM_SRGB"] = 29] = "DXGI_FORMAT_R8G8B8A8_UNORM_SRGB"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UINT"] = 30] = "DXGI_FORMAT_R8G8B8A8_UINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_SNORM"] = 31] = "DXGI_FORMAT_R8G8B8A8_SNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_SINT"] = 32] = "DXGI_FORMAT_R8G8B8A8_SINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_TYPELESS"] = 33] = "DXGI_FORMAT_R16G16_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_FLOAT"] = 34] = "DXGI_FORMAT_R16G16_FLOAT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_UNORM"] = 35] = "DXGI_FORMAT_R16G16_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_UINT"] = 36] = "DXGI_FORMAT_R16G16_UINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_SNORM"] = 37] = "DXGI_FORMAT_R16G16_SNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_SINT"] = 38] = "DXGI_FORMAT_R16G16_SINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_TYPELESS"] = 39] = "DXGI_FORMAT_R32_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D32_FLOAT"] = 40] = "DXGI_FORMAT_D32_FLOAT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_FLOAT"] = 41] = "DXGI_FORMAT_R32_FLOAT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_UINT"] = 42] = "DXGI_FORMAT_R32_UINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_SINT"] = 43] = "DXGI_FORMAT_R32_SINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R24G8_TYPELESS"] = 44] = "DXGI_FORMAT_R24G8_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D24_UNORM_S8_UINT"] = 45] = "DXGI_FORMAT_D24_UNORM_S8_UINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R24_UNORM_X8_TYPELESS"] = 46] = "DXGI_FORMAT_R24_UNORM_X8_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_X24_TYPELESS_G8_UINT"] = 47] = "DXGI_FORMAT_X24_TYPELESS_G8_UINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_TYPELESS"] = 48] = "DXGI_FORMAT_R8G8_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_UNORM"] = 49] = "DXGI_FORMAT_R8G8_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_UINT"] = 50] = "DXGI_FORMAT_R8G8_UINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_SNORM"] = 51] = "DXGI_FORMAT_R8G8_SNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_SINT"] = 52] = "DXGI_FORMAT_R8G8_SINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_TYPELESS"] = 53] = "DXGI_FORMAT_R16_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_FLOAT"] = 54] = "DXGI_FORMAT_R16_FLOAT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D16_UNORM"] = 55] = "DXGI_FORMAT_D16_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_UNORM"] = 56] = "DXGI_FORMAT_R16_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_UINT"] = 57] = "DXGI_FORMAT_R16_UINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_SNORM"] = 58] = "DXGI_FORMAT_R16_SNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_SINT"] = 59] = "DXGI_FORMAT_R16_SINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_TYPELESS"] = 60] = "DXGI_FORMAT_R8_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_UNORM"] = 61] = "DXGI_FORMAT_R8_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_UINT"] = 62] = "DXGI_FORMAT_R8_UINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_SNORM"] = 63] = "DXGI_FORMAT_R8_SNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_SINT"] = 64] = "DXGI_FORMAT_R8_SINT"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_A8_UNORM"] = 65] = "DXGI_FORMAT_A8_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R1_UNORM"] = 66] = "DXGI_FORMAT_R1_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R9G9B9E5_SHAREDEXP"] = 67] = "DXGI_FORMAT_R9G9B9E5_SHAREDEXP"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_B8G8_UNORM"] = 68] = "DXGI_FORMAT_R8G8_B8G8_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_G8R8_G8B8_UNORM"] = 69] = "DXGI_FORMAT_G8R8_G8B8_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_TYPELESS"] = 70] = "DXGI_FORMAT_BC1_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_UNORM"] = 71] = "DXGI_FORMAT_BC1_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_UNORM_SRGB"] = 72] = "DXGI_FORMAT_BC1_UNORM_SRGB"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_TYPELESS"] = 73] = "DXGI_FORMAT_BC2_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_UNORM"] = 74] = "DXGI_FORMAT_BC2_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_UNORM_SRGB"] = 75] = "DXGI_FORMAT_BC2_UNORM_SRGB"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_TYPELESS"] = 76] = "DXGI_FORMAT_BC3_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_UNORM"] = 77] = "DXGI_FORMAT_BC3_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_UNORM_SRGB"] = 78] = "DXGI_FORMAT_BC3_UNORM_SRGB"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_TYPELESS"] = 79] = "DXGI_FORMAT_BC4_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_UNORM"] = 80] = "DXGI_FORMAT_BC4_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_SNORM"] = 81] = "DXGI_FORMAT_BC4_SNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_TYPELESS"] = 82] = "DXGI_FORMAT_BC5_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_UNORM"] = 83] = "DXGI_FORMAT_BC5_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_SNORM"] = 84] = "DXGI_FORMAT_BC5_SNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B5G6R5_UNORM"] = 85] = "DXGI_FORMAT_B5G6R5_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B5G5R5A1_UNORM"] = 86] = "DXGI_FORMAT_B5G5R5A1_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_UNORM"] = 87] = "DXGI_FORMAT_B8G8R8A8_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_UNORM"] = 88] = "DXGI_FORMAT_B8G8R8X8_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM"] = 89] = "DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_TYPELESS"] = 90] = "DXGI_FORMAT_B8G8R8A8_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_UNORM_SRGB"] = 91] = "DXGI_FORMAT_B8G8R8A8_UNORM_SRGB"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_TYPELESS"] = 92] = "DXGI_FORMAT_B8G8R8X8_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_UNORM_SRGB"] = 93] = "DXGI_FORMAT_B8G8R8X8_UNORM_SRGB"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_TYPELESS"] = 94] = "DXGI_FORMAT_BC6H_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_UF16"] = 95] = "DXGI_FORMAT_BC6H_UF16"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_SF16"] = 96] = "DXGI_FORMAT_BC6H_SF16"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_TYPELESS"] = 97] = "DXGI_FORMAT_BC7_TYPELESS"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_UNORM"] = 98] = "DXGI_FORMAT_BC7_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_UNORM_SRGB"] = 99] = "DXGI_FORMAT_BC7_UNORM_SRGB"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_AYUV"] = 100] = "DXGI_FORMAT_AYUV"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y410"] = 101] = "DXGI_FORMAT_Y410"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y416"] = 102] = "DXGI_FORMAT_Y416"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_NV12"] = 103] = "DXGI_FORMAT_NV12"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P010"] = 104] = "DXGI_FORMAT_P010"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P016"] = 105] = "DXGI_FORMAT_P016"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_420_OPAQUE"] = 106] = "DXGI_FORMAT_420_OPAQUE"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_YUY2"] = 107] = "DXGI_FORMAT_YUY2"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y210"] = 108] = "DXGI_FORMAT_Y210"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y216"] = 109] = "DXGI_FORMAT_Y216"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_NV11"] = 110] = "DXGI_FORMAT_NV11"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_AI44"] = 111] = "DXGI_FORMAT_AI44"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_IA44"] = 112] = "DXGI_FORMAT_IA44"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P8"] = 113] = "DXGI_FORMAT_P8"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_A8P8"] = 114] = "DXGI_FORMAT_A8P8"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B4G4R4A4_UNORM"] = 115] = "DXGI_FORMAT_B4G4R4A4_UNORM"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P208"] = 116] = "DXGI_FORMAT_P208"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_V208"] = 117] = "DXGI_FORMAT_V208"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_V408"] = 118] = "DXGI_FORMAT_V408"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE"] = 119] = "DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE"] = 120] = "DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE"; - DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_FORCE_UINT"] = 121] = "DXGI_FORMAT_FORCE_UINT"; - })(DXGI_FORMAT || (DXGI_FORMAT = {})); - /** - * Possible values of the field {@link DDS_DX10_FIELDS.RESOURCE_DIMENSION} - * @ignore - */ - var D3D10_RESOURCE_DIMENSION; - (function (D3D10_RESOURCE_DIMENSION) { - D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE1D"] = 2] = "DDS_DIMENSION_TEXTURE1D"; - D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE2D"] = 3] = "DDS_DIMENSION_TEXTURE2D"; - D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE3D"] = 6] = "DDS_DIMENSION_TEXTURE3D"; - })(D3D10_RESOURCE_DIMENSION || (D3D10_RESOURCE_DIMENSION = {})); - var PF_FLAGS = 1; - // PIXEL_FORMAT flags - var DDPF_ALPHA = 0x2; - var DDPF_FOURCC = 0x4; - var DDPF_RGB = 0x40; - var DDPF_YUV = 0x200; - var DDPF_LUMINANCE = 0x20000; - // Four character codes for DXTn formats - var FOURCC_DXT1 = 0x31545844; - var FOURCC_DXT3 = 0x33545844; - var FOURCC_DXT5 = 0x35545844; - var FOURCC_DX10 = 0x30315844; - // Cubemap texture flag (for DDS_DX10_FIELDS.MISC_FLAG) - var DDS_RESOURCE_MISC_TEXTURECUBE = 0x4; - /** - * Maps `FOURCC_*` formats to internal formats (see {@link PIXI.INTERNAL_FORMATS}). - * @ignore - */ - var FOURCC_TO_FORMAT = (_a$1 = {}, - _a$1[FOURCC_DXT1] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT, - _a$1[FOURCC_DXT3] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT, - _a$1[FOURCC_DXT5] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT, - _a$1); - /** - * Maps {@link DXGI_FORMAT} to types/internal-formats (see {@link PIXI.TYPES}, {@link PIXI.INTERNAL_FORMATS}) - * @ignore - */ - var DXGI_TO_FORMAT = (_b$1 = {}, - // WEBGL_compressed_texture_s3tc - _b$1[DXGI_FORMAT.DXGI_FORMAT_BC1_TYPELESS] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT, - _b$1[DXGI_FORMAT.DXGI_FORMAT_BC1_UNORM] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT, - _b$1[DXGI_FORMAT.DXGI_FORMAT_BC2_TYPELESS] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT, - _b$1[DXGI_FORMAT.DXGI_FORMAT_BC2_UNORM] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT, - _b$1[DXGI_FORMAT.DXGI_FORMAT_BC3_TYPELESS] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT, - _b$1[DXGI_FORMAT.DXGI_FORMAT_BC3_UNORM] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT, - // WEBGL_compressed_texture_s3tc_srgb - _b$1[DXGI_FORMAT.DXGI_FORMAT_BC1_UNORM_SRGB] = exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, - _b$1[DXGI_FORMAT.DXGI_FORMAT_BC2_UNORM_SRGB] = exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, - _b$1[DXGI_FORMAT.DXGI_FORMAT_BC3_UNORM_SRGB] = exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, - _b$1); - /** - * @class - * @memberof PIXI - * @implements {PIXI.ILoaderPlugin} - * @see https://docs.microsoft.com/en-us/windows/win32/direct3ddds/dx-graphics-dds-pguide - */ - /** - * Parses the DDS file header, generates base-textures, and puts them into the texture cache. - * @param arrayBuffer - */ - function parseDDS(arrayBuffer) { - var data = new Uint32Array(arrayBuffer); - var magicWord = data[0]; - if (magicWord !== DDS_MAGIC) { - throw new Error('Invalid DDS file magic word'); - } - var header = new Uint32Array(arrayBuffer, 0, DDS_HEADER_SIZE / Uint32Array.BYTES_PER_ELEMENT); - // DDS header fields - var height = header[DDS_FIELDS.HEIGHT]; - var width = header[DDS_FIELDS.WIDTH]; - var mipmapCount = header[DDS_FIELDS.MIPMAP_COUNT]; - // PIXEL_FORMAT fields - var pixelFormat = new Uint32Array(arrayBuffer, DDS_FIELDS.PIXEL_FORMAT * Uint32Array.BYTES_PER_ELEMENT, DDS_HEADER_PF_SIZE / Uint32Array.BYTES_PER_ELEMENT); - var formatFlags = pixelFormat[PF_FLAGS]; - // File contains compressed texture(s) - if (formatFlags & DDPF_FOURCC) { - var fourCC = pixelFormat[DDS_PF_FIELDS.FOURCC]; - // File contains one DXTn compressed texture - if (fourCC !== FOURCC_DX10) { - var internalFormat_1 = FOURCC_TO_FORMAT[fourCC]; - var dataOffset_1 = DDS_MAGIC_SIZE + DDS_HEADER_SIZE; - var texData = new Uint8Array(arrayBuffer, dataOffset_1); - var resource = new CompressedTextureResource(texData, { - format: internalFormat_1, - width: width, - height: height, - levels: mipmapCount // CompressedTextureResource will separate the levelBuffers for us! - }); - return [resource]; - } - // FOURCC_DX10 indicates there is a 20-byte DDS_HEADER_DX10 after DDS_HEADER - var dx10Offset = DDS_MAGIC_SIZE + DDS_HEADER_SIZE; - var dx10Header = new Uint32Array(data.buffer, dx10Offset, DDS_HEADER_DX10_SIZE / Uint32Array.BYTES_PER_ELEMENT); - var dxgiFormat = dx10Header[DDS_DX10_FIELDS.DXGI_FORMAT]; - var resourceDimension = dx10Header[DDS_DX10_FIELDS.RESOURCE_DIMENSION]; - var miscFlag = dx10Header[DDS_DX10_FIELDS.MISC_FLAG]; - var arraySize = dx10Header[DDS_DX10_FIELDS.ARRAY_SIZE]; - // Map dxgiFormat to PIXI.INTERNAL_FORMATS - var internalFormat_2 = DXGI_TO_FORMAT[dxgiFormat]; - if (internalFormat_2 === undefined) { - throw new Error("DDSParser cannot parse texture data with DXGI format " + dxgiFormat); - } - if (miscFlag === DDS_RESOURCE_MISC_TEXTURECUBE) { - // FIXME: Anybody excited about cubemap compressed textures? - throw new Error('DDSParser does not support cubemap textures'); - } - if (resourceDimension === D3D10_RESOURCE_DIMENSION.DDS_DIMENSION_TEXTURE3D) { - // FIXME: Anybody excited about 3D compressed textures? - throw new Error('DDSParser does not supported 3D texture data'); - } - // Uint8Array buffers of image data, including all mipmap levels in each image - var imageBuffers = new Array(); - var dataOffset = DDS_MAGIC_SIZE - + DDS_HEADER_SIZE - + DDS_HEADER_DX10_SIZE; - if (arraySize === 1) { - // No need bothering with the imageSize calculation! - imageBuffers.push(new Uint8Array(arrayBuffer, dataOffset)); - } - else { - // Calculate imageSize for each texture, and then locate each image's texture data - var pixelSize = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[internalFormat_2]; - var imageSize = 0; - var levelWidth = width; - var levelHeight = height; - for (var i = 0; i < mipmapCount; i++) { - var alignedLevelWidth = Math.max(1, (levelWidth + 3) & ~3); - var alignedLevelHeight = Math.max(1, (levelHeight + 3) & ~3); - var levelSize = alignedLevelWidth * alignedLevelHeight * pixelSize; - imageSize += levelSize; - levelWidth = levelWidth >>> 1; - levelHeight = levelHeight >>> 1; - } - var imageOffset = dataOffset; - // NOTE: Cubemaps have 6-images per texture (but they aren't supported so ^_^) - for (var i = 0; i < arraySize; i++) { - imageBuffers.push(new Uint8Array(arrayBuffer, imageOffset, imageSize)); - imageOffset += imageSize; - } - } - // Uint8Array -> CompressedTextureResource, and we're done! - return imageBuffers.map(function (buffer) { return new CompressedTextureResource(buffer, { - format: internalFormat_2, - width: width, - height: height, - levels: mipmapCount - }); }); - } - if (formatFlags & DDPF_RGB) { - // FIXME: We might want to allow uncompressed *.dds files? - throw new Error('DDSParser does not support uncompressed texture data.'); - } - if (formatFlags & DDPF_YUV) { - // FIXME: Does anybody need this feature? - throw new Error('DDSParser does not supported YUV uncompressed texture data.'); - } - if (formatFlags & DDPF_LUMINANCE) { - // FIXME: Microsoft says older DDS filers use this feature! Probably not worth the effort! - throw new Error('DDSParser does not support single-channel (lumninance) texture data!'); - } - if (formatFlags & DDPF_ALPHA) { - // FIXME: I'm tired! See above =) - throw new Error('DDSParser does not support single-channel (alpha) texture data!'); - } - throw new Error('DDSParser failed to load a texture file due to an unknown reason!'); - } - - var _a$3, _b, _c; - /** - * The 12-byte KTX file identifier - * @see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/#2.1 - * @ignore - */ - var FILE_IDENTIFIER = [0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A]; - /** - * The value stored in the "endianness" field. - * @see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/#2.2 - * @ignore - */ - var ENDIANNESS = 0x04030201; - /** - * Byte offsets of the KTX file header fields - * @ignore - */ - var KTX_FIELDS = { - FILE_IDENTIFIER: 0, - ENDIANNESS: 12, - GL_TYPE: 16, - GL_TYPE_SIZE: 20, - GL_FORMAT: 24, - GL_INTERNAL_FORMAT: 28, - GL_BASE_INTERNAL_FORMAT: 32, - PIXEL_WIDTH: 36, - PIXEL_HEIGHT: 40, - PIXEL_DEPTH: 44, - NUMBER_OF_ARRAY_ELEMENTS: 48, - NUMBER_OF_FACES: 52, - NUMBER_OF_MIPMAP_LEVELS: 56, - BYTES_OF_KEY_VALUE_DATA: 60 - }; - /** - * Byte size of the file header fields in {@code KTX_FIELDS} - * @ignore - */ - var FILE_HEADER_SIZE = 64; - /** - * Maps {@link PIXI.TYPES} to the bytes taken per component, excluding those ones that are bit-fields. - * @ignore - */ - var TYPES_TO_BYTES_PER_COMPONENT = (_a$3 = {}, - _a$3[exports.TYPES.UNSIGNED_BYTE] = 1, - _a$3[exports.TYPES.UNSIGNED_SHORT] = 2, - _a$3[exports.TYPES.INT] = 4, - _a$3[exports.TYPES.UNSIGNED_INT] = 4, - _a$3[exports.TYPES.FLOAT] = 4, - _a$3[exports.TYPES.HALF_FLOAT] = 8, - _a$3); - /** - * Number of components in each {@link PIXI.FORMATS} - * @ignore - */ - var FORMATS_TO_COMPONENTS = (_b = {}, - _b[exports.FORMATS.RGBA] = 4, - _b[exports.FORMATS.RGB] = 3, - _b[exports.FORMATS.RG] = 2, - _b[exports.FORMATS.RED] = 1, - _b[exports.FORMATS.LUMINANCE] = 1, - _b[exports.FORMATS.LUMINANCE_ALPHA] = 2, - _b[exports.FORMATS.ALPHA] = 1, - _b); - /** - * Number of bytes per pixel in bit-field types in {@link PIXI.TYPES} - * @ignore - */ - var TYPES_TO_BYTES_PER_PIXEL = (_c = {}, - _c[exports.TYPES.UNSIGNED_SHORT_4_4_4_4] = 2, - _c[exports.TYPES.UNSIGNED_SHORT_5_5_5_1] = 2, - _c[exports.TYPES.UNSIGNED_SHORT_5_6_5] = 2, - _c); - function parseKTX(url, arrayBuffer, loadKeyValueData) { - if (loadKeyValueData === void 0) { loadKeyValueData = false; } - var dataView = new DataView(arrayBuffer); - if (!validate(url, dataView)) { - return null; - } - var littleEndian = dataView.getUint32(KTX_FIELDS.ENDIANNESS, true) === ENDIANNESS; - var glType = dataView.getUint32(KTX_FIELDS.GL_TYPE, littleEndian); - // const glTypeSize = dataView.getUint32(KTX_FIELDS.GL_TYPE_SIZE, littleEndian); - var glFormat = dataView.getUint32(KTX_FIELDS.GL_FORMAT, littleEndian); - var glInternalFormat = dataView.getUint32(KTX_FIELDS.GL_INTERNAL_FORMAT, littleEndian); - var pixelWidth = dataView.getUint32(KTX_FIELDS.PIXEL_WIDTH, littleEndian); - var pixelHeight = dataView.getUint32(KTX_FIELDS.PIXEL_HEIGHT, littleEndian) || 1; // "pixelHeight = 0" -> "1" - var pixelDepth = dataView.getUint32(KTX_FIELDS.PIXEL_DEPTH, littleEndian) || 1; // ^^ - var numberOfArrayElements = dataView.getUint32(KTX_FIELDS.NUMBER_OF_ARRAY_ELEMENTS, littleEndian) || 1; // ^^ - var numberOfFaces = dataView.getUint32(KTX_FIELDS.NUMBER_OF_FACES, littleEndian); - var numberOfMipmapLevels = dataView.getUint32(KTX_FIELDS.NUMBER_OF_MIPMAP_LEVELS, littleEndian); - var bytesOfKeyValueData = dataView.getUint32(KTX_FIELDS.BYTES_OF_KEY_VALUE_DATA, littleEndian); - // Whether the platform architecture is little endian. If littleEndian !== platformLittleEndian, then the - // file contents must be endian-converted! - // TODO: Endianness conversion - // const platformLittleEndian = new Uint8Array((new Uint32Array([ENDIANNESS])).buffer)[0] === 0x01; - if (pixelHeight === 0 || pixelDepth !== 1) { - throw new Error('Only 2D textures are supported'); - } - if (numberOfFaces !== 1) { - throw new Error('CubeTextures are not supported by KTXLoader yet!'); - } - if (numberOfArrayElements !== 1) { - // TODO: Support splitting array-textures into multiple BaseTextures - throw new Error('WebGL does not support array textures'); - } - // TODO: 8x4 blocks for 2bpp pvrtc - var blockWidth = 4; - var blockHeight = 4; - var alignedWidth = (pixelWidth + 3) & ~3; - var alignedHeight = (pixelHeight + 3) & ~3; - var imageBuffers = new Array(numberOfArrayElements); - var imagePixels = pixelWidth * pixelHeight; - if (glType === 0) { - // Align to 16 pixels (4x4 blocks) - imagePixels = alignedWidth * alignedHeight; - } - var imagePixelByteSize; - if (glType !== 0) { - // Uncompressed texture format - if (TYPES_TO_BYTES_PER_COMPONENT[glType]) { - imagePixelByteSize = TYPES_TO_BYTES_PER_COMPONENT[glType] * FORMATS_TO_COMPONENTS[glFormat]; - } - else { - imagePixelByteSize = TYPES_TO_BYTES_PER_PIXEL[glType]; - } - } - else { - imagePixelByteSize = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[glInternalFormat]; - } - if (imagePixelByteSize === undefined) { - throw new Error('Unable to resolve the pixel format stored in the *.ktx file!'); - } - var kvData = loadKeyValueData - ? parseKvData(dataView, bytesOfKeyValueData, littleEndian) - : null; - var imageByteSize = imagePixels * imagePixelByteSize; - var mipByteSize = imageByteSize; - var mipWidth = pixelWidth; - var mipHeight = pixelHeight; - var alignedMipWidth = alignedWidth; - var alignedMipHeight = alignedHeight; - var imageOffset = FILE_HEADER_SIZE + bytesOfKeyValueData; - for (var mipmapLevel = 0; mipmapLevel < numberOfMipmapLevels; mipmapLevel++) { - var imageSize = dataView.getUint32(imageOffset, littleEndian); - var elementOffset = imageOffset + 4; - for (var arrayElement = 0; arrayElement < numberOfArrayElements; arrayElement++) { - // TODO: Maybe support 3D textures? :-) - // for (let zSlice = 0; zSlice < pixelDepth; zSlice) - var mips = imageBuffers[arrayElement]; - if (!mips) { - mips = imageBuffers[arrayElement] = new Array(numberOfMipmapLevels); - } - mips[mipmapLevel] = { - levelID: mipmapLevel, - // don't align mipWidth when texture not compressed! (glType not zero) - levelWidth: numberOfMipmapLevels > 1 || glType !== 0 ? mipWidth : alignedMipWidth, - levelHeight: numberOfMipmapLevels > 1 || glType !== 0 ? mipHeight : alignedMipHeight, - levelBuffer: new Uint8Array(arrayBuffer, elementOffset, mipByteSize) - }; - elementOffset += mipByteSize; - } - // HINT: Aligns to 4-byte boundary after jumping imageSize (in lieu of mipPadding) - imageOffset += imageSize + 4; // (+4 to jump the imageSize field itself) - imageOffset = imageOffset % 4 !== 0 ? imageOffset + 4 - (imageOffset % 4) : imageOffset; - // Calculate mipWidth, mipHeight for _next_ iteration - mipWidth = (mipWidth >> 1) || 1; - mipHeight = (mipHeight >> 1) || 1; - alignedMipWidth = (mipWidth + blockWidth - 1) & ~(blockWidth - 1); - alignedMipHeight = (mipHeight + blockHeight - 1) & ~(blockHeight - 1); - // Each mipmap level is 4-times smaller? - mipByteSize = alignedMipWidth * alignedMipHeight * imagePixelByteSize; - } - // We use the levelBuffers feature of CompressedTextureResource b/c texture data is image-major, not level-major. - if (glType !== 0) { - return { - uncompressed: imageBuffers.map(function (levelBuffers) { - var buffer = levelBuffers[0].levelBuffer; - var convertToInt = false; - if (glType === exports.TYPES.FLOAT) { - buffer = new Float32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4); - } - else if (glType === exports.TYPES.UNSIGNED_INT) { - convertToInt = true; - buffer = new Uint32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4); - } - else if (glType === exports.TYPES.INT) { - convertToInt = true; - buffer = new Int32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4); - } - return { - resource: new BufferResource(buffer, { - width: levelBuffers[0].levelWidth, - height: levelBuffers[0].levelHeight, - }), - type: glType, - format: convertToInt ? convertFormatToInteger(glFormat) : glFormat, - }; - }), - kvData: kvData - }; - } - return { - compressed: imageBuffers.map(function (levelBuffers) { return new CompressedTextureResource(null, { - format: glInternalFormat, - width: pixelWidth, - height: pixelHeight, - levels: numberOfMipmapLevels, - levelBuffers: levelBuffers, - }); }), - kvData: kvData - }; - } - /** - * Checks whether the arrayBuffer contains a valid *.ktx file. - * @param url - * @param dataView - */ - function validate(url, dataView) { - // NOTE: Do not optimize this into 3 32-bit integer comparison because the endianness - // of the data is not specified. - for (var i = 0; i < FILE_IDENTIFIER.length; i++) { - if (dataView.getUint8(i) !== FILE_IDENTIFIER[i]) { - console.error(url + " is not a valid *.ktx file!"); - return false; - } - } - return true; - } - function convertFormatToInteger(format) { - switch (format) { - case exports.FORMATS.RGBA: return exports.FORMATS.RGBA_INTEGER; - case exports.FORMATS.RGB: return exports.FORMATS.RGB_INTEGER; - case exports.FORMATS.RG: return exports.FORMATS.RG_INTEGER; - case exports.FORMATS.RED: return exports.FORMATS.RED_INTEGER; - default: return format; - } - } - function parseKvData(dataView, bytesOfKeyValueData, littleEndian) { - var kvData = new Map(); - var bytesIntoKeyValueData = 0; - while (bytesIntoKeyValueData < bytesOfKeyValueData) { - var keyAndValueByteSize = dataView.getUint32(FILE_HEADER_SIZE + bytesIntoKeyValueData, littleEndian); - var keyAndValueByteOffset = FILE_HEADER_SIZE + bytesIntoKeyValueData + 4; - var valuePadding = 3 - ((keyAndValueByteSize + 3) % 4); - // Bounds check - if (keyAndValueByteSize === 0 || keyAndValueByteSize > bytesOfKeyValueData - bytesIntoKeyValueData) { - console.error('KTXLoader: keyAndValueByteSize out of bounds'); - break; - } - // Note: keyNulByte can't be 0 otherwise the key is an empty string. - var keyNulByte = 0; - for (; keyNulByte < keyAndValueByteSize; keyNulByte++) { - if (dataView.getUint8(keyAndValueByteOffset + keyNulByte) === 0x00) { - break; - } - } - if (keyNulByte === -1) { - console.error('KTXLoader: Failed to find null byte terminating kvData key'); - break; - } - var key = new TextDecoder().decode(new Uint8Array(dataView.buffer, keyAndValueByteOffset, keyNulByte)); - var value = new DataView(dataView.buffer, keyAndValueByteOffset + keyNulByte + 1, keyAndValueByteSize - keyNulByte - 1); - kvData.set(key, value); - // 4 = the keyAndValueByteSize field itself - // keyAndValueByteSize = the bytes taken by the key and value - // valuePadding = extra padding to align with 4 bytes - bytesIntoKeyValueData += 4 + keyAndValueByteSize + valuePadding; - } - return kvData; - } - - // Set DDS files to be loaded as an ArrayBuffer - exports.LoaderResource.setExtensionXhrType('dds', exports.LoaderResource.XHR_RESPONSE_TYPE.BUFFER); - /** - * @class - * @memberof PIXI - * @implements {PIXI.ILoaderPlugin} - * @see https://docs.microsoft.com/en-us/windows/win32/direct3ddds/dx-graphics-dds-pguide - */ - var DDSLoader = /** @class */ (function () { - function DDSLoader() { - } - /** - * Registers a DDS compressed texture - * @see PIXI.Loader.loaderMiddleware - * @param resource - loader resource that is checked to see if it is a DDS file - * @param next - callback Function to call when done - */ - DDSLoader.use = function (resource, next) { - if (resource.extension === 'dds' && resource.data) { - try { - Object.assign(resource, registerCompressedTextures(resource.name || resource.url, parseDDS(resource.data), resource.metadata)); - } - catch (err) { - next(err); - return; - } - } - next(); - }; - /** @ignore */ - DDSLoader.extension = exports.ExtensionType.Loader; - return DDSLoader; - }()); - - // Set KTX files to be loaded as an ArrayBuffer - exports.LoaderResource.setExtensionXhrType('ktx', exports.LoaderResource.XHR_RESPONSE_TYPE.BUFFER); - /** - * Loader plugin for handling KTX texture container files. - * - * This KTX loader does not currently support the following features: - * * cube textures - * * 3D textures - * * endianness conversion for big-endian machines - * * embedded *.basis files - * - * It does supports the following features: - * * multiple textures per file - * * mipmapping (only for compressed formats) - * * vendor-specific key/value data parsing (enable {@link PIXI.KTXLoader.loadKeyValueData}) - * @class - * @memberof PIXI - * @implements {PIXI.ILoaderPlugin} - */ - var KTXLoader = /** @class */ (function () { - function KTXLoader() { - } - /** - * Called after a KTX file is loaded. - * - * This will parse the KTX file header and add a {@code BaseTexture} to the texture - * cache. - * @see PIXI.Loader.loaderMiddleware - * @param resource - loader resource that is checked to see if it is a KTX file - * @param next - callback Function to call when done - */ - KTXLoader.use = function (resource, next) { - if (resource.extension === 'ktx' && resource.data) { - try { - var url_1 = resource.name || resource.url; - var _a = parseKTX(url_1, resource.data, this.loadKeyValueData), compressed = _a.compressed, uncompressed = _a.uncompressed, kvData_1 = _a.kvData; - if (compressed) { - var result = registerCompressedTextures(url_1, compressed, resource.metadata); - if (kvData_1 && result.textures) { - for (var textureId in result.textures) { - result.textures[textureId].baseTexture.ktxKeyValueData = kvData_1; - } - } - Object.assign(resource, result); - } - else if (uncompressed) { - var textures_1 = {}; - uncompressed.forEach(function (image, i) { - var texture = new Texture(new BaseTexture(image.resource, { - mipmap: exports.MIPMAP_MODES.OFF, - alphaMode: exports.ALPHA_MODES.NO_PREMULTIPLIED_ALPHA, - type: image.type, - format: image.format, - })); - var cacheID = url_1 + "-" + (i + 1); - if (kvData_1) - { texture.baseTexture.ktxKeyValueData = kvData_1; } - BaseTexture.addToCache(texture.baseTexture, cacheID); - Texture.addToCache(texture, cacheID); - if (i === 0) { - textures_1[url_1] = texture; - BaseTexture.addToCache(texture.baseTexture, url_1); - Texture.addToCache(texture, url_1); - } - textures_1[cacheID] = texture; - }); - Object.assign(resource, { textures: textures_1 }); - } - } - catch (err) { - next(err); - return; - } - } - next(); - }; - /** @ignore */ - KTXLoader.extension = exports.ExtensionType.Loader; - /** - * If set to `true`, {@link PIXI.KTXLoader} will parse key-value data in KTX textures. This feature relies - * on the [Encoding Standard]{@link https://encoding.spec.whatwg.org}. - * - * The key-value data will be available on the base-textures as {@code PIXI.BaseTexture.ktxKeyValueData}. They - * will hold a reference to the texture data buffer, so make sure to delete key-value data once you are done - * using it. - */ - KTXLoader.loadKeyValueData = false; - return KTXLoader; - }()); - - /*! - * @pixi/particle-container - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/particle-container is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$f = function(d, b) { - extendStatics$f = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$f(d, b); - }; - - function __extends$f(d, b) { - extendStatics$f(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** - * The ParticleContainer class is a really fast version of the Container built solely for speed, - * so use when you need a lot of sprites or particles. - * - * The tradeoff of the ParticleContainer is that most advanced functionality will not work. - * ParticleContainer implements the basic object transform (position, scale, rotation) - * and some advanced functionality like tint (as of v4.5.6). - * - * Other more advanced functionality like masking, children, filters, etc will not work on sprites in this batch. - * - * It's extremely easy to use: - * ```js - * let container = new ParticleContainer(); - * - * for (let i = 0; i < 100; ++i) - * { - * let sprite = PIXI.Sprite.from("myImage.png"); - * container.addChild(sprite); - * } - * ``` - * - * And here you have a hundred sprites that will be rendered at the speed of light. - * @memberof PIXI - */ - var ParticleContainer = /** @class */ (function (_super) { - __extends$f(ParticleContainer, _super); - /** - * @param maxSize - The maximum number of particles that can be rendered by the container. - * Affects size of allocated buffers. - * @param properties - The properties of children that should be uploaded to the gpu and applied. - * @param {boolean} [properties.vertices=false] - When true, vertices be uploaded and applied. - * if sprite's ` scale/anchor/trim/frame/orig` is dynamic, please set `true`. - * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. - * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. - * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. - * @param {boolean} [properties.tint=false] - When true, alpha and tint be uploaded and applied. - * @param {number} [batchSize=16384] - Number of particles per batch. If less than maxSize, it uses maxSize instead. - * @param {boolean} [autoResize=false] - If true, container allocates more batches in case - * there are more than `maxSize` particles. - */ - function ParticleContainer(maxSize, properties, batchSize, autoResize) { - if (maxSize === void 0) { maxSize = 1500; } - if (batchSize === void 0) { batchSize = 16384; } - if (autoResize === void 0) { autoResize = false; } - var _this = _super.call(this) || this; - // Making sure the batch size is valid - // 65535 is max vertex index in the index buffer (see ParticleRenderer) - // so max number of particles is 65536 / 4 = 16384 - var maxBatchSize = 16384; - if (batchSize > maxBatchSize) { - batchSize = maxBatchSize; - } - _this._properties = [false, true, false, false, false]; - _this._maxSize = maxSize; - _this._batchSize = batchSize; - _this._buffers = null; - _this._bufferUpdateIDs = []; - _this._updateID = 0; - _this.interactiveChildren = false; - _this.blendMode = exports.BLEND_MODES.NORMAL; - _this.autoResize = autoResize; - _this.roundPixels = true; - _this.baseTexture = null; - _this.setProperties(properties); - _this._tint = 0; - _this.tintRgb = new Float32Array(4); - _this.tint = 0xFFFFFF; - return _this; - } - /** - * Sets the private properties array to dynamic / static based on the passed properties object - * @param properties - The properties to be uploaded - */ - ParticleContainer.prototype.setProperties = function (properties) { - if (properties) { - this._properties[0] = 'vertices' in properties || 'scale' in properties - ? !!properties.vertices || !!properties.scale : this._properties[0]; - this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; - this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; - this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; - this._properties[4] = 'tint' in properties || 'alpha' in properties - ? !!properties.tint || !!properties.alpha : this._properties[4]; - } - }; - ParticleContainer.prototype.updateTransform = function () { - // TODO don't need to! - this.displayObjectUpdateTransform(); - }; - Object.defineProperty(ParticleContainer.prototype, "tint", { - /** - * The tint applied to the container. This is a hex value. - * A value of 0xFFFFFF will remove any tint effect. - * IMPORTANT: This is a WebGL only feature and will be ignored by the canvas renderer. - * @default 0xFFFFFF - */ - get: function () { - return this._tint; - }, - set: function (value) { - this._tint = value; - hex2rgb(value, this.tintRgb); - }, - enumerable: false, - configurable: true - }); - /** - * Renders the container using the WebGL renderer. - * @param renderer - The WebGL renderer. - */ - ParticleContainer.prototype.render = function (renderer) { - var _this = this; - if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { - return; - } - if (!this.baseTexture) { - this.baseTexture = this.children[0]._texture.baseTexture; - if (!this.baseTexture.valid) { - this.baseTexture.once('update', function () { return _this.onChildrenChange(0); }); - } - } - renderer.batch.setObjectRenderer(renderer.plugins.particle); - renderer.plugins.particle.render(this); - }; - /** - * Set the flag that static data should be updated to true - * @param smallestChildIndex - The smallest child index. - */ - ParticleContainer.prototype.onChildrenChange = function (smallestChildIndex) { - var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); - while (this._bufferUpdateIDs.length < bufferIndex) { - this._bufferUpdateIDs.push(0); - } - this._bufferUpdateIDs[bufferIndex] = ++this._updateID; - }; - ParticleContainer.prototype.dispose = function () { - if (this._buffers) { - for (var i = 0; i < this._buffers.length; ++i) { - this._buffers[i].destroy(); - } - this._buffers = null; - } - }; - /** - * Destroys the container - * @param options - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their - * destroy method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the texture of the child sprite - * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the base texture of the child sprite - */ - ParticleContainer.prototype.destroy = function (options) { - _super.prototype.destroy.call(this, options); - this.dispose(); - this._properties = null; - this._buffers = null; - this._bufferUpdateIDs = null; - }; - return ParticleContainer; - }(Container)); - - /* - * @author Mat Groves - * - * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ - * for creating the original PixiJS version! - * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that - * they now share 4 bytes on the vertex buffer - * - * Heavily inspired by LibGDX's ParticleBuffer: - * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java - */ - /** - * The particle buffer manages the static and dynamic buffers for a particle container. - * @private - * @memberof PIXI - */ - var ParticleBuffer = /** @class */ (function () { - /** - * @param {object} properties - The properties to upload. - * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. - * @param {number} size - The size of the batch. - */ - function ParticleBuffer(properties, dynamicPropertyFlags, size) { - this.geometry = new Geometry(); - this.indexBuffer = null; - this.size = size; - this.dynamicProperties = []; - this.staticProperties = []; - for (var i = 0; i < properties.length; ++i) { - var property = properties[i]; - // Make copy of properties object so that when we edit the offset it doesn't - // change all other instances of the object literal - property = { - attributeName: property.attributeName, - size: property.size, - uploadFunction: property.uploadFunction, - type: property.type || exports.TYPES.FLOAT, - offset: property.offset, - }; - if (dynamicPropertyFlags[i]) { - this.dynamicProperties.push(property); - } - else { - this.staticProperties.push(property); - } - } - this.staticStride = 0; - this.staticBuffer = null; - this.staticData = null; - this.staticDataUint32 = null; - this.dynamicStride = 0; - this.dynamicBuffer = null; - this.dynamicData = null; - this.dynamicDataUint32 = null; - this._updateID = 0; - this.initBuffers(); - } - /** Sets up the renderer context and necessary buffers. */ - ParticleBuffer.prototype.initBuffers = function () { - var geometry = this.geometry; - var dynamicOffset = 0; - this.indexBuffer = new Buffer(createIndicesForQuads(this.size), true, true); - geometry.addIndex(this.indexBuffer); - this.dynamicStride = 0; - for (var i = 0; i < this.dynamicProperties.length; ++i) { - var property = this.dynamicProperties[i]; - property.offset = dynamicOffset; - dynamicOffset += property.size; - this.dynamicStride += property.size; - } - var dynBuffer = new ArrayBuffer(this.size * this.dynamicStride * 4 * 4); - this.dynamicData = new Float32Array(dynBuffer); - this.dynamicDataUint32 = new Uint32Array(dynBuffer); - this.dynamicBuffer = new Buffer(this.dynamicData, false, false); - // static // - var staticOffset = 0; - this.staticStride = 0; - for (var i = 0; i < this.staticProperties.length; ++i) { - var property = this.staticProperties[i]; - property.offset = staticOffset; - staticOffset += property.size; - this.staticStride += property.size; - } - var statBuffer = new ArrayBuffer(this.size * this.staticStride * 4 * 4); - this.staticData = new Float32Array(statBuffer); - this.staticDataUint32 = new Uint32Array(statBuffer); - this.staticBuffer = new Buffer(this.staticData, true, false); - for (var i = 0; i < this.dynamicProperties.length; ++i) { - var property = this.dynamicProperties[i]; - geometry.addAttribute(property.attributeName, this.dynamicBuffer, 0, property.type === exports.TYPES.UNSIGNED_BYTE, property.type, this.dynamicStride * 4, property.offset * 4); - } - for (var i = 0; i < this.staticProperties.length; ++i) { - var property = this.staticProperties[i]; - geometry.addAttribute(property.attributeName, this.staticBuffer, 0, property.type === exports.TYPES.UNSIGNED_BYTE, property.type, this.staticStride * 4, property.offset * 4); - } - }; - /** - * Uploads the dynamic properties. - * @param children - The children to upload. - * @param startIndex - The index to start at. - * @param amount - The number to upload. - */ - ParticleBuffer.prototype.uploadDynamic = function (children, startIndex, amount) { - for (var i = 0; i < this.dynamicProperties.length; i++) { - var property = this.dynamicProperties[i]; - property.uploadFunction(children, startIndex, amount, property.type === exports.TYPES.UNSIGNED_BYTE ? this.dynamicDataUint32 : this.dynamicData, this.dynamicStride, property.offset); - } - this.dynamicBuffer._updateID++; - }; - /** - * Uploads the static properties. - * @param children - The children to upload. - * @param startIndex - The index to start at. - * @param amount - The number to upload. - */ - ParticleBuffer.prototype.uploadStatic = function (children, startIndex, amount) { - for (var i = 0; i < this.staticProperties.length; i++) { - var property = this.staticProperties[i]; - property.uploadFunction(children, startIndex, amount, property.type === exports.TYPES.UNSIGNED_BYTE ? this.staticDataUint32 : this.staticData, this.staticStride, property.offset); - } - this.staticBuffer._updateID++; - }; - /** Destroys the ParticleBuffer. */ - ParticleBuffer.prototype.destroy = function () { - this.indexBuffer = null; - this.dynamicProperties = null; - this.dynamicBuffer = null; - this.dynamicData = null; - this.dynamicDataUint32 = null; - this.staticProperties = null; - this.staticBuffer = null; - this.staticData = null; - this.staticDataUint32 = null; - // all buffers are destroyed inside geometry - this.geometry.destroy(); - }; - return ParticleBuffer; - }()); - - var fragment$6 = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n vec4 color = texture2D(uSampler, vTextureCoord) * vColor;\n gl_FragColor = color;\n}"; - - var vertex$3 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\n\nattribute vec2 aPositionCoord;\nattribute float aRotation;\n\nuniform mat3 translationMatrix;\nuniform vec4 uColor;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nvoid main(void){\n float x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);\n float y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);\n\n vec2 v = vec2(x, y);\n v = v + aPositionCoord;\n\n gl_Position = vec4((translationMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vColor = aColor * uColor;\n}\n"; - - /* - * @author Mat Groves - * - * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ - * for creating the original PixiJS version! - * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now - * share 4 bytes on the vertex buffer - * - * Heavily inspired by LibGDX's ParticleRenderer: - * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java - */ - /** - * Renderer for Particles that is designer for speed over feature set. - * @memberof PIXI - */ - var ParticleRenderer = /** @class */ (function (_super) { - __extends$f(ParticleRenderer, _super); - /** - * @param renderer - The renderer this sprite batch works for. - */ - function ParticleRenderer(renderer) { - var _this = _super.call(this, renderer) || this; - // 65535 is max vertex index in the index buffer (see ParticleRenderer) - // so max number of particles is 65536 / 4 = 16384 - // and max number of element in the index buffer is 16384 * 6 = 98304 - // Creating a full index buffer, overhead is 98304 * 2 = 196Ko - // let numIndices = 98304; - _this.shader = null; - _this.properties = null; - _this.tempMatrix = new Matrix(); - _this.properties = [ - // verticesData - { - attributeName: 'aVertexPosition', - size: 2, - uploadFunction: _this.uploadVertices, - offset: 0, - }, - // positionData - { - attributeName: 'aPositionCoord', - size: 2, - uploadFunction: _this.uploadPosition, - offset: 0, - }, - // rotationData - { - attributeName: 'aRotation', - size: 1, - uploadFunction: _this.uploadRotation, - offset: 0, - }, - // uvsData - { - attributeName: 'aTextureCoord', - size: 2, - uploadFunction: _this.uploadUvs, - offset: 0, - }, - // tintData - { - attributeName: 'aColor', - size: 1, - type: exports.TYPES.UNSIGNED_BYTE, - uploadFunction: _this.uploadTint, - offset: 0, - } ]; - _this.shader = Shader.from(vertex$3, fragment$6, {}); - _this.state = State.for2d(); - return _this; - } - /** - * Renders the particle container object. - * @param container - The container to render using this ParticleRenderer. - */ - ParticleRenderer.prototype.render = function (container) { - var children = container.children; - var maxSize = container._maxSize; - var batchSize = container._batchSize; - var renderer = this.renderer; - var totalChildren = children.length; - if (totalChildren === 0) { - return; - } - else if (totalChildren > maxSize && !container.autoResize) { - totalChildren = maxSize; - } - var buffers = container._buffers; - if (!buffers) { - buffers = container._buffers = this.generateBuffers(container); - } - var baseTexture = children[0]._texture.baseTexture; - var premultiplied = baseTexture.alphaMode > 0; - // if the uvs have not updated then no point rendering just yet! - this.state.blendMode = correctBlendMode(container.blendMode, premultiplied); - renderer.state.set(this.state); - var gl = renderer.gl; - var m = container.worldTransform.copyTo(this.tempMatrix); - m.prepend(renderer.globalUniforms.uniforms.projectionMatrix); - this.shader.uniforms.translationMatrix = m.toArray(true); - this.shader.uniforms.uColor = premultiplyRgba(container.tintRgb, container.worldAlpha, this.shader.uniforms.uColor, premultiplied); - this.shader.uniforms.uSampler = baseTexture; - this.renderer.shader.bind(this.shader); - var updateStatic = false; - // now lets upload and render the buffers.. - for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { - var amount = (totalChildren - i); - if (amount > batchSize) { - amount = batchSize; - } - if (j >= buffers.length) { - buffers.push(this._generateOneMoreBuffer(container)); - } - var buffer = buffers[j]; - // we always upload the dynamic - buffer.uploadDynamic(children, i, amount); - var bid = container._bufferUpdateIDs[j] || 0; - updateStatic = updateStatic || (buffer._updateID < bid); - // we only upload the static content when we have to! - if (updateStatic) { - buffer._updateID = container._updateID; - buffer.uploadStatic(children, i, amount); - } - // bind the buffer - renderer.geometry.bind(buffer.geometry); - gl.drawElements(gl.TRIANGLES, amount * 6, gl.UNSIGNED_SHORT, 0); - } - }; - /** - * Creates one particle buffer for each child in the container we want to render and updates internal properties. - * @param container - The container to render using this ParticleRenderer - * @returns - The buffers - */ - ParticleRenderer.prototype.generateBuffers = function (container) { - var buffers = []; - var size = container._maxSize; - var batchSize = container._batchSize; - var dynamicPropertyFlags = container._properties; - for (var i = 0; i < size; i += batchSize) { - buffers.push(new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize)); - } - return buffers; - }; - /** - * Creates one more particle buffer, because container has autoResize feature. - * @param container - The container to render using this ParticleRenderer - * @returns - The generated buffer - */ - ParticleRenderer.prototype._generateOneMoreBuffer = function (container) { - var batchSize = container._batchSize; - var dynamicPropertyFlags = container._properties; - return new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize); - }; - /** - * Uploads the vertices. - * @param children - the array of sprites to render - * @param startIndex - the index to start from in the children array - * @param amount - the amount of children that will have their vertices uploaded - * @param array - The vertices to upload. - * @param stride - Stride to use for iteration. - * @param offset - Offset to start at. - */ - ParticleRenderer.prototype.uploadVertices = function (children, startIndex, amount, array, stride, offset) { - var w0 = 0; - var w1 = 0; - var h0 = 0; - var h1 = 0; - for (var i = 0; i < amount; ++i) { - var sprite = children[startIndex + i]; - var texture = sprite._texture; - var sx = sprite.scale.x; - var sy = sprite.scale.y; - var trim = texture.trim; - var orig = texture.orig; - if (trim) { - // if the sprite is trimmed and is not a tilingsprite then we need to add the - // extra space before transforming the sprite coords.. - w1 = trim.x - (sprite.anchor.x * orig.width); - w0 = w1 + trim.width; - h1 = trim.y - (sprite.anchor.y * orig.height); - h0 = h1 + trim.height; - } - else { - w0 = (orig.width) * (1 - sprite.anchor.x); - w1 = (orig.width) * -sprite.anchor.x; - h0 = orig.height * (1 - sprite.anchor.y); - h1 = orig.height * -sprite.anchor.y; - } - array[offset] = w1 * sx; - array[offset + 1] = h1 * sy; - array[offset + stride] = w0 * sx; - array[offset + stride + 1] = h1 * sy; - array[offset + (stride * 2)] = w0 * sx; - array[offset + (stride * 2) + 1] = h0 * sy; - array[offset + (stride * 3)] = w1 * sx; - array[offset + (stride * 3) + 1] = h0 * sy; - offset += stride * 4; - } - }; - /** - * Uploads the position. - * @param children - the array of sprites to render - * @param startIndex - the index to start from in the children array - * @param amount - the amount of children that will have their positions uploaded - * @param array - The vertices to upload. - * @param stride - Stride to use for iteration. - * @param offset - Offset to start at. - */ - ParticleRenderer.prototype.uploadPosition = function (children, startIndex, amount, array, stride, offset) { - for (var i = 0; i < amount; i++) { - var spritePosition = children[startIndex + i].position; - array[offset] = spritePosition.x; - array[offset + 1] = spritePosition.y; - array[offset + stride] = spritePosition.x; - array[offset + stride + 1] = spritePosition.y; - array[offset + (stride * 2)] = spritePosition.x; - array[offset + (stride * 2) + 1] = spritePosition.y; - array[offset + (stride * 3)] = spritePosition.x; - array[offset + (stride * 3) + 1] = spritePosition.y; - offset += stride * 4; - } - }; - /** - * Uploads the rotation. - * @param children - the array of sprites to render - * @param startIndex - the index to start from in the children array - * @param amount - the amount of children that will have their rotation uploaded - * @param array - The vertices to upload. - * @param stride - Stride to use for iteration. - * @param offset - Offset to start at. - */ - ParticleRenderer.prototype.uploadRotation = function (children, startIndex, amount, array, stride, offset) { - for (var i = 0; i < amount; i++) { - var spriteRotation = children[startIndex + i].rotation; - array[offset] = spriteRotation; - array[offset + stride] = spriteRotation; - array[offset + (stride * 2)] = spriteRotation; - array[offset + (stride * 3)] = spriteRotation; - offset += stride * 4; - } - }; - /** - * Uploads the UVs. - * @param children - the array of sprites to render - * @param startIndex - the index to start from in the children array - * @param amount - the amount of children that will have their rotation uploaded - * @param array - The vertices to upload. - * @param stride - Stride to use for iteration. - * @param offset - Offset to start at. - */ - ParticleRenderer.prototype.uploadUvs = function (children, startIndex, amount, array, stride, offset) { - for (var i = 0; i < amount; ++i) { - var textureUvs = children[startIndex + i]._texture._uvs; - if (textureUvs) { - array[offset] = textureUvs.x0; - array[offset + 1] = textureUvs.y0; - array[offset + stride] = textureUvs.x1; - array[offset + stride + 1] = textureUvs.y1; - array[offset + (stride * 2)] = textureUvs.x2; - array[offset + (stride * 2) + 1] = textureUvs.y2; - array[offset + (stride * 3)] = textureUvs.x3; - array[offset + (stride * 3) + 1] = textureUvs.y3; - offset += stride * 4; - } - else { - // TODO you know this can be easier! - array[offset] = 0; - array[offset + 1] = 0; - array[offset + stride] = 0; - array[offset + stride + 1] = 0; - array[offset + (stride * 2)] = 0; - array[offset + (stride * 2) + 1] = 0; - array[offset + (stride * 3)] = 0; - array[offset + (stride * 3) + 1] = 0; - offset += stride * 4; - } - } - }; - /** - * Uploads the tint. - * @param children - the array of sprites to render - * @param startIndex - the index to start from in the children array - * @param amount - the amount of children that will have their rotation uploaded - * @param array - The vertices to upload. - * @param stride - Stride to use for iteration. - * @param offset - Offset to start at. - */ - ParticleRenderer.prototype.uploadTint = function (children, startIndex, amount, array, stride, offset) { - for (var i = 0; i < amount; ++i) { - var sprite = children[startIndex + i]; - var premultiplied = sprite._texture.baseTexture.alphaMode > 0; - var alpha = sprite.alpha; - // we dont call extra function if alpha is 1.0, that's faster - var argb = alpha < 1.0 && premultiplied - ? premultiplyTint(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); - array[offset] = argb; - array[offset + stride] = argb; - array[offset + (stride * 2)] = argb; - array[offset + (stride * 3)] = argb; - offset += stride * 4; - } - }; - /** Destroys the ParticleRenderer. */ - ParticleRenderer.prototype.destroy = function () { - _super.prototype.destroy.call(this); - if (this.shader) { - this.shader.destroy(); - this.shader = null; - } - this.tempMatrix = null; - }; - /** @ignore */ - ParticleRenderer.extension = { - name: 'particle', - type: exports.ExtensionType.RendererPlugin, - }; - return ParticleRenderer; - }(ObjectRenderer)); - - /*! - * @pixi/graphics - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/graphics is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Supported line joints in `PIXI.LineStyle` for graphics. - * @see PIXI.Graphics#lineStyle - * @see https://graphicdesign.stackexchange.com/questions/59018/what-is-a-bevel-join-of-two-lines-exactly-illustrator - * @name LINE_JOIN - * @memberof PIXI - * @static - * @enum {string} - * @property {string} MITER - 'miter': make a sharp corner where outer part of lines meet - * @property {string} BEVEL - 'bevel': add a square butt at each end of line segment and fill the triangle at turn - * @property {string} ROUND - 'round': add an arc at the joint - */ - exports.LINE_JOIN = void 0; - (function (LINE_JOIN) { - LINE_JOIN["MITER"] = "miter"; - LINE_JOIN["BEVEL"] = "bevel"; - LINE_JOIN["ROUND"] = "round"; - })(exports.LINE_JOIN || (exports.LINE_JOIN = {})); - /** - * Support line caps in `PIXI.LineStyle` for graphics. - * @see PIXI.Graphics#lineStyle - * @name LINE_CAP - * @memberof PIXI - * @static - * @enum {string} - * @property {string} BUTT - 'butt': don't add any cap at line ends (leaves orthogonal edges) - * @property {string} ROUND - 'round': add semicircle at ends - * @property {string} SQUARE - 'square': add square at end (like `BUTT` except more length at end) - */ - exports.LINE_CAP = void 0; - (function (LINE_CAP) { - LINE_CAP["BUTT"] = "butt"; - LINE_CAP["ROUND"] = "round"; - LINE_CAP["SQUARE"] = "square"; - })(exports.LINE_CAP || (exports.LINE_CAP = {})); - /** - * Graphics curves resolution settings. If `adaptive` flag is set to `true`, - * the resolution is calculated based on the curve's length to ensure better visual quality. - * Adaptive draw works with `bezierCurveTo` and `quadraticCurveTo`. - * @static - * @constant - * @memberof PIXI - * @name GRAPHICS_CURVES - * @type {object} - * @property {boolean} [adaptive=true] - flag indicating if the resolution should be adaptive - * @property {number} [maxLength=10] - maximal length of a single segment of the curve (if adaptive = false, ignored) - * @property {number} [minSegments=8] - minimal number of segments in the curve (if adaptive = false, ignored) - * @property {number} [maxSegments=2048] - maximal number of segments in the curve (if adaptive = false, ignored) - */ - var GRAPHICS_CURVES = { - adaptive: true, - maxLength: 10, - minSegments: 8, - maxSegments: 2048, - epsilon: 0.0001, - _segmentsCount: function (length, defaultSegments) { - if (defaultSegments === void 0) { defaultSegments = 20; } - if (!this.adaptive || !length || isNaN(length)) { - return defaultSegments; - } - var result = Math.ceil(length / this.maxLength); - if (result < this.minSegments) { - result = this.minSegments; - } - else if (result > this.maxSegments) { - result = this.maxSegments; - } - return result; - }, - }; - - /** - * Fill style object for Graphics. - * @memberof PIXI - */ - var FillStyle = /** @class */ (function () { - function FillStyle() { - /** - * The hex color value used when coloring the Graphics object. - * @default 0xFFFFFF - */ - this.color = 0xFFFFFF; - /** The alpha value used when filling the Graphics object. */ - this.alpha = 1.0; - /** - * The texture to be used for the fill. - * @default 0 - */ - this.texture = Texture.WHITE; - /** - * The transform applied to the texture. - * @default null - */ - this.matrix = null; - /** If the current fill is visible. */ - this.visible = false; - this.reset(); - } - /** Clones the object */ - FillStyle.prototype.clone = function () { - var obj = new FillStyle(); - obj.color = this.color; - obj.alpha = this.alpha; - obj.texture = this.texture; - obj.matrix = this.matrix; - obj.visible = this.visible; - return obj; - }; - /** Reset */ - FillStyle.prototype.reset = function () { - this.color = 0xFFFFFF; - this.alpha = 1; - this.texture = Texture.WHITE; - this.matrix = null; - this.visible = false; - }; - /** Destroy and don't use after this. */ - FillStyle.prototype.destroy = function () { - this.texture = null; - this.matrix = null; - }; - return FillStyle; - }()); - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$e = function(d, b) { - extendStatics$e = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$e(d, b); - }; - - function __extends$e(d, b) { - extendStatics$e(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - function fixOrientation(points, hole) { - var _a, _b; - if (hole === void 0) { hole = false; } - var m = points.length; - if (m < 6) { - return; - } - var area = 0; - for (var i = 0, x1 = points[m - 2], y1 = points[m - 1]; i < m; i += 2) { - var x2 = points[i]; - var y2 = points[i + 1]; - area += (x2 - x1) * (y2 + y1); - x1 = x2; - y1 = y2; - } - if ((!hole && area > 0) || (hole && area <= 0)) { - var n = m / 2; - for (var i = n + (n % 2); i < m; i += 2) { - var i1 = m - i - 2; - var i2 = m - i - 1; - var i3 = i; - var i4 = i + 1; - _a = [points[i3], points[i1]], points[i1] = _a[0], points[i3] = _a[1]; - _b = [points[i4], points[i2]], points[i2] = _b[0], points[i4] = _b[1]; - } - } - } - /** - * Builds a polygon to draw - * - * Ignored from docs since it is not directly exposed. - * @ignore - * @private - * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape - * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines - */ - var buildPoly = { - build: function (graphicsData) { - graphicsData.points = graphicsData.shape.points.slice(); - }, - triangulate: function (graphicsData, graphicsGeometry) { - var points = graphicsData.points; - var holes = graphicsData.holes; - var verts = graphicsGeometry.points; - var indices = graphicsGeometry.indices; - if (points.length >= 6) { - fixOrientation(points, false); - var holeArray = []; - // Process holes.. - for (var i = 0; i < holes.length; i++) { - var hole = holes[i]; - fixOrientation(hole.points, true); - holeArray.push(points.length / 2); - points = points.concat(hole.points); - } - // sort color - var triangles = earcut_1(points, holeArray, 2); - if (!triangles) { - return; - } - var vertPos = verts.length / 2; - for (var i = 0; i < triangles.length; i += 3) { - indices.push(triangles[i] + vertPos); - indices.push(triangles[i + 1] + vertPos); - indices.push(triangles[i + 2] + vertPos); - } - for (var i = 0; i < points.length; i++) { - verts.push(points[i]); - } - } - }, - }; - - // for type only - /** - * Builds a circle to draw - * - * Ignored from docs since it is not directly exposed. - * @ignore - * @private - * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw - * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape - * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines - */ - var buildCircle = { - build: function (graphicsData) { - // need to convert points to a nice regular data - var points = graphicsData.points; - var x; - var y; - var dx; - var dy; - var rx; - var ry; - if (graphicsData.type === exports.SHAPES.CIRC) { - var circle = graphicsData.shape; - x = circle.x; - y = circle.y; - rx = ry = circle.radius; - dx = dy = 0; - } - else if (graphicsData.type === exports.SHAPES.ELIP) { - var ellipse = graphicsData.shape; - x = ellipse.x; - y = ellipse.y; - rx = ellipse.width; - ry = ellipse.height; - dx = dy = 0; - } - else { - var roundedRect = graphicsData.shape; - var halfWidth = roundedRect.width / 2; - var halfHeight = roundedRect.height / 2; - x = roundedRect.x + halfWidth; - y = roundedRect.y + halfHeight; - rx = ry = Math.max(0, Math.min(roundedRect.radius, Math.min(halfWidth, halfHeight))); - dx = halfWidth - rx; - dy = halfHeight - ry; - } - if (!(rx >= 0 && ry >= 0 && dx >= 0 && dy >= 0)) { - points.length = 0; - return; - } - // Choose a number of segments such that the maximum absolute deviation from the circle is approximately 0.029 - var n = Math.ceil(2.3 * Math.sqrt(rx + ry)); - var m = (n * 8) + (dx ? 4 : 0) + (dy ? 4 : 0); - points.length = m; - if (m === 0) { - return; - } - if (n === 0) { - points.length = 8; - points[0] = points[6] = x + dx; - points[1] = points[3] = y + dy; - points[2] = points[4] = x - dx; - points[5] = points[7] = y - dy; - return; - } - var j1 = 0; - var j2 = (n * 4) + (dx ? 2 : 0) + 2; - var j3 = j2; - var j4 = m; - { - var x0 = dx + rx; - var y0 = dy; - var x1 = x + x0; - var x2 = x - x0; - var y1 = y + y0; - points[j1++] = x1; - points[j1++] = y1; - points[--j2] = y1; - points[--j2] = x2; - if (dy) { - var y2 = y - y0; - points[j3++] = x2; - points[j3++] = y2; - points[--j4] = y2; - points[--j4] = x1; - } - } - for (var i = 1; i < n; i++) { - var a = Math.PI / 2 * (i / n); - var x0 = dx + (Math.cos(a) * rx); - var y0 = dy + (Math.sin(a) * ry); - var x1 = x + x0; - var x2 = x - x0; - var y1 = y + y0; - var y2 = y - y0; - points[j1++] = x1; - points[j1++] = y1; - points[--j2] = y1; - points[--j2] = x2; - points[j3++] = x2; - points[j3++] = y2; - points[--j4] = y2; - points[--j4] = x1; - } - { - var x0 = dx; - var y0 = dy + ry; - var x1 = x + x0; - var x2 = x - x0; - var y1 = y + y0; - var y2 = y - y0; - points[j1++] = x1; - points[j1++] = y1; - points[--j4] = y2; - points[--j4] = x1; - if (dx) { - points[j1++] = x2; - points[j1++] = y1; - points[--j4] = y2; - points[--j4] = x2; - } - } - }, - triangulate: function (graphicsData, graphicsGeometry) { - var points = graphicsData.points; - var verts = graphicsGeometry.points; - var indices = graphicsGeometry.indices; - if (points.length === 0) { - return; - } - var vertPos = verts.length / 2; - var center = vertPos; - var x; - var y; - if (graphicsData.type !== exports.SHAPES.RREC) { - var circle = graphicsData.shape; - x = circle.x; - y = circle.y; - } - else { - var roundedRect = graphicsData.shape; - x = roundedRect.x + (roundedRect.width / 2); - y = roundedRect.y + (roundedRect.height / 2); - } - var matrix = graphicsData.matrix; - // Push center (special point) - verts.push(graphicsData.matrix ? (matrix.a * x) + (matrix.c * y) + matrix.tx : x, graphicsData.matrix ? (matrix.b * x) + (matrix.d * y) + matrix.ty : y); - vertPos++; - verts.push(points[0], points[1]); - for (var i = 2; i < points.length; i += 2) { - verts.push(points[i], points[i + 1]); - // add some uvs - indices.push(vertPos++, center, vertPos); - } - indices.push(center + 1, center, vertPos); - }, - }; - - /** - * Builds a rectangle to draw - * - * Ignored from docs since it is not directly exposed. - * @ignore - * @private - * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape - * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines - */ - var buildRectangle = { - build: function (graphicsData) { - // --- // - // need to convert points to a nice regular data - // - var rectData = graphicsData.shape; - var x = rectData.x; - var y = rectData.y; - var width = rectData.width; - var height = rectData.height; - var points = graphicsData.points; - points.length = 0; - points.push(x, y, x + width, y, x + width, y + height, x, y + height); - }, - triangulate: function (graphicsData, graphicsGeometry) { - var points = graphicsData.points; - var verts = graphicsGeometry.points; - var vertPos = verts.length / 2; - verts.push(points[0], points[1], points[2], points[3], points[6], points[7], points[4], points[5]); - graphicsGeometry.indices.push(vertPos, vertPos + 1, vertPos + 2, vertPos + 1, vertPos + 2, vertPos + 3); - }, - }; - - /** - * Calculate a single point for a quadratic bezier curve. - * Utility function used by quadraticBezierCurve. - * Ignored from docs since it is not directly exposed. - * @ignore - * @private - * @param {number} n1 - first number - * @param {number} n2 - second number - * @param {number} perc - percentage - * @returns {number} the result - */ - function getPt(n1, n2, perc) { - var diff = n2 - n1; - return n1 + (diff * perc); - } - /** - * Calculate the points for a quadratic bezier curve. (helper function..) - * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c - * - * Ignored from docs since it is not directly exposed. - * @ignore - * @private - * @param {number} fromX - Origin point x - * @param {number} fromY - Origin point x - * @param {number} cpX - Control point x - * @param {number} cpY - Control point y - * @param {number} toX - Destination point x - * @param {number} toY - Destination point y - * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. - * @returns {number[]} an array of points - */ - function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY, out) { - if (out === void 0) { out = []; } - var n = 20; - var points = out; - var xa = 0; - var ya = 0; - var xb = 0; - var yb = 0; - var x = 0; - var y = 0; - for (var i = 0, j = 0; i <= n; ++i) { - j = i / n; - // The Green Line - xa = getPt(fromX, cpX, j); - ya = getPt(fromY, cpY, j); - xb = getPt(cpX, toX, j); - yb = getPt(cpY, toY, j); - // The Black Dot - x = getPt(xa, xb, j); - y = getPt(ya, yb, j); - // Handle case when first curve points overlaps and earcut fails to triangulate - if (i === 0 && points[points.length - 2] === x && points[points.length - 1] === y) { - continue; - } - points.push(x, y); - } - return points; - } - /** - * Builds a rounded rectangle to draw - * - * Ignored from docs since it is not directly exposed. - * @ignore - * @private - * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape - * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines - */ - var buildRoundedRectangle = { - build: function (graphicsData) { - if (Graphics.nextRoundedRectBehavior) { - buildCircle.build(graphicsData); - return; - } - var rrectData = graphicsData.shape; - var points = graphicsData.points; - var x = rrectData.x; - var y = rrectData.y; - var width = rrectData.width; - var height = rrectData.height; - // Don't allow negative radius or greater than half the smallest width - var radius = Math.max(0, Math.min(rrectData.radius, Math.min(width, height) / 2)); - points.length = 0; - // No radius, do a simple rectangle - if (!radius) { - points.push(x, y, x + width, y, x + width, y + height, x, y + height); - } - else { - quadraticBezierCurve(x, y + radius, x, y, x + radius, y, points); - quadraticBezierCurve(x + width - radius, y, x + width, y, x + width, y + radius, points); - quadraticBezierCurve(x + width, y + height - radius, x + width, y + height, x + width - radius, y + height, points); - quadraticBezierCurve(x + radius, y + height, x, y + height, x, y + height - radius, points); - } - }, - triangulate: function (graphicsData, graphicsGeometry) { - if (Graphics.nextRoundedRectBehavior) { - buildCircle.triangulate(graphicsData, graphicsGeometry); - return; - } - var points = graphicsData.points; - var verts = graphicsGeometry.points; - var indices = graphicsGeometry.indices; - var vecPos = verts.length / 2; - var triangles = earcut_1(points, null, 2); - for (var i = 0, j = triangles.length; i < j; i += 3) { - indices.push(triangles[i] + vecPos); - // indices.push(triangles[i] + vecPos); - indices.push(triangles[i + 1] + vecPos); - // indices.push(triangles[i + 2] + vecPos); - indices.push(triangles[i + 2] + vecPos); - } - for (var i = 0, j = points.length; i < j; i++) { - verts.push(points[i], points[++i]); - } - }, - }; - - /** - * Buffers vertices to draw a square cap. - * - * Ignored from docs since it is not directly exposed. - * @ignore - * @private - * @param {number} x - X-coord of end point - * @param {number} y - Y-coord of end point - * @param {number} nx - X-coord of line normal pointing inside - * @param {number} ny - Y-coord of line normal pointing inside - * @param {number} innerWeight - Weight of inner points - * @param {number} outerWeight - Weight of outer points - * @param {boolean} clockwise - Whether the cap is drawn clockwise - * @param {Array} verts - vertex buffer - * @returns {number} - no. of vertices pushed - */ - function square(x, y, nx, ny, innerWeight, outerWeight, clockwise, /* rotation for square (true at left end, false at right end) */ verts) { - var ix = x - (nx * innerWeight); - var iy = y - (ny * innerWeight); - var ox = x + (nx * outerWeight); - var oy = y + (ny * outerWeight); - /* Rotate nx,ny for extension vector */ - var exx; - var eyy; - if (clockwise) { - exx = ny; - eyy = -nx; - } - else { - exx = -ny; - eyy = nx; - } - /* [i|0]x,y extended at cap */ - var eix = ix + exx; - var eiy = iy + eyy; - var eox = ox + exx; - var eoy = oy + eyy; - /* Square itself must be inserted clockwise*/ - verts.push(eix, eiy); - verts.push(eox, eoy); - return 2; - } - /** - * Buffers vertices to draw an arc at the line joint or cap. - * - * Ignored from docs since it is not directly exposed. - * @ignore - * @private - * @param {number} cx - X-coord of center - * @param {number} cy - Y-coord of center - * @param {number} sx - X-coord of arc start - * @param {number} sy - Y-coord of arc start - * @param {number} ex - X-coord of arc end - * @param {number} ey - Y-coord of arc end - * @param {Array} verts - buffer of vertices - * @param {boolean} clockwise - orientation of vertices - * @returns {number} - no. of vertices pushed - */ - function round(cx, cy, sx, sy, ex, ey, verts, clockwise) { - var cx2p0x = sx - cx; - var cy2p0y = sy - cy; - var angle0 = Math.atan2(cx2p0x, cy2p0y); - var angle1 = Math.atan2(ex - cx, ey - cy); - if (clockwise && angle0 < angle1) { - angle0 += Math.PI * 2; - } - else if (!clockwise && angle0 > angle1) { - angle1 += Math.PI * 2; - } - var startAngle = angle0; - var angleDiff = angle1 - angle0; - var absAngleDiff = Math.abs(angleDiff); - /* if (absAngleDiff >= PI_LBOUND && absAngleDiff <= PI_UBOUND) - { - const r1x = cx - nxtPx; - const r1y = cy - nxtPy; - - if (r1x === 0) - { - if (r1y > 0) - { - angleDiff = -angleDiff; - } - } - else if (r1x >= -GRAPHICS_CURVES.epsilon) - { - angleDiff = -angleDiff; - } - }*/ - var radius = Math.sqrt((cx2p0x * cx2p0x) + (cy2p0y * cy2p0y)); - var segCount = ((15 * absAngleDiff * Math.sqrt(radius) / Math.PI) >> 0) + 1; - var angleInc = angleDiff / segCount; - startAngle += angleInc; - if (clockwise) { - verts.push(cx, cy); - verts.push(sx, sy); - for (var i = 1, angle = startAngle; i < segCount; i++, angle += angleInc) { - verts.push(cx, cy); - verts.push(cx + ((Math.sin(angle) * radius)), cy + ((Math.cos(angle) * radius))); - } - verts.push(cx, cy); - verts.push(ex, ey); - } - else { - verts.push(sx, sy); - verts.push(cx, cy); - for (var i = 1, angle = startAngle; i < segCount; i++, angle += angleInc) { - verts.push(cx + ((Math.sin(angle) * radius)), cy + ((Math.cos(angle) * radius))); - verts.push(cx, cy); - } - verts.push(ex, ey); - verts.push(cx, cy); - } - return segCount * 2; - } - /** - * Builds a line to draw using the polygon method. - * - * Ignored from docs since it is not directly exposed. - * @ignore - * @private - * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output - */ - function buildNonNativeLine(graphicsData, graphicsGeometry) { - var shape = graphicsData.shape; - var points = graphicsData.points || shape.points.slice(); - var eps = graphicsGeometry.closePointEps; - if (points.length === 0) { - return; - } - // if the line width is an odd number add 0.5 to align to a whole pixel - // commenting this out fixes #711 and #1620 - // if (graphicsData.lineWidth%2) - // { - // for (i = 0; i < points.length; i++) - // { - // points[i] += 0.5; - // } - // } - var style = graphicsData.lineStyle; - // get first and last point.. figure out the middle! - var firstPoint = new Point(points[0], points[1]); - var lastPoint = new Point(points[points.length - 2], points[points.length - 1]); - var closedShape = shape.type !== exports.SHAPES.POLY || shape.closeStroke; - var closedPath = Math.abs(firstPoint.x - lastPoint.x) < eps - && Math.abs(firstPoint.y - lastPoint.y) < eps; - // if the first point is the last point - gonna have issues :) - if (closedShape) { - // need to clone as we are going to slightly modify the shape.. - points = points.slice(); - if (closedPath) { - points.pop(); - points.pop(); - lastPoint.set(points[points.length - 2], points[points.length - 1]); - } - var midPointX = (firstPoint.x + lastPoint.x) * 0.5; - var midPointY = (lastPoint.y + firstPoint.y) * 0.5; - points.unshift(midPointX, midPointY); - points.push(midPointX, midPointY); - } - var verts = graphicsGeometry.points; - var length = points.length / 2; - var indexCount = points.length; - var indexStart = verts.length / 2; - // Max. inner and outer width - var width = style.width / 2; - var widthSquared = width * width; - var miterLimitSquared = style.miterLimit * style.miterLimit; - /* Line segments of interest where (x1,y1) forms the corner. */ - var x0 = points[0]; - var y0 = points[1]; - var x1 = points[2]; - var y1 = points[3]; - var x2 = 0; - var y2 = 0; - /* perp[?](x|y) = the line normal with magnitude lineWidth. */ - var perpx = -(y0 - y1); - var perpy = x0 - x1; - var perp1x = 0; - var perp1y = 0; - var dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); - perpx /= dist; - perpy /= dist; - perpx *= width; - perpy *= width; - var ratio = style.alignment; // 0.5; - var innerWeight = (1 - ratio) * 2; - var outerWeight = ratio * 2; - if (!closedShape) { - if (style.cap === exports.LINE_CAP.ROUND) { - indexCount += round(x0 - (perpx * (innerWeight - outerWeight) * 0.5), y0 - (perpy * (innerWeight - outerWeight) * 0.5), x0 - (perpx * innerWeight), y0 - (perpy * innerWeight), x0 + (perpx * outerWeight), y0 + (perpy * outerWeight), verts, true) + 2; - } - else if (style.cap === exports.LINE_CAP.SQUARE) { - indexCount += square(x0, y0, perpx, perpy, innerWeight, outerWeight, true, verts); - } - } - // Push first point (below & above vertices) - verts.push(x0 - (perpx * innerWeight), y0 - (perpy * innerWeight)); - verts.push(x0 + (perpx * outerWeight), y0 + (perpy * outerWeight)); - for (var i = 1; i < length - 1; ++i) { - x0 = points[(i - 1) * 2]; - y0 = points[((i - 1) * 2) + 1]; - x1 = points[i * 2]; - y1 = points[(i * 2) + 1]; - x2 = points[(i + 1) * 2]; - y2 = points[((i + 1) * 2) + 1]; - perpx = -(y0 - y1); - perpy = x0 - x1; - dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); - perpx /= dist; - perpy /= dist; - perpx *= width; - perpy *= width; - perp1x = -(y1 - y2); - perp1y = x1 - x2; - dist = Math.sqrt((perp1x * perp1x) + (perp1y * perp1y)); - perp1x /= dist; - perp1y /= dist; - perp1x *= width; - perp1y *= width; - /* d[x|y](0|1) = the component displacement between points p(0,1|1,2) */ - var dx0 = x1 - x0; - var dy0 = y0 - y1; - var dx1 = x1 - x2; - var dy1 = y2 - y1; - /* +ve if internal angle < 90 degree, -ve if internal angle > 90 degree. */ - var dot = (dx0 * dx1) + (dy0 * dy1); - /* +ve if internal angle counterclockwise, -ve if internal angle clockwise. */ - var cross = (dy0 * dx1) - (dy1 * dx0); - var clockwise = (cross < 0); - /* Going nearly parallel? */ - /* atan(0.001) ~= 0.001 rad ~= 0.057 degree */ - if (Math.abs(cross) < 0.001 * Math.abs(dot)) { - verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); - verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); - /* 180 degree corner? */ - if (dot >= 0) { - if (style.join === exports.LINE_JOIN.ROUND) { - indexCount += round(x1, y1, x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight), verts, false) + 4; - } - else { - indexCount += 2; - } - verts.push(x1 - (perp1x * outerWeight), y1 - (perp1y * outerWeight)); - verts.push(x1 + (perp1x * innerWeight), y1 + (perp1y * innerWeight)); - } - continue; - } - /* p[x|y] is the miter point. pdist is the distance between miter point and p1. */ - var c1 = ((-perpx + x0) * (-perpy + y1)) - ((-perpx + x1) * (-perpy + y0)); - var c2 = ((-perp1x + x2) * (-perp1y + y1)) - ((-perp1x + x1) * (-perp1y + y2)); - var px = ((dx0 * c2) - (dx1 * c1)) / cross; - var py = ((dy1 * c1) - (dy0 * c2)) / cross; - var pdist = ((px - x1) * (px - x1)) + ((py - y1) * (py - y1)); - /* Inner miter point */ - var imx = x1 + ((px - x1) * innerWeight); - var imy = y1 + ((py - y1) * innerWeight); - /* Outer miter point */ - var omx = x1 - ((px - x1) * outerWeight); - var omy = y1 - ((py - y1) * outerWeight); - /* Is the inside miter point too far away, creating a spike? */ - var smallerInsideSegmentSq = Math.min((dx0 * dx0) + (dy0 * dy0), (dx1 * dx1) + (dy1 * dy1)); - var insideWeight = clockwise ? innerWeight : outerWeight; - var smallerInsideDiagonalSq = smallerInsideSegmentSq + (insideWeight * insideWeight * widthSquared); - var insideMiterOk = pdist <= smallerInsideDiagonalSq; - if (insideMiterOk) { - if (style.join === exports.LINE_JOIN.BEVEL || pdist / widthSquared > miterLimitSquared) { - if (clockwise) /* rotating at inner angle */ { - verts.push(imx, imy); // inner miter point - verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); // first segment's outer vertex - verts.push(imx, imy); // inner miter point - verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); // second segment's outer vertex - } - else /* rotating at outer angle */ { - verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); // first segment's inner vertex - verts.push(omx, omy); // outer miter point - verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); // second segment's outer vertex - verts.push(omx, omy); // outer miter point - } - indexCount += 2; - } - else if (style.join === exports.LINE_JOIN.ROUND) { - if (clockwise) /* arc is outside */ { - verts.push(imx, imy); - verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); - indexCount += round(x1, y1, x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight), verts, true) + 4; - verts.push(imx, imy); - verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); - } - else /* arc is inside */ { - verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); - verts.push(omx, omy); - indexCount += round(x1, y1, x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight), verts, false) + 4; - verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); - verts.push(omx, omy); - } - } - else { - verts.push(imx, imy); - verts.push(omx, omy); - } - } - else // inside miter is NOT ok - { - verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); // first segment's inner vertex - verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); // first segment's outer vertex - if (style.join === exports.LINE_JOIN.ROUND) { - if (clockwise) /* arc is outside */ { - indexCount += round(x1, y1, x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight), verts, true) + 2; - } - else /* arc is inside */ { - indexCount += round(x1, y1, x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight), verts, false) + 2; - } - } - else if (style.join === exports.LINE_JOIN.MITER && pdist / widthSquared <= miterLimitSquared) { - if (clockwise) { - verts.push(omx, omy); // inner miter point - verts.push(omx, omy); // inner miter point - } - else { - verts.push(imx, imy); // outer miter point - verts.push(imx, imy); // outer miter point - } - indexCount += 2; - } - verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); // second segment's inner vertex - verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); // second segment's outer vertex - indexCount += 2; - } - } - x0 = points[(length - 2) * 2]; - y0 = points[((length - 2) * 2) + 1]; - x1 = points[(length - 1) * 2]; - y1 = points[((length - 1) * 2) + 1]; - perpx = -(y0 - y1); - perpy = x0 - x1; - dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); - perpx /= dist; - perpy /= dist; - perpx *= width; - perpy *= width; - verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); - verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); - if (!closedShape) { - if (style.cap === exports.LINE_CAP.ROUND) { - indexCount += round(x1 - (perpx * (innerWeight - outerWeight) * 0.5), y1 - (perpy * (innerWeight - outerWeight) * 0.5), x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), verts, false) + 2; - } - else if (style.cap === exports.LINE_CAP.SQUARE) { - indexCount += square(x1, y1, perpx, perpy, innerWeight, outerWeight, false, verts); - } - } - var indices = graphicsGeometry.indices; - var eps2 = GRAPHICS_CURVES.epsilon * GRAPHICS_CURVES.epsilon; - // indices.push(indexStart); - for (var i = indexStart; i < indexCount + indexStart - 2; ++i) { - x0 = verts[(i * 2)]; - y0 = verts[(i * 2) + 1]; - x1 = verts[(i + 1) * 2]; - y1 = verts[((i + 1) * 2) + 1]; - x2 = verts[(i + 2) * 2]; - y2 = verts[((i + 2) * 2) + 1]; - /* Skip zero area triangles */ - if (Math.abs((x0 * (y1 - y2)) + (x1 * (y2 - y0)) + (x2 * (y0 - y1))) < eps2) { - continue; - } - indices.push(i, i + 1, i + 2); - } - } - /** - * Builds a line to draw using the gl.drawArrays(gl.LINES) method - * - * Ignored from docs since it is not directly exposed. - * @ignore - * @private - * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output - */ - function buildNativeLine(graphicsData, graphicsGeometry) { - var i = 0; - var shape = graphicsData.shape; - var points = graphicsData.points || shape.points; - var closedShape = shape.type !== exports.SHAPES.POLY || shape.closeStroke; - if (points.length === 0) - { return; } - var verts = graphicsGeometry.points; - var indices = graphicsGeometry.indices; - var length = points.length / 2; - var startIndex = verts.length / 2; - var currentIndex = startIndex; - verts.push(points[0], points[1]); - for (i = 1; i < length; i++) { - verts.push(points[i * 2], points[(i * 2) + 1]); - indices.push(currentIndex, currentIndex + 1); - currentIndex++; - } - if (closedShape) { - indices.push(currentIndex, startIndex); - } - } - /** - * Builds a line to draw - * - * Ignored from docs since it is not directly exposed. - * @ignore - * @private - * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output - */ - function buildLine(graphicsData, graphicsGeometry) { - if (graphicsData.lineStyle.native) { - buildNativeLine(graphicsData, graphicsGeometry); - } - else { - buildNonNativeLine(graphicsData, graphicsGeometry); - } - } - - /** - * Utilities for arc curves. - * @private - */ - var ArcUtils = /** @class */ (function () { - function ArcUtils() { - } - /** - * The arcTo() method creates an arc/curve between two tangents on the canvas. - * - * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! - * @private - * @param x1 - The x-coordinate of the beginning of the arc - * @param y1 - The y-coordinate of the beginning of the arc - * @param x2 - The x-coordinate of the end of the arc - * @param y2 - The y-coordinate of the end of the arc - * @param radius - The radius of the arc - * @param points - - * @returns - If the arc length is valid, return center of circle, radius and other info otherwise `null`. - */ - ArcUtils.curveTo = function (x1, y1, x2, y2, radius, points) { - var fromX = points[points.length - 2]; - var fromY = points[points.length - 1]; - var a1 = fromY - y1; - var b1 = fromX - x1; - var a2 = y2 - y1; - var b2 = x2 - x1; - var mm = Math.abs((a1 * b2) - (b1 * a2)); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { - points.push(x1, y1); - } - return null; - } - var dd = (a1 * a1) + (b1 * b1); - var cc = (a2 * a2) + (b2 * b2); - var tt = (a1 * a2) + (b1 * b2); - var k1 = radius * Math.sqrt(dd) / mm; - var k2 = radius * Math.sqrt(cc) / mm; - var j1 = k1 * tt / dd; - var j2 = k2 * tt / cc; - var cx = (k1 * b2) + (k2 * b1); - var cy = (k1 * a2) + (k2 * a1); - var px = b1 * (k2 + j1); - var py = a1 * (k2 + j1); - var qx = b2 * (k1 + j2); - var qy = a2 * (k1 + j2); - var startAngle = Math.atan2(py - cy, px - cx); - var endAngle = Math.atan2(qy - cy, qx - cx); - return { - cx: (cx + x1), - cy: (cy + y1), - radius: radius, - startAngle: startAngle, - endAngle: endAngle, - anticlockwise: (b1 * a2 > b2 * a1), - }; - }; - /* eslint-disable max-len */ - /** - * The arc method creates an arc/curve (used to create circles, or parts of circles). - * @private - * @param _startX - Start x location of arc - * @param _startY - Start y location of arc - * @param cx - The x-coordinate of the center of the circle - * @param cy - The y-coordinate of the center of the circle - * @param radius - The radius of the circle - * @param startAngle - The starting angle, in radians (0 is at the 3 o'clock position - * of the arc's circle) - * @param endAngle - The ending angle, in radians - * @param _anticlockwise - Specifies whether the drawing should be - * counter-clockwise or clockwise. False is default, and indicates clockwise, while true - * indicates counter-clockwise. - * @param points - Collection of points to add to - */ - ArcUtils.arc = function (_startX, _startY, cx, cy, radius, startAngle, endAngle, _anticlockwise, points) { - var sweep = endAngle - startAngle; - var n = GRAPHICS_CURVES._segmentsCount(Math.abs(sweep) * radius, Math.ceil(Math.abs(sweep) / PI_2) * 40); - var theta = (sweep) / (n * 2); - var theta2 = theta * 2; - var cTheta = Math.cos(theta); - var sTheta = Math.sin(theta); - var segMinus = n - 1; - var remainder = (segMinus % 1) / segMinus; - for (var i = 0; i <= segMinus; ++i) { - var real = i + (remainder * i); - var angle = ((theta) + startAngle + (theta2 * real)); - var c = Math.cos(angle); - var s = -Math.sin(angle); - points.push((((cTheta * c) + (sTheta * s)) * radius) + cx, (((cTheta * -s) + (sTheta * c)) * radius) + cy); - } - }; - return ArcUtils; - }()); - - /** - * Utilities for bezier curves - * @private - */ - var BezierUtils = /** @class */ (function () { - function BezierUtils() { - } - /** - * Calculate length of bezier curve. - * Analytical solution is impossible, since it involves an integral that does not integrate in general. - * Therefore numerical solution is used. - * @private - * @param fromX - Starting point x - * @param fromY - Starting point y - * @param cpX - Control point x - * @param cpY - Control point y - * @param cpX2 - Second Control point x - * @param cpY2 - Second Control point y - * @param toX - Destination point x - * @param toY - Destination point y - * @returns - Length of bezier curve - */ - BezierUtils.curveLength = function (fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { - var n = 10; - var result = 0.0; - var t = 0.0; - var t2 = 0.0; - var t3 = 0.0; - var nt = 0.0; - var nt2 = 0.0; - var nt3 = 0.0; - var x = 0.0; - var y = 0.0; - var dx = 0.0; - var dy = 0.0; - var prevX = fromX; - var prevY = fromY; - for (var i = 1; i <= n; ++i) { - t = i / n; - t2 = t * t; - t3 = t2 * t; - nt = (1.0 - t); - nt2 = nt * nt; - nt3 = nt2 * nt; - x = (nt3 * fromX) + (3.0 * nt2 * t * cpX) + (3.0 * nt * t2 * cpX2) + (t3 * toX); - y = (nt3 * fromY) + (3.0 * nt2 * t * cpY) + (3 * nt * t2 * cpY2) + (t3 * toY); - dx = prevX - x; - dy = prevY - y; - prevX = x; - prevY = y; - result += Math.sqrt((dx * dx) + (dy * dy)); - } - return result; - }; - /** - * Calculate the points for a bezier curve and then draws it. - * - * Ignored from docs since it is not directly exposed. - * @ignore - * @param cpX - Control point x - * @param cpY - Control point y - * @param cpX2 - Second Control point x - * @param cpY2 - Second Control point y - * @param toX - Destination point x - * @param toY - Destination point y - * @param points - Path array to push points into - */ - BezierUtils.curveTo = function (cpX, cpY, cpX2, cpY2, toX, toY, points) { - var fromX = points[points.length - 2]; - var fromY = points[points.length - 1]; - points.length -= 2; - var n = GRAPHICS_CURVES._segmentsCount(BezierUtils.curveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY)); - var dt = 0; - var dt2 = 0; - var dt3 = 0; - var t2 = 0; - var t3 = 0; - points.push(fromX, fromY); - for (var i = 1, j = 0; i <= n; ++i) { - j = i / n; - dt = (1 - j); - dt2 = dt * dt; - dt3 = dt2 * dt; - t2 = j * j; - t3 = t2 * j; - points.push((dt3 * fromX) + (3 * dt2 * j * cpX) + (3 * dt * t2 * cpX2) + (t3 * toX), (dt3 * fromY) + (3 * dt2 * j * cpY) + (3 * dt * t2 * cpY2) + (t3 * toY)); - } - }; - return BezierUtils; - }()); - - /** - * Utilities for quadratic curves. - * @private - */ - var QuadraticUtils = /** @class */ (function () { - function QuadraticUtils() { - } - /** - * Calculate length of quadratic curve - * @see {@link http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/} - * for the detailed explanation of math behind this. - * @private - * @param fromX - x-coordinate of curve start point - * @param fromY - y-coordinate of curve start point - * @param cpX - x-coordinate of curve control point - * @param cpY - y-coordinate of curve control point - * @param toX - x-coordinate of curve end point - * @param toY - y-coordinate of curve end point - * @returns - Length of quadratic curve - */ - QuadraticUtils.curveLength = function (fromX, fromY, cpX, cpY, toX, toY) { - var ax = fromX - (2.0 * cpX) + toX; - var ay = fromY - (2.0 * cpY) + toY; - var bx = (2.0 * cpX) - (2.0 * fromX); - var by = (2.0 * cpY) - (2.0 * fromY); - var a = 4.0 * ((ax * ax) + (ay * ay)); - var b = 4.0 * ((ax * bx) + (ay * by)); - var c = (bx * bx) + (by * by); - var s = 2.0 * Math.sqrt(a + b + c); - var a2 = Math.sqrt(a); - var a32 = 2.0 * a * a2; - var c2 = 2.0 * Math.sqrt(c); - var ba = b / a2; - return ((a32 * s) - + (a2 * b * (s - c2)) - + (((4.0 * c * a) - (b * b)) - * Math.log(((2.0 * a2) + ba + s) / (ba + c2)))) / (4.0 * a32); - }; - /** - * Calculate the points for a quadratic bezier curve and then draws it. - * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c - * @private - * @param cpX - Control point x - * @param cpY - Control point y - * @param toX - Destination point x - * @param toY - Destination point y - * @param points - Points to add segments to. - */ - QuadraticUtils.curveTo = function (cpX, cpY, toX, toY, points) { - var fromX = points[points.length - 2]; - var fromY = points[points.length - 1]; - var n = GRAPHICS_CURVES._segmentsCount(QuadraticUtils.curveLength(fromX, fromY, cpX, cpY, toX, toY)); - var xa = 0; - var ya = 0; - for (var i = 1; i <= n; ++i) { - var j = i / n; - xa = fromX + ((cpX - fromX) * j); - ya = fromY + ((cpY - fromY) * j); - points.push(xa + (((cpX + ((toX - cpX) * j)) - xa) * j), ya + (((cpY + ((toY - cpY) * j)) - ya) * j)); - } - }; - return QuadraticUtils; - }()); - - /** - * A structure to hold interim batch objects for Graphics. - * @memberof PIXI.graphicsUtils - */ - var BatchPart = /** @class */ (function () { - function BatchPart() { - this.reset(); - } - /** - * Begin batch part. - * @param style - * @param startIndex - * @param attribStart - */ - BatchPart.prototype.begin = function (style, startIndex, attribStart) { - this.reset(); - this.style = style; - this.start = startIndex; - this.attribStart = attribStart; - }; - /** - * End batch part. - * @param endIndex - * @param endAttrib - */ - BatchPart.prototype.end = function (endIndex, endAttrib) { - this.attribSize = endAttrib - this.attribStart; - this.size = endIndex - this.start; - }; - BatchPart.prototype.reset = function () { - this.style = null; - this.size = 0; - this.start = 0; - this.attribStart = 0; - this.attribSize = 0; - }; - return BatchPart; - }()); - - /** - * Generalized convenience utilities for Graphics. - * @namespace graphicsUtils - * @memberof PIXI - */ - var _a; - /** - * Map of fill commands for each shape type. - * @memberof PIXI.graphicsUtils - * @member {object} FILL_COMMANDS - */ - var FILL_COMMANDS = (_a = {}, - _a[exports.SHAPES.POLY] = buildPoly, - _a[exports.SHAPES.CIRC] = buildCircle, - _a[exports.SHAPES.ELIP] = buildCircle, - _a[exports.SHAPES.RECT] = buildRectangle, - _a[exports.SHAPES.RREC] = buildRoundedRectangle, - _a); - /** - * Batch pool, stores unused batches for preventing allocations. - * @memberof PIXI.graphicsUtils - * @member {Array} BATCH_POOL - */ - var BATCH_POOL = []; - /** - * Draw call pool, stores unused draw calls for preventing allocations. - * @memberof PIXI.graphicsUtils - * @member {Array} DRAW_CALL_POOL - */ - var DRAW_CALL_POOL = []; - - /** - * A class to contain data useful for Graphics objects - * @memberof PIXI - */ - var GraphicsData = /** @class */ (function () { - /** - * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. - * @param fillStyle - the width of the line to draw - * @param lineStyle - the color of the line to draw - * @param matrix - Transform matrix - */ - function GraphicsData(shape, fillStyle, lineStyle, matrix) { - if (fillStyle === void 0) { fillStyle = null; } - if (lineStyle === void 0) { lineStyle = null; } - if (matrix === void 0) { matrix = null; } - /** The collection of points. */ - this.points = []; - /** The collection of holes. */ - this.holes = []; - this.shape = shape; - this.lineStyle = lineStyle; - this.fillStyle = fillStyle; - this.matrix = matrix; - this.type = shape.type; - } - /** - * Creates a new GraphicsData object with the same values as this one. - * @returns - Cloned GraphicsData object - */ - GraphicsData.prototype.clone = function () { - return new GraphicsData(this.shape, this.fillStyle, this.lineStyle, this.matrix); - }; - /** Destroys the Graphics data. */ - GraphicsData.prototype.destroy = function () { - this.shape = null; - this.holes.length = 0; - this.holes = null; - this.points.length = 0; - this.points = null; - this.lineStyle = null; - this.fillStyle = null; - }; - return GraphicsData; - }()); - - var tmpPoint = new Point(); - /** - * The Graphics class contains methods used to draw primitive shapes such as lines, circles and - * rectangles to the display, and to color and fill them. - * - * GraphicsGeometry is designed to not be continually updating the geometry since it's expensive - * to re-tesselate using **earcut**. Consider using {@link PIXI.Mesh} for this use-case, it's much faster. - * @memberof PIXI - */ - var GraphicsGeometry = /** @class */ (function (_super) { - __extends$e(GraphicsGeometry, _super); - // eslint-disable-next-line @typescript-eslint/no-useless-constructor - function GraphicsGeometry() { - var _this = _super.call(this) || this; - /** Minimal distance between points that are considered different. Affects line tesselation. */ - _this.closePointEps = 1e-4; - /** Padding to add to the bounds. */ - _this.boundsPadding = 0; - _this.uvsFloat32 = null; - _this.indicesUint16 = null; - _this.batchable = false; - /** An array of points to draw, 2 numbers per point */ - _this.points = []; - /** The collection of colors */ - _this.colors = []; - /** The UVs collection */ - _this.uvs = []; - /** The indices of the vertices */ - _this.indices = []; - /** Reference to the texture IDs. */ - _this.textureIds = []; - /** - * The collection of drawn shapes. - * @member {PIXI.GraphicsData[]} - */ - _this.graphicsData = []; - /** - * List of current draw calls drived from the batches. - * @member {PIXI.BatchDrawCall[]} - */ - _this.drawCalls = []; - /** Batches need to regenerated if the geometry is updated. */ - _this.batchDirty = -1; - /** - * Intermediate abstract format sent to batch system. - * Can be converted to drawCalls or to batchable objects. - * @member {PIXI.graphicsUtils.BatchPart[]} - */ - _this.batches = []; - /** Used to detect if the graphics object has changed. */ - _this.dirty = 0; - /** Used to check if the cache is dirty. */ - _this.cacheDirty = -1; - /** Used to detect if we cleared the graphicsData. */ - _this.clearDirty = 0; - /** Index of the last batched shape in the stack of calls. */ - _this.shapeIndex = 0; - /** Cached bounds. */ - _this._bounds = new Bounds(); - /** The bounds dirty flag. */ - _this.boundsDirty = -1; - return _this; - } - Object.defineProperty(GraphicsGeometry.prototype, "bounds", { - /** - * Get the current bounds of the graphic geometry. - * @readonly - */ - get: function () { - this.updateBatches(); - if (this.boundsDirty !== this.dirty) { - this.boundsDirty = this.dirty; - this.calculateBounds(); - } - return this._bounds; - }, - enumerable: false, - configurable: true - }); - /** Call if you changed graphicsData manually. Empties all batch buffers. */ - GraphicsGeometry.prototype.invalidate = function () { - this.boundsDirty = -1; - this.dirty++; - this.batchDirty++; - this.shapeIndex = 0; - this.points.length = 0; - this.colors.length = 0; - this.uvs.length = 0; - this.indices.length = 0; - this.textureIds.length = 0; - for (var i = 0; i < this.drawCalls.length; i++) { - this.drawCalls[i].texArray.clear(); - DRAW_CALL_POOL.push(this.drawCalls[i]); - } - this.drawCalls.length = 0; - for (var i = 0; i < this.batches.length; i++) { - var batchPart = this.batches[i]; - batchPart.reset(); - BATCH_POOL.push(batchPart); - } - this.batches.length = 0; - }; - /** - * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. - * @returns - This GraphicsGeometry object. Good for chaining method calls - */ - GraphicsGeometry.prototype.clear = function () { - if (this.graphicsData.length > 0) { - this.invalidate(); - this.clearDirty++; - this.graphicsData.length = 0; - } - return this; - }; - /** - * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. - * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. - * @param fillStyle - Defines style of the fill. - * @param lineStyle - Defines style of the lines. - * @param matrix - Transform applied to the points of the shape. - * @returns - Returns geometry for chaining. - */ - GraphicsGeometry.prototype.drawShape = function (shape, fillStyle, lineStyle, matrix) { - if (fillStyle === void 0) { fillStyle = null; } - if (lineStyle === void 0) { lineStyle = null; } - if (matrix === void 0) { matrix = null; } - var data = new GraphicsData(shape, fillStyle, lineStyle, matrix); - this.graphicsData.push(data); - this.dirty++; - return this; - }; - /** - * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. - * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. - * @param matrix - Transform applied to the points of the shape. - * @returns - Returns geometry for chaining. - */ - GraphicsGeometry.prototype.drawHole = function (shape, matrix) { - if (matrix === void 0) { matrix = null; } - if (!this.graphicsData.length) { - return null; - } - var data = new GraphicsData(shape, null, null, matrix); - var lastShape = this.graphicsData[this.graphicsData.length - 1]; - data.lineStyle = lastShape.lineStyle; - lastShape.holes.push(data); - this.dirty++; - return this; - }; - /** Destroys the GraphicsGeometry object. */ - GraphicsGeometry.prototype.destroy = function () { - _super.prototype.destroy.call(this); - // destroy each of the GraphicsData objects - for (var i = 0; i < this.graphicsData.length; ++i) { - this.graphicsData[i].destroy(); - } - this.points.length = 0; - this.points = null; - this.colors.length = 0; - this.colors = null; - this.uvs.length = 0; - this.uvs = null; - this.indices.length = 0; - this.indices = null; - this.indexBuffer.destroy(); - this.indexBuffer = null; - this.graphicsData.length = 0; - this.graphicsData = null; - this.drawCalls.length = 0; - this.drawCalls = null; - this.batches.length = 0; - this.batches = null; - this._bounds = null; - }; - /** - * Check to see if a point is contained within this geometry. - * @param point - Point to check if it's contained. - * @returns {boolean} `true` if the point is contained within geometry. - */ - GraphicsGeometry.prototype.containsPoint = function (point) { - var graphicsData = this.graphicsData; - for (var i = 0; i < graphicsData.length; ++i) { - var data = graphicsData[i]; - if (!data.fillStyle.visible) { - continue; - } - // only deal with fills.. - if (data.shape) { - if (data.matrix) { - data.matrix.applyInverse(point, tmpPoint); - } - else { - tmpPoint.copyFrom(point); - } - if (data.shape.contains(tmpPoint.x, tmpPoint.y)) { - var hitHole = false; - if (data.holes) { - for (var i_1 = 0; i_1 < data.holes.length; i_1++) { - var hole = data.holes[i_1]; - if (hole.shape.contains(tmpPoint.x, tmpPoint.y)) { - hitHole = true; - break; - } - } - } - if (!hitHole) { - return true; - } - } - } - } - return false; - }; - /** - * Generates intermediate batch data. Either gets converted to drawCalls - * or used to convert to batch objects directly by the Graphics object. - */ - GraphicsGeometry.prototype.updateBatches = function () { - if (!this.graphicsData.length) { - this.batchable = true; - return; - } - if (!this.validateBatching()) { - return; - } - this.cacheDirty = this.dirty; - var uvs = this.uvs; - var graphicsData = this.graphicsData; - var batchPart = null; - var currentStyle = null; - if (this.batches.length > 0) { - batchPart = this.batches[this.batches.length - 1]; - currentStyle = batchPart.style; - } - for (var i = this.shapeIndex; i < graphicsData.length; i++) { - this.shapeIndex++; - var data = graphicsData[i]; - var fillStyle = data.fillStyle; - var lineStyle = data.lineStyle; - var command = FILL_COMMANDS[data.type]; - // build out the shapes points.. - command.build(data); - if (data.matrix) { - this.transformPoints(data.points, data.matrix); - } - if (fillStyle.visible || lineStyle.visible) { - this.processHoles(data.holes); - } - for (var j = 0; j < 2; j++) { - var style = (j === 0) ? fillStyle : lineStyle; - if (!style.visible) - { continue; } - var nextTexture = style.texture.baseTexture; - var index_1 = this.indices.length; - var attribIndex = this.points.length / 2; - nextTexture.wrapMode = exports.WRAP_MODES.REPEAT; - if (j === 0) { - this.processFill(data); - } - else { - this.processLine(data); - } - var size = (this.points.length / 2) - attribIndex; - if (size === 0) - { continue; } - // close batch if style is different - if (batchPart && !this._compareStyles(currentStyle, style)) { - batchPart.end(index_1, attribIndex); - batchPart = null; - } - // spawn new batch if its first batch or previous was closed - if (!batchPart) { - batchPart = BATCH_POOL.pop() || new BatchPart(); - batchPart.begin(style, index_1, attribIndex); - this.batches.push(batchPart); - currentStyle = style; - } - this.addUvs(this.points, uvs, style.texture, attribIndex, size, style.matrix); - } - } - var index = this.indices.length; - var attrib = this.points.length / 2; - if (batchPart) { - batchPart.end(index, attrib); - } - if (this.batches.length === 0) { - // there are no visible styles in GraphicsData - // its possible that someone wants Graphics just for the bounds - this.batchable = true; - return; - } - var need32 = attrib > 0xffff; - // prevent allocation when length is same as buffer - if (this.indicesUint16 && this.indices.length === this.indicesUint16.length - && need32 === (this.indicesUint16.BYTES_PER_ELEMENT > 2)) { - this.indicesUint16.set(this.indices); - } - else { - this.indicesUint16 = need32 ? new Uint32Array(this.indices) : new Uint16Array(this.indices); - } - // TODO make this a const.. - this.batchable = this.isBatchable(); - if (this.batchable) { - this.packBatches(); - } - else { - this.buildDrawCalls(); - } - }; - /** - * Affinity check - * @param styleA - * @param styleB - */ - GraphicsGeometry.prototype._compareStyles = function (styleA, styleB) { - if (!styleA || !styleB) { - return false; - } - if (styleA.texture.baseTexture !== styleB.texture.baseTexture) { - return false; - } - if (styleA.color + styleA.alpha !== styleB.color + styleB.alpha) { - return false; - } - if (!!styleA.native !== !!styleB.native) { - return false; - } - return true; - }; - /** Test geometry for batching process. */ - GraphicsGeometry.prototype.validateBatching = function () { - if (this.dirty === this.cacheDirty || !this.graphicsData.length) { - return false; - } - for (var i = 0, l = this.graphicsData.length; i < l; i++) { - var data = this.graphicsData[i]; - var fill = data.fillStyle; - var line = data.lineStyle; - if (fill && !fill.texture.baseTexture.valid) - { return false; } - if (line && !line.texture.baseTexture.valid) - { return false; } - } - return true; - }; - /** Offset the indices so that it works with the batcher. */ - GraphicsGeometry.prototype.packBatches = function () { - this.batchDirty++; - this.uvsFloat32 = new Float32Array(this.uvs); - var batches = this.batches; - for (var i = 0, l = batches.length; i < l; i++) { - var batch = batches[i]; - for (var j = 0; j < batch.size; j++) { - var index = batch.start + j; - this.indicesUint16[index] = this.indicesUint16[index] - batch.attribStart; - } - } - }; - /** - * Checks to see if this graphics geometry can be batched. - * Currently it needs to be small enough and not contain any native lines. - */ - GraphicsGeometry.prototype.isBatchable = function () { - // prevent heavy mesh batching - if (this.points.length > 0xffff * 2) { - return false; - } - var batches = this.batches; - for (var i = 0; i < batches.length; i++) { - if (batches[i].style.native) { - return false; - } - } - return (this.points.length < GraphicsGeometry.BATCHABLE_SIZE * 2); - }; - /** Converts intermediate batches data to drawCalls. */ - GraphicsGeometry.prototype.buildDrawCalls = function () { - var TICK = ++BaseTexture._globalBatch; - for (var i = 0; i < this.drawCalls.length; i++) { - this.drawCalls[i].texArray.clear(); - DRAW_CALL_POOL.push(this.drawCalls[i]); - } - this.drawCalls.length = 0; - var colors = this.colors; - var textureIds = this.textureIds; - var currentGroup = DRAW_CALL_POOL.pop(); - if (!currentGroup) { - currentGroup = new BatchDrawCall(); - currentGroup.texArray = new BatchTextureArray(); - } - currentGroup.texArray.count = 0; - currentGroup.start = 0; - currentGroup.size = 0; - currentGroup.type = exports.DRAW_MODES.TRIANGLES; - var textureCount = 0; - var currentTexture = null; - var textureId = 0; - var native = false; - var drawMode = exports.DRAW_MODES.TRIANGLES; - var index = 0; - this.drawCalls.push(currentGroup); - // TODO - this can be simplified - for (var i = 0; i < this.batches.length; i++) { - var data = this.batches[i]; - // TODO add some full on MAX_TEXTURE CODE.. - var MAX_TEXTURES = 8; - // Forced cast for checking `native` without errors - var style = data.style; - var nextTexture = style.texture.baseTexture; - if (native !== !!style.native) { - native = !!style.native; - drawMode = native ? exports.DRAW_MODES.LINES : exports.DRAW_MODES.TRIANGLES; - // force the batch to break! - currentTexture = null; - textureCount = MAX_TEXTURES; - TICK++; - } - if (currentTexture !== nextTexture) { - currentTexture = nextTexture; - if (nextTexture._batchEnabled !== TICK) { - if (textureCount === MAX_TEXTURES) { - TICK++; - textureCount = 0; - if (currentGroup.size > 0) { - currentGroup = DRAW_CALL_POOL.pop(); - if (!currentGroup) { - currentGroup = new BatchDrawCall(); - currentGroup.texArray = new BatchTextureArray(); - } - this.drawCalls.push(currentGroup); - } - currentGroup.start = index; - currentGroup.size = 0; - currentGroup.texArray.count = 0; - currentGroup.type = drawMode; - } - // TODO add this to the render part.. - // Hack! Because texture has protected `touched` - nextTexture.touched = 1; // touch; - nextTexture._batchEnabled = TICK; - nextTexture._batchLocation = textureCount; - nextTexture.wrapMode = exports.WRAP_MODES.REPEAT; - currentGroup.texArray.elements[currentGroup.texArray.count++] = nextTexture; - textureCount++; - } - } - currentGroup.size += data.size; - index += data.size; - textureId = nextTexture._batchLocation; - this.addColors(colors, style.color, style.alpha, data.attribSize, data.attribStart); - this.addTextureIds(textureIds, textureId, data.attribSize, data.attribStart); - } - BaseTexture._globalBatch = TICK; - // upload.. - // merge for now! - this.packAttributes(); - }; - /** Packs attributes to single buffer. */ - GraphicsGeometry.prototype.packAttributes = function () { - var verts = this.points; - var uvs = this.uvs; - var colors = this.colors; - var textureIds = this.textureIds; - // verts are 2 positions.. so we * by 3 as there are 6 properties.. then 4 cos its bytes - var glPoints = new ArrayBuffer(verts.length * 3 * 4); - var f32 = new Float32Array(glPoints); - var u32 = new Uint32Array(glPoints); - var p = 0; - for (var i = 0; i < verts.length / 2; i++) { - f32[p++] = verts[i * 2]; - f32[p++] = verts[(i * 2) + 1]; - f32[p++] = uvs[i * 2]; - f32[p++] = uvs[(i * 2) + 1]; - u32[p++] = colors[i]; - f32[p++] = textureIds[i]; - } - this._buffer.update(glPoints); - this._indexBuffer.update(this.indicesUint16); - }; - /** - * Process fill part of Graphics. - * @param data - */ - GraphicsGeometry.prototype.processFill = function (data) { - if (data.holes.length) { - buildPoly.triangulate(data, this); - } - else { - var command = FILL_COMMANDS[data.type]; - command.triangulate(data, this); - } - }; - /** - * Process line part of Graphics. - * @param data - */ - GraphicsGeometry.prototype.processLine = function (data) { - buildLine(data, this); - for (var i = 0; i < data.holes.length; i++) { - buildLine(data.holes[i], this); - } - }; - /** - * Process the holes data. - * @param holes - */ - GraphicsGeometry.prototype.processHoles = function (holes) { - for (var i = 0; i < holes.length; i++) { - var hole = holes[i]; - var command = FILL_COMMANDS[hole.type]; - command.build(hole); - if (hole.matrix) { - this.transformPoints(hole.points, hole.matrix); - } - } - }; - /** Update the local bounds of the object. Expensive to use performance-wise. */ - GraphicsGeometry.prototype.calculateBounds = function () { - var bounds = this._bounds; - bounds.clear(); - bounds.addVertexData(this.points, 0, this.points.length); - bounds.pad(this.boundsPadding, this.boundsPadding); - }; - /** - * Transform points using matrix. - * @param points - Points to transform - * @param matrix - Transform matrix - */ - GraphicsGeometry.prototype.transformPoints = function (points, matrix) { - for (var i = 0; i < points.length / 2; i++) { - var x = points[(i * 2)]; - var y = points[(i * 2) + 1]; - points[(i * 2)] = (matrix.a * x) + (matrix.c * y) + matrix.tx; - points[(i * 2) + 1] = (matrix.b * x) + (matrix.d * y) + matrix.ty; - } - }; - /** - * Add colors. - * @param colors - List of colors to add to - * @param color - Color to add - * @param alpha - Alpha to use - * @param size - Number of colors to add - * @param offset - */ - GraphicsGeometry.prototype.addColors = function (colors, color, alpha, size, offset) { - if (offset === void 0) { offset = 0; } - // TODO use the premultiply bits Ivan added - var rgb = (color >> 16) + (color & 0xff00) + ((color & 0xff) << 16); - var rgba = premultiplyTint(rgb, alpha); - colors.length = Math.max(colors.length, offset + size); - for (var i = 0; i < size; i++) { - colors[offset + i] = rgba; - } - }; - /** - * Add texture id that the shader/fragment wants to use. - * @param textureIds - * @param id - * @param size - * @param offset - */ - GraphicsGeometry.prototype.addTextureIds = function (textureIds, id, size, offset) { - if (offset === void 0) { offset = 0; } - textureIds.length = Math.max(textureIds.length, offset + size); - for (var i = 0; i < size; i++) { - textureIds[offset + i] = id; - } - }; - /** - * Generates the UVs for a shape. - * @param verts - Vertices - * @param uvs - UVs - * @param texture - Reference to Texture - * @param start - Index buffer start index. - * @param size - The size/length for index buffer. - * @param matrix - Optional transform for all points. - */ - GraphicsGeometry.prototype.addUvs = function (verts, uvs, texture, start, size, matrix) { - if (matrix === void 0) { matrix = null; } - var index = 0; - var uvsStart = uvs.length; - var frame = texture.frame; - while (index < size) { - var x = verts[(start + index) * 2]; - var y = verts[((start + index) * 2) + 1]; - if (matrix) { - var nx = (matrix.a * x) + (matrix.c * y) + matrix.tx; - y = (matrix.b * x) + (matrix.d * y) + matrix.ty; - x = nx; - } - index++; - uvs.push(x / frame.width, y / frame.height); - } - var baseTexture = texture.baseTexture; - if (frame.width < baseTexture.width - || frame.height < baseTexture.height) { - this.adjustUvs(uvs, texture, uvsStart, size); - } - }; - /** - * Modify uvs array according to position of texture region - * Does not work with rotated or trimmed textures - * @param uvs - array - * @param texture - region - * @param start - starting index for uvs - * @param size - how many points to adjust - */ - GraphicsGeometry.prototype.adjustUvs = function (uvs, texture, start, size) { - var baseTexture = texture.baseTexture; - var eps = 1e-6; - var finish = start + (size * 2); - var frame = texture.frame; - var scaleX = frame.width / baseTexture.width; - var scaleY = frame.height / baseTexture.height; - var offsetX = frame.x / frame.width; - var offsetY = frame.y / frame.height; - var minX = Math.floor(uvs[start] + eps); - var minY = Math.floor(uvs[start + 1] + eps); - for (var i = start + 2; i < finish; i += 2) { - minX = Math.min(minX, Math.floor(uvs[i] + eps)); - minY = Math.min(minY, Math.floor(uvs[i + 1] + eps)); - } - offsetX -= minX; - offsetY -= minY; - for (var i = start; i < finish; i += 2) { - uvs[i] = (uvs[i] + offsetX) * scaleX; - uvs[i + 1] = (uvs[i + 1] + offsetY) * scaleY; - } - }; - /** - * The maximum number of points to consider an object "batchable", - * able to be batched by the renderer's batch system. - \ - */ - GraphicsGeometry.BATCHABLE_SIZE = 100; - return GraphicsGeometry; - }(BatchGeometry)); - - /** - * Represents the line style for Graphics. - * @memberof PIXI - */ - var LineStyle = /** @class */ (function (_super) { - __extends$e(LineStyle, _super); - function LineStyle() { - var _this = _super !== null && _super.apply(this, arguments) || this; - /** The width (thickness) of any lines drawn. */ - _this.width = 0; - /** The alignment of any lines drawn (0.5 = middle, 1 = outer, 0 = inner). WebGL only. */ - _this.alignment = 0.5; - /** If true the lines will be draw using LINES instead of TRIANGLE_STRIP. */ - _this.native = false; - /** - * Line cap style. - * @member {PIXI.LINE_CAP} - * @default PIXI.LINE_CAP.BUTT - */ - _this.cap = exports.LINE_CAP.BUTT; - /** - * Line join style. - * @member {PIXI.LINE_JOIN} - * @default PIXI.LINE_JOIN.MITER - */ - _this.join = exports.LINE_JOIN.MITER; - /** Miter limit. */ - _this.miterLimit = 10; - return _this; - } - /** Clones the object. */ - LineStyle.prototype.clone = function () { - var obj = new LineStyle(); - obj.color = this.color; - obj.alpha = this.alpha; - obj.texture = this.texture; - obj.matrix = this.matrix; - obj.visible = this.visible; - obj.width = this.width; - obj.alignment = this.alignment; - obj.native = this.native; - obj.cap = this.cap; - obj.join = this.join; - obj.miterLimit = this.miterLimit; - return obj; - }; - /** Reset the line style to default. */ - LineStyle.prototype.reset = function () { - _super.prototype.reset.call(this); - // Override default line style color - this.color = 0x0; - this.alignment = 0.5; - this.width = 0; - this.native = false; - }; - return LineStyle; - }(FillStyle)); - - var temp = new Float32Array(3); - // a default shaders map used by graphics.. - var DEFAULT_SHADERS = {}; - /** - * The Graphics class is primarily used to render primitive shapes such as lines, circles and - * rectangles to the display, and to color and fill them. However, you can also use a Graphics - * object to build a list of primitives to use as a mask, or as a complex hitArea. - * - * Please note that due to legacy naming conventions, the behavior of some functions in this class - * can be confusing. Each call to `drawRect()`, `drawPolygon()`, etc. actually stores that primitive - * in the Geometry class's GraphicsGeometry object for later use in rendering or hit testing - the - * functions do not directly draw anything to the screen. Similarly, the `clear()` function doesn't - * change the screen, it simply resets the list of primitives, which can be useful if you want to - * rebuild the contents of an existing Graphics object. - * - * Once a GraphicsGeometry list is built, you can re-use it in other Geometry objects as - * an optimization, by passing it into a new Geometry object's constructor. Because of this - * ability, it's important to call `destroy()` on Geometry objects once you are done with them, to - * properly dereference each GraphicsGeometry and prevent memory leaks. - * @memberof PIXI - */ - var Graphics = /** @class */ (function (_super) { - __extends$e(Graphics, _super); - /** - * @param geometry - Geometry to use, if omitted will create a new GraphicsGeometry instance. - */ - function Graphics(geometry) { - if (geometry === void 0) { geometry = null; } - var _this = _super.call(this) || this; - /** - * Represents the vertex and fragment shaders that processes the geometry and runs on the GPU. - * Can be shared between multiple Graphics objects. - */ - _this.shader = null; - /** Renderer plugin for batching */ - _this.pluginName = 'batch'; - /** - * Current path - * @readonly - */ - _this.currentPath = null; - /** A collections of batches! These can be drawn by the renderer batch system. */ - _this.batches = []; - /** Update dirty for limiting calculating tints for batches. */ - _this.batchTint = -1; - /** Update dirty for limiting calculating batches.*/ - _this.batchDirty = -1; - /** Copy of the object vertex data. */ - _this.vertexData = null; - /** Current fill style. */ - _this._fillStyle = new FillStyle(); - /** Current line style. */ - _this._lineStyle = new LineStyle(); - /** Current shape transform matrix. */ - _this._matrix = null; - /** Current hole mode is enabled. */ - _this._holeMode = false; - /** - * Represents the WebGL state the Graphics required to render, excludes shader and geometry. E.g., - * blend mode, culling, depth testing, direction of rendering triangles, backface, etc. - */ - _this.state = State.for2d(); - _this._geometry = geometry || new GraphicsGeometry(); - _this._geometry.refCount++; - /** - * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. - * This is useful if your graphics element does not change often, as it will speed up the rendering - * of the object in exchange for taking up texture memory. It is also useful if you need the graphics - * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if - * you are constantly redrawing the graphics element. - * @name cacheAsBitmap - * @member {boolean} - * @memberof PIXI.Graphics# - * @default false - */ - _this._transformID = -1; - // Set default - _this.tint = 0xFFFFFF; - _this.blendMode = exports.BLEND_MODES.NORMAL; - return _this; - } - Object.defineProperty(Graphics.prototype, "geometry", { - /** - * Includes vertex positions, face indices, normals, colors, UVs, and - * custom attributes within buffers, reducing the cost of passing all - * this data to the GPU. Can be shared between multiple Mesh or Graphics objects. - * @readonly - */ - get: function () { - return this._geometry; - }, - enumerable: false, - configurable: true - }); - /** - * Creates a new Graphics object with the same values as this one. - * Note that only the geometry of the object is cloned, not its transform (position,scale,etc) - * @returns - A clone of the graphics object - */ - Graphics.prototype.clone = function () { - this.finishPoly(); - return new Graphics(this._geometry); - }; - Object.defineProperty(Graphics.prototype, "blendMode", { - get: function () { - return this.state.blendMode; - }, - /** - * The blend mode to be applied to the graphic shape. Apply a value of - * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. Note that, since each - * primitive in the GraphicsGeometry list is rendered sequentially, modes - * such as `PIXI.BLEND_MODES.ADD` and `PIXI.BLEND_MODES.MULTIPLY` will - * be applied per-primitive. - * @default PIXI.BLEND_MODES.NORMAL - */ - set: function (value) { - this.state.blendMode = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Graphics.prototype, "tint", { - /** - * The tint applied to each graphic shape. This is a hex value. A value of - * 0xFFFFFF will remove any tint effect. - * @default 0xFFFFFF - */ - get: function () { - return this._tint; - }, - set: function (value) { - this._tint = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Graphics.prototype, "fill", { - /** - * The current fill style. - * @readonly - */ - get: function () { - return this._fillStyle; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Graphics.prototype, "line", { - /** - * The current line style. - * @readonly - */ - get: function () { - return this._lineStyle; - }, - enumerable: false, - configurable: true - }); - Graphics.prototype.lineStyle = function (options, color, alpha, alignment, native) { - if (options === void 0) { options = null; } - if (color === void 0) { color = 0x0; } - if (alpha === void 0) { alpha = 1; } - if (alignment === void 0) { alignment = 0.5; } - if (native === void 0) { native = false; } - // Support non-object params: (width, color, alpha, alignment, native) - if (typeof options === 'number') { - options = { width: options, color: color, alpha: alpha, alignment: alignment, native: native }; - } - return this.lineTextureStyle(options); - }; - /** - * Like line style but support texture for line fill. - * @param [options] - Collection of options for setting line style. - * @param {number} [options.width=0] - width of the line to draw, will update the objects stored style - * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to use - * @param {number} [options.color=0x0] - color of the line to draw, will update the objects stored style. - * Default 0xFFFFFF if texture present. - * @param {number} [options.alpha=1] - alpha of the line to draw, will update the objects stored style - * @param {PIXI.Matrix} [options.matrix=null] - Texture matrix to transform texture - * @param {number} [options.alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outer). - * WebGL only. - * @param {boolean} [options.native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP - * @param {PIXI.LINE_CAP}[options.cap=PIXI.LINE_CAP.BUTT] - line cap style - * @param {PIXI.LINE_JOIN}[options.join=PIXI.LINE_JOIN.MITER] - line join style - * @param {number}[options.miterLimit=10] - miter limit ratio - * @returns {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.lineTextureStyle = function (options) { - // Apply defaults - options = Object.assign({ - width: 0, - texture: Texture.WHITE, - color: (options && options.texture) ? 0xFFFFFF : 0x0, - alpha: 1, - matrix: null, - alignment: 0.5, - native: false, - cap: exports.LINE_CAP.BUTT, - join: exports.LINE_JOIN.MITER, - miterLimit: 10, - }, options); - if (this.currentPath) { - this.startPoly(); - } - var visible = options.width > 0 && options.alpha > 0; - if (!visible) { - this._lineStyle.reset(); - } - else { - if (options.matrix) { - options.matrix = options.matrix.clone(); - options.matrix.invert(); - } - Object.assign(this._lineStyle, { visible: visible }, options); - } - return this; - }; - /** - * Start a polygon object internally. - * @protected - */ - Graphics.prototype.startPoly = function () { - if (this.currentPath) { - var points = this.currentPath.points; - var len = this.currentPath.points.length; - if (len > 2) { - this.drawShape(this.currentPath); - this.currentPath = new Polygon(); - this.currentPath.closeStroke = false; - this.currentPath.points.push(points[len - 2], points[len - 1]); - } - } - else { - this.currentPath = new Polygon(); - this.currentPath.closeStroke = false; - } - }; - /** - * Finish the polygon object. - * @protected - */ - Graphics.prototype.finishPoly = function () { - if (this.currentPath) { - if (this.currentPath.points.length > 2) { - this.drawShape(this.currentPath); - this.currentPath = null; - } - else { - this.currentPath.points.length = 0; - } - } - }; - /** - * Moves the current drawing position to x, y. - * @param x - the X coordinate to move to - * @param y - the Y coordinate to move to - * @returns - This Graphics object. Good for chaining method calls - */ - Graphics.prototype.moveTo = function (x, y) { - this.startPoly(); - this.currentPath.points[0] = x; - this.currentPath.points[1] = y; - return this; - }; - /** - * Draws a line using the current line style from the current drawing position to (x, y); - * The current drawing position is then set to (x, y). - * @param x - the X coordinate to draw to - * @param y - the Y coordinate to draw to - * @returns - This Graphics object. Good for chaining method calls - */ - Graphics.prototype.lineTo = function (x, y) { - if (!this.currentPath) { - this.moveTo(0, 0); - } - // remove duplicates.. - var points = this.currentPath.points; - var fromX = points[points.length - 2]; - var fromY = points[points.length - 1]; - if (fromX !== x || fromY !== y) { - points.push(x, y); - } - return this; - }; - /** - * Initialize the curve - * @param x - * @param y - */ - Graphics.prototype._initCurve = function (x, y) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - if (this.currentPath) { - if (this.currentPath.points.length === 0) { - this.currentPath.points = [x, y]; - } - } - else { - this.moveTo(x, y); - } - }; - /** - * Calculate the points for a quadratic bezier curve and then draws it. - * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c - * @param cpX - Control point x - * @param cpY - Control point y - * @param toX - Destination point x - * @param toY - Destination point y - * @returns - This Graphics object. Good for chaining method calls - */ - Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - this._initCurve(); - var points = this.currentPath.points; - if (points.length === 0) { - this.moveTo(0, 0); - } - QuadraticUtils.curveTo(cpX, cpY, toX, toY, points); - return this; - }; - /** - * Calculate the points for a bezier curve and then draws it. - * @param cpX - Control point x - * @param cpY - Control point y - * @param cpX2 - Second Control point x - * @param cpY2 - Second Control point y - * @param toX - Destination point x - * @param toY - Destination point y - * @returns This Graphics object. Good for chaining method calls - */ - Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - this._initCurve(); - BezierUtils.curveTo(cpX, cpY, cpX2, cpY2, toX, toY, this.currentPath.points); - return this; - }; - /** - * The arcTo() method creates an arc/curve between two tangents on the canvas. - * - * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! - * @param x1 - The x-coordinate of the first tangent point of the arc - * @param y1 - The y-coordinate of the first tangent point of the arc - * @param x2 - The x-coordinate of the end of the arc - * @param y2 - The y-coordinate of the end of the arc - * @param radius - The radius of the arc - * @returns - This Graphics object. Good for chaining method calls - */ - Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - this._initCurve(x1, y1); - var points = this.currentPath.points; - var result = ArcUtils.curveTo(x1, y1, x2, y2, radius, points); - if (result) { - var cx = result.cx, cy = result.cy, radius_1 = result.radius, startAngle = result.startAngle, endAngle = result.endAngle, anticlockwise = result.anticlockwise; - this.arc(cx, cy, radius_1, startAngle, endAngle, anticlockwise); - } - return this; - }; - /** - * The arc method creates an arc/curve (used to create circles, or parts of circles). - * @param cx - The x-coordinate of the center of the circle - * @param cy - The y-coordinate of the center of the circle - * @param radius - The radius of the circle - * @param startAngle - The starting angle, in radians (0 is at the 3 o'clock position - * of the arc's circle) - * @param endAngle - The ending angle, in radians - * @param anticlockwise - Specifies whether the drawing should be - * counter-clockwise or clockwise. False is default, and indicates clockwise, while true - * indicates counter-clockwise. - * @returns - This Graphics object. Good for chaining method calls - */ - Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { - if (anticlockwise === void 0) { anticlockwise = false; } - if (startAngle === endAngle) { - return this; - } - if (!anticlockwise && endAngle <= startAngle) { - endAngle += PI_2; - } - else if (anticlockwise && startAngle <= endAngle) { - startAngle += PI_2; - } - var sweep = endAngle - startAngle; - if (sweep === 0) { - return this; - } - var startX = cx + (Math.cos(startAngle) * radius); - var startY = cy + (Math.sin(startAngle) * radius); - var eps = this._geometry.closePointEps; - // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. - var points = this.currentPath ? this.currentPath.points : null; - if (points) { - // TODO: make a better fix. - // We check how far our start is from the last existing point - var xDiff = Math.abs(points[points.length - 2] - startX); - var yDiff = Math.abs(points[points.length - 1] - startY); - if (xDiff < eps && yDiff < eps) { ; } - else { - points.push(startX, startY); - } - } - else { - this.moveTo(startX, startY); - points = this.currentPath.points; - } - ArcUtils.arc(startX, startY, cx, cy, radius, startAngle, endAngle, anticlockwise, points); - return this; - }; - /** - * Specifies a simple one-color fill that subsequent calls to other Graphics methods - * (such as lineTo() or drawCircle()) use when drawing. - * @param color - the color of the fill - * @param alpha - the alpha of the fill - * @returns - This Graphics object. Good for chaining method calls - */ - Graphics.prototype.beginFill = function (color, alpha) { - if (color === void 0) { color = 0; } - if (alpha === void 0) { alpha = 1; } - return this.beginTextureFill({ texture: Texture.WHITE, color: color, alpha: alpha }); - }; - /** - * Begin the texture fill - * @param options - Object object. - * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to fill - * @param {number} [options.color=0xffffff] - Background to fill behind texture - * @param {number} [options.alpha=1] - Alpha of fill - * @param {PIXI.Matrix} [options.matrix=null] - Transform matrix - * @returns {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.beginTextureFill = function (options) { - // Apply defaults - options = Object.assign({ - texture: Texture.WHITE, - color: 0xFFFFFF, - alpha: 1, - matrix: null, - }, options); - if (this.currentPath) { - this.startPoly(); - } - var visible = options.alpha > 0; - if (!visible) { - this._fillStyle.reset(); - } - else { - if (options.matrix) { - options.matrix = options.matrix.clone(); - options.matrix.invert(); - } - Object.assign(this._fillStyle, { visible: visible }, options); - } - return this; - }; - /** - * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. - * @returns - This Graphics object. Good for chaining method calls - */ - Graphics.prototype.endFill = function () { - this.finishPoly(); - this._fillStyle.reset(); - return this; - }; - /** - * Draws a rectangle shape. - * @param x - The X coord of the top-left of the rectangle - * @param y - The Y coord of the top-left of the rectangle - * @param width - The width of the rectangle - * @param height - The height of the rectangle - * @returns - This Graphics object. Good for chaining method calls - */ - Graphics.prototype.drawRect = function (x, y, width, height) { - return this.drawShape(new Rectangle(x, y, width, height)); - }; - /** - * Draw a rectangle shape with rounded/beveled corners. - * @param x - The X coord of the top-left of the rectangle - * @param y - The Y coord of the top-left of the rectangle - * @param width - The width of the rectangle - * @param height - The height of the rectangle - * @param radius - Radius of the rectangle corners - * @returns - This Graphics object. Good for chaining method calls - */ - Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) { - return this.drawShape(new RoundedRectangle(x, y, width, height, radius)); - }; - /** - * Draws a circle. - * @param x - The X coordinate of the center of the circle - * @param y - The Y coordinate of the center of the circle - * @param radius - The radius of the circle - * @returns - This Graphics object. Good for chaining method calls - */ - Graphics.prototype.drawCircle = function (x, y, radius) { - return this.drawShape(new Circle(x, y, radius)); - }; - /** - * Draws an ellipse. - * @param x - The X coordinate of the center of the ellipse - * @param y - The Y coordinate of the center of the ellipse - * @param width - The half width of the ellipse - * @param height - The half height of the ellipse - * @returns - This Graphics object. Good for chaining method calls - */ - Graphics.prototype.drawEllipse = function (x, y, width, height) { - return this.drawShape(new Ellipse(x, y, width, height)); - }; - /** - * Draws a polygon using the given path. - * @param {number[]|PIXI.IPointData[]|PIXI.Polygon} path - The path data used to construct the polygon. - * @returns - This Graphics object. Good for chaining method calls - */ - Graphics.prototype.drawPolygon = function () { - var arguments$1 = arguments; - - var path = []; - for (var _i = 0; _i < arguments.length; _i++) { - path[_i] = arguments$1[_i]; - } - var points; - var closeStroke = true; // !!this._fillStyle; - var poly = path[0]; - // check if data has points.. - if (poly.points) { - closeStroke = poly.closeStroke; - points = poly.points; - } - else if (Array.isArray(path[0])) { - points = path[0]; - } - else { - points = path; - } - var shape = new Polygon(points); - shape.closeStroke = closeStroke; - this.drawShape(shape); - return this; - }; - /** - * Draw any shape. - * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - Shape to draw - * @returns - This Graphics object. Good for chaining method calls - */ - Graphics.prototype.drawShape = function (shape) { - if (!this._holeMode) { - this._geometry.drawShape(shape, this._fillStyle.clone(), this._lineStyle.clone(), this._matrix); - } - else { - this._geometry.drawHole(shape, this._matrix); - } - return this; - }; - /** - * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. - * @returns - This Graphics object. Good for chaining method calls - */ - Graphics.prototype.clear = function () { - this._geometry.clear(); - this._lineStyle.reset(); - this._fillStyle.reset(); - this._boundsID++; - this._matrix = null; - this._holeMode = false; - this.currentPath = null; - return this; - }; - /** - * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and - * masked with gl.scissor. - * @returns - True if only 1 rect. - */ - Graphics.prototype.isFastRect = function () { - var data = this._geometry.graphicsData; - return data.length === 1 - && data[0].shape.type === exports.SHAPES.RECT - && !data[0].matrix - && !data[0].holes.length - && !(data[0].lineStyle.visible && data[0].lineStyle.width); - }; - /** - * Renders the object using the WebGL renderer - * @param renderer - The renderer - */ - Graphics.prototype._render = function (renderer) { - this.finishPoly(); - var geometry = this._geometry; - // batch part.. - // batch it! - geometry.updateBatches(); - if (geometry.batchable) { - if (this.batchDirty !== geometry.batchDirty) { - this._populateBatches(); - } - this._renderBatched(renderer); - } - else { - // no batching... - renderer.batch.flush(); - this._renderDirect(renderer); - } - }; - /** Populating batches for rendering. */ - Graphics.prototype._populateBatches = function () { - var geometry = this._geometry; - var blendMode = this.blendMode; - var len = geometry.batches.length; - this.batchTint = -1; - this._transformID = -1; - this.batchDirty = geometry.batchDirty; - this.batches.length = len; - this.vertexData = new Float32Array(geometry.points); - for (var i = 0; i < len; i++) { - var gI = geometry.batches[i]; - var color = gI.style.color; - var vertexData = new Float32Array(this.vertexData.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2); - var uvs = new Float32Array(geometry.uvsFloat32.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2); - var indices = new Uint16Array(geometry.indicesUint16.buffer, gI.start * 2, gI.size); - var batch = { - vertexData: vertexData, - blendMode: blendMode, - indices: indices, - uvs: uvs, - _batchRGB: hex2rgb(color), - _tintRGB: color, - _texture: gI.style.texture, - alpha: gI.style.alpha, - worldAlpha: 1 - }; - this.batches[i] = batch; - } - }; - /** - * Renders the batches using the BathedRenderer plugin - * @param renderer - The renderer - */ - Graphics.prototype._renderBatched = function (renderer) { - if (!this.batches.length) { - return; - } - renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); - this.calculateVertices(); - this.calculateTints(); - for (var i = 0, l = this.batches.length; i < l; i++) { - var batch = this.batches[i]; - batch.worldAlpha = this.worldAlpha * batch.alpha; - renderer.plugins[this.pluginName].render(batch); - } - }; - /** - * Renders the graphics direct - * @param renderer - The renderer - */ - Graphics.prototype._renderDirect = function (renderer) { - var shader = this._resolveDirectShader(renderer); - var geometry = this._geometry; - var tint = this.tint; - var worldAlpha = this.worldAlpha; - var uniforms = shader.uniforms; - var drawCalls = geometry.drawCalls; - // lets set the transfomr - uniforms.translationMatrix = this.transform.worldTransform; - // and then lets set the tint.. - uniforms.tint[0] = (((tint >> 16) & 0xFF) / 255) * worldAlpha; - uniforms.tint[1] = (((tint >> 8) & 0xFF) / 255) * worldAlpha; - uniforms.tint[2] = ((tint & 0xFF) / 255) * worldAlpha; - uniforms.tint[3] = worldAlpha; - // the first draw call, we can set the uniforms of the shader directly here. - // this means that we can tack advantage of the sync function of pixi! - // bind and sync uniforms.. - // there is a way to optimise this.. - renderer.shader.bind(shader); - renderer.geometry.bind(geometry, shader); - // set state.. - renderer.state.set(this.state); - // then render the rest of them... - for (var i = 0, l = drawCalls.length; i < l; i++) { - this._renderDrawCallDirect(renderer, geometry.drawCalls[i]); - } - }; - /** - * Renders specific DrawCall - * @param renderer - * @param drawCall - */ - Graphics.prototype._renderDrawCallDirect = function (renderer, drawCall) { - var texArray = drawCall.texArray, type = drawCall.type, size = drawCall.size, start = drawCall.start; - var groupTextureCount = texArray.count; - for (var j = 0; j < groupTextureCount; j++) { - renderer.texture.bind(texArray.elements[j], j); - } - renderer.geometry.draw(type, size, start); - }; - /** - * Resolves shader for direct rendering - * @param renderer - The renderer - */ - Graphics.prototype._resolveDirectShader = function (renderer) { - var shader = this.shader; - var pluginName = this.pluginName; - if (!shader) { - // if there is no shader here, we can use the default shader. - // and that only gets created if we actually need it.. - // but may be more than one plugins for graphics - if (!DEFAULT_SHADERS[pluginName]) { - var MAX_TEXTURES = renderer.plugins[pluginName].MAX_TEXTURES; - var sampleValues = new Int32Array(MAX_TEXTURES); - for (var i = 0; i < MAX_TEXTURES; i++) { - sampleValues[i] = i; - } - var uniforms = { - tint: new Float32Array([1, 1, 1, 1]), - translationMatrix: new Matrix(), - default: UniformGroup.from({ uSamplers: sampleValues }, true), - }; - var program = renderer.plugins[pluginName]._shader.program; - DEFAULT_SHADERS[pluginName] = new Shader(program, uniforms); - } - shader = DEFAULT_SHADERS[pluginName]; - } - return shader; - }; - /** Retrieves the bounds of the graphic shape as a rectangle object. */ - Graphics.prototype._calculateBounds = function () { - this.finishPoly(); - var geometry = this._geometry; - // skipping when graphics is empty, like a container - if (!geometry.graphicsData.length) { - return; - } - var _a = geometry.bounds, minX = _a.minX, minY = _a.minY, maxX = _a.maxX, maxY = _a.maxY; - this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); - }; - /** - * Tests if a point is inside this graphics object - * @param point - the point to test - * @returns - the result of the test - */ - Graphics.prototype.containsPoint = function (point) { - this.worldTransform.applyInverse(point, Graphics._TEMP_POINT); - return this._geometry.containsPoint(Graphics._TEMP_POINT); - }; - /** Recalculate the tint by applying tint to batches using Graphics tint. */ - Graphics.prototype.calculateTints = function () { - if (this.batchTint !== this.tint) { - this.batchTint = this.tint; - var tintRGB = hex2rgb(this.tint, temp); - for (var i = 0; i < this.batches.length; i++) { - var batch = this.batches[i]; - var batchTint = batch._batchRGB; - var r = (tintRGB[0] * batchTint[0]) * 255; - var g = (tintRGB[1] * batchTint[1]) * 255; - var b = (tintRGB[2] * batchTint[2]) * 255; - // TODO Ivan, can this be done in one go? - var color = (r << 16) + (g << 8) + (b | 0); - batch._tintRGB = (color >> 16) - + (color & 0xff00) - + ((color & 0xff) << 16); - } - } - }; - /** If there's a transform update or a change to the shape of the geometry, recalculate the vertices. */ - Graphics.prototype.calculateVertices = function () { - var wtID = this.transform._worldID; - if (this._transformID === wtID) { - return; - } - this._transformID = wtID; - var wt = this.transform.worldTransform; - var a = wt.a; - var b = wt.b; - var c = wt.c; - var d = wt.d; - var tx = wt.tx; - var ty = wt.ty; - var data = this._geometry.points; // batch.vertexDataOriginal; - var vertexData = this.vertexData; - var count = 0; - for (var i = 0; i < data.length; i += 2) { - var x = data[i]; - var y = data[i + 1]; - vertexData[count++] = (a * x) + (c * y) + tx; - vertexData[count++] = (d * y) + (b * x) + ty; - } - }; - /** - * Closes the current path. - * @returns - Returns itself. - */ - Graphics.prototype.closePath = function () { - var currentPath = this.currentPath; - if (currentPath) { - // we don't need to add extra point in the end because buildLine will take care of that - currentPath.closeStroke = true; - // ensure that the polygon is completed, and is available for hit detection - // (even if the graphics is not rendered yet) - this.finishPoly(); - } - return this; - }; - /** - * Apply a matrix to the positional data. - * @param matrix - Matrix to use for transform current shape. - * @returns - Returns itself. - */ - Graphics.prototype.setMatrix = function (matrix) { - this._matrix = matrix; - return this; - }; - /** - * Begin adding holes to the last draw shape - * IMPORTANT: holes must be fully inside a shape to work - * Also weirdness ensues if holes overlap! - * Ellipses, Circles, Rectangles and Rounded Rectangles cannot be holes or host for holes in CanvasRenderer, - * please use `moveTo` `lineTo`, `quadraticCurveTo` if you rely on pixi-legacy bundle. - * @returns - Returns itself. - */ - Graphics.prototype.beginHole = function () { - this.finishPoly(); - this._holeMode = true; - return this; - }; - /** - * End adding holes to the last draw shape. - * @returns - Returns itself. - */ - Graphics.prototype.endHole = function () { - this.finishPoly(); - this._holeMode = false; - return this; - }; - /** - * Destroys the Graphics object. - * @param options - Options parameter. A boolean will act as if all - * options have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have - * their destroy method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the texture of the child sprite - * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the base texture of the child sprite - */ - Graphics.prototype.destroy = function (options) { - this._geometry.refCount--; - if (this._geometry.refCount === 0) { - this._geometry.dispose(); - } - this._matrix = null; - this.currentPath = null; - this._lineStyle.destroy(); - this._lineStyle = null; - this._fillStyle.destroy(); - this._fillStyle = null; - this._geometry = null; - this.shader = null; - this.vertexData = null; - this.batches.length = 0; - this.batches = null; - _super.prototype.destroy.call(this, options); - }; - /** - * New rendering behavior for rounded rectangles: circular arcs instead of quadratic bezier curves. - * In the next major release, we'll enable this by default. - */ - Graphics.nextRoundedRectBehavior = false; - /** - * Temporary point to use for containsPoint. - * @private - */ - Graphics._TEMP_POINT = new Point(); - return Graphics; - }(Container)); - - var graphicsUtils = { - buildPoly: buildPoly, - buildCircle: buildCircle, - buildRectangle: buildRectangle, - buildRoundedRectangle: buildRoundedRectangle, - buildLine: buildLine, - ArcUtils: ArcUtils, - BezierUtils: BezierUtils, - QuadraticUtils: QuadraticUtils, - BatchPart: BatchPart, - FILL_COMMANDS: FILL_COMMANDS, - BATCH_POOL: BATCH_POOL, - DRAW_CALL_POOL: DRAW_CALL_POOL - }; - - /*! - * @pixi/sprite - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/sprite is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$d = function(d, b) { - extendStatics$d = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$d(d, b); - }; - - function __extends$d(d, b) { - extendStatics$d(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var tempPoint$2 = new Point(); - var indices = new Uint16Array([0, 1, 2, 0, 2, 3]); - /** - * The Sprite object is the base for all textured objects that are rendered to the screen - * - * A sprite can be created directly from an image like this: - * - * ```js - * let sprite = PIXI.Sprite.from('assets/image.png'); - * ``` - * - * The more efficient way to create sprites is using a {@link PIXI.Spritesheet}, - * as swapping base textures when rendering to the screen is inefficient. - * - * ```js - * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup); - * - * function setup() { - * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet; - * let sprite = new PIXI.Sprite(sheet.textures["image.png"]); - * ... - * } - * ``` - * @memberof PIXI - */ - var Sprite = /** @class */ (function (_super) { - __extends$d(Sprite, _super); - /** @param texture - The texture for this sprite. */ - function Sprite(texture) { - var _this = _super.call(this) || this; - _this._anchor = new ObservablePoint(_this._onAnchorUpdate, _this, (texture ? texture.defaultAnchor.x : 0), (texture ? texture.defaultAnchor.y : 0)); - _this._texture = null; - _this._width = 0; - _this._height = 0; - _this._tint = null; - _this._tintRGB = null; - _this.tint = 0xFFFFFF; - _this.blendMode = exports.BLEND_MODES.NORMAL; - _this._cachedTint = 0xFFFFFF; - _this.uvs = null; - // call texture setter - _this.texture = texture || Texture.EMPTY; - _this.vertexData = new Float32Array(8); - _this.vertexTrimmedData = null; - _this._transformID = -1; - _this._textureID = -1; - _this._transformTrimmedID = -1; - _this._textureTrimmedID = -1; - // Batchable stuff.. - // TODO could make this a mixin? - _this.indices = indices; - _this.pluginName = 'batch'; - /** - * Used to fast check if a sprite is.. a sprite! - * @member {boolean} - */ - _this.isSprite = true; - _this._roundPixels = settings.ROUND_PIXELS; - return _this; - } - /** When the texture is updated, this event will fire to update the scale and frame. */ - Sprite.prototype._onTextureUpdate = function () { - this._textureID = -1; - this._textureTrimmedID = -1; - this._cachedTint = 0xFFFFFF; - // so if _width is 0 then width was not set.. - if (this._width) { - this.scale.x = sign(this.scale.x) * this._width / this._texture.orig.width; - } - if (this._height) { - this.scale.y = sign(this.scale.y) * this._height / this._texture.orig.height; - } - }; - /** Called when the anchor position updates. */ - Sprite.prototype._onAnchorUpdate = function () { - this._transformID = -1; - this._transformTrimmedID = -1; - }; - /** Calculates worldTransform * vertices, store it in vertexData. */ - Sprite.prototype.calculateVertices = function () { - var texture = this._texture; - if (this._transformID === this.transform._worldID && this._textureID === texture._updateID) { - return; - } - // update texture UV here, because base texture can be changed without calling `_onTextureUpdate` - if (this._textureID !== texture._updateID) { - this.uvs = this._texture._uvs.uvsFloat32; - } - this._transformID = this.transform._worldID; - this._textureID = texture._updateID; - // set the vertex data - var wt = this.transform.worldTransform; - var a = wt.a; - var b = wt.b; - var c = wt.c; - var d = wt.d; - var tx = wt.tx; - var ty = wt.ty; - var vertexData = this.vertexData; - var trim = texture.trim; - var orig = texture.orig; - var anchor = this._anchor; - var w0 = 0; - var w1 = 0; - var h0 = 0; - var h1 = 0; - if (trim) { - // if the sprite is trimmed and is not a tilingsprite then we need to add the extra - // space before transforming the sprite coords. - w1 = trim.x - (anchor._x * orig.width); - w0 = w1 + trim.width; - h1 = trim.y - (anchor._y * orig.height); - h0 = h1 + trim.height; - } - else { - w1 = -anchor._x * orig.width; - w0 = w1 + orig.width; - h1 = -anchor._y * orig.height; - h0 = h1 + orig.height; - } - // xy - vertexData[0] = (a * w1) + (c * h1) + tx; - vertexData[1] = (d * h1) + (b * w1) + ty; - // xy - vertexData[2] = (a * w0) + (c * h1) + tx; - vertexData[3] = (d * h1) + (b * w0) + ty; - // xy - vertexData[4] = (a * w0) + (c * h0) + tx; - vertexData[5] = (d * h0) + (b * w0) + ty; - // xy - vertexData[6] = (a * w1) + (c * h0) + tx; - vertexData[7] = (d * h0) + (b * w1) + ty; - if (this._roundPixels) { - var resolution = settings.RESOLUTION; - for (var i = 0; i < vertexData.length; ++i) { - vertexData[i] = Math.round((vertexData[i] * resolution | 0) / resolution); - } - } - }; - /** - * Calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData. - * - * This is used to ensure that the true width and height of a trimmed texture is respected. - */ - Sprite.prototype.calculateTrimmedVertices = function () { - if (!this.vertexTrimmedData) { - this.vertexTrimmedData = new Float32Array(8); - } - else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { - return; - } - this._transformTrimmedID = this.transform._worldID; - this._textureTrimmedID = this._texture._updateID; - // lets do some special trim code! - var texture = this._texture; - var vertexData = this.vertexTrimmedData; - var orig = texture.orig; - var anchor = this._anchor; - // lets calculate the new untrimmed bounds.. - var wt = this.transform.worldTransform; - var a = wt.a; - var b = wt.b; - var c = wt.c; - var d = wt.d; - var tx = wt.tx; - var ty = wt.ty; - var w1 = -anchor._x * orig.width; - var w0 = w1 + orig.width; - var h1 = -anchor._y * orig.height; - var h0 = h1 + orig.height; - // xy - vertexData[0] = (a * w1) + (c * h1) + tx; - vertexData[1] = (d * h1) + (b * w1) + ty; - // xy - vertexData[2] = (a * w0) + (c * h1) + tx; - vertexData[3] = (d * h1) + (b * w0) + ty; - // xy - vertexData[4] = (a * w0) + (c * h0) + tx; - vertexData[5] = (d * h0) + (b * w0) + ty; - // xy - vertexData[6] = (a * w1) + (c * h0) + tx; - vertexData[7] = (d * h0) + (b * w1) + ty; - }; - /** - * - * Renders the object using the WebGL renderer - * @param renderer - The webgl renderer to use. - */ - Sprite.prototype._render = function (renderer) { - this.calculateVertices(); - renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); - renderer.plugins[this.pluginName].render(this); - }; - /** Updates the bounds of the sprite. */ - Sprite.prototype._calculateBounds = function () { - var trim = this._texture.trim; - var orig = this._texture.orig; - // First lets check to see if the current texture has a trim.. - if (!trim || (trim.width === orig.width && trim.height === orig.height)) { - // no trim! lets use the usual calculations.. - this.calculateVertices(); - this._bounds.addQuad(this.vertexData); - } - else { - // lets calculate a special trimmed bounds... - this.calculateTrimmedVertices(); - this._bounds.addQuad(this.vertexTrimmedData); - } - }; - /** - * Gets the local bounds of the sprite object. - * @param rect - Optional output rectangle. - * @returns The bounds. - */ - Sprite.prototype.getLocalBounds = function (rect) { - // we can do a fast local bounds if the sprite has no children! - if (this.children.length === 0) { - if (!this._localBounds) { - this._localBounds = new Bounds(); - } - this._localBounds.minX = this._texture.orig.width * -this._anchor._x; - this._localBounds.minY = this._texture.orig.height * -this._anchor._y; - this._localBounds.maxX = this._texture.orig.width * (1 - this._anchor._x); - this._localBounds.maxY = this._texture.orig.height * (1 - this._anchor._y); - if (!rect) { - if (!this._localBoundsRect) { - this._localBoundsRect = new Rectangle(); - } - rect = this._localBoundsRect; - } - return this._localBounds.getRectangle(rect); - } - return _super.prototype.getLocalBounds.call(this, rect); - }; - /** - * Tests if a point is inside this sprite - * @param point - the point to test - * @returns The result of the test - */ - Sprite.prototype.containsPoint = function (point) { - this.worldTransform.applyInverse(point, tempPoint$2); - var width = this._texture.orig.width; - var height = this._texture.orig.height; - var x1 = -width * this.anchor.x; - var y1 = 0; - if (tempPoint$2.x >= x1 && tempPoint$2.x < x1 + width) { - y1 = -height * this.anchor.y; - if (tempPoint$2.y >= y1 && tempPoint$2.y < y1 + height) { - return true; - } - } - return false; - }; - /** - * Destroys this sprite and optionally its texture and children. - * @param options - Options parameter. A boolean will act as if all options - * have been set to that value - * @param [options.children=false] - if set to true, all the children will have their destroy - * method called as well. 'options' will be passed on to those calls. - * @param [options.texture=false] - Should it destroy the current texture of the sprite as well - * @param [options.baseTexture=false] - Should it destroy the base texture of the sprite as well - */ - Sprite.prototype.destroy = function (options) { - _super.prototype.destroy.call(this, options); - this._texture.off('update', this._onTextureUpdate, this); - this._anchor = null; - var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; - if (destroyTexture) { - var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; - this._texture.destroy(!!destroyBaseTexture); - } - this._texture = null; - }; - // some helper functions.. - /** - * Helper function that creates a new sprite based on the source you provide. - * The source can be - frame id, image url, video url, canvas element, video element, base texture - * @param {string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from - * @param {object} [options] - See {@link PIXI.BaseTexture}'s constructor for options. - * @returns The newly created sprite - */ - Sprite.from = function (source, options) { - var texture = (source instanceof Texture) - ? source - : Texture.from(source, options); - return new Sprite(texture); - }; - Object.defineProperty(Sprite.prototype, "roundPixels", { - get: function () { - return this._roundPixels; - }, - /** - * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. - * - * Advantages can include sharper image quality (like text) and faster rendering on canvas. - * The main disadvantage is movement of objects may appear less smooth. - * - * To set the global default, change {@link PIXI.settings.ROUND_PIXELS}. - * @default false - */ - set: function (value) { - if (this._roundPixels !== value) { - this._transformID = -1; - } - this._roundPixels = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Sprite.prototype, "width", { - /** The width of the sprite, setting this will actually modify the scale to achieve the value set. */ - get: function () { - return Math.abs(this.scale.x) * this._texture.orig.width; - }, - set: function (value) { - var s = sign(this.scale.x) || 1; - this.scale.x = s * value / this._texture.orig.width; - this._width = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Sprite.prototype, "height", { - /** The height of the sprite, setting this will actually modify the scale to achieve the value set. */ - get: function () { - return Math.abs(this.scale.y) * this._texture.orig.height; - }, - set: function (value) { - var s = sign(this.scale.y) || 1; - this.scale.y = s * value / this._texture.orig.height; - this._height = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Sprite.prototype, "anchor", { - /** - * The anchor sets the origin point of the sprite. The default value is taken from the {@link PIXI.Texture|Texture} - * and passed to the constructor. - * - * The default is `(0,0)`, this means the sprite's origin is the top left. - * - * Setting the anchor to `(0.5,0.5)` means the sprite's origin is centered. - * - * Setting the anchor to `(1,1)` would mean the sprite's origin point will be the bottom right corner. - * - * If you pass only single parameter, it will set both x and y to the same value as shown in the example below. - * @example - * const sprite = new PIXI.Sprite(texture); - * sprite.anchor.set(0.5); // This will set the origin to center. (0.5) is same as (0.5, 0.5). - */ - get: function () { - return this._anchor; - }, - set: function (value) { - this._anchor.copyFrom(value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Sprite.prototype, "tint", { - /** - * The tint applied to the sprite. This is a hex value. - * - * A value of 0xFFFFFF will remove any tint effect. - * @default 0xFFFFFF - */ - get: function () { - return this._tint; - }, - set: function (value) { - this._tint = value; - this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Sprite.prototype, "texture", { - /** The texture that the sprite is using. */ - get: function () { - return this._texture; - }, - set: function (value) { - if (this._texture === value) { - return; - } - if (this._texture) { - this._texture.off('update', this._onTextureUpdate, this); - } - this._texture = value || Texture.EMPTY; - this._cachedTint = 0xFFFFFF; - this._textureID = -1; - this._textureTrimmedID = -1; - if (value) { - // wait for the texture to load - if (value.baseTexture.valid) { - this._onTextureUpdate(); - } - else { - value.once('update', this._onTextureUpdate, this); - } - } - }, - enumerable: false, - configurable: true - }); - return Sprite; - }(Container)); - - /*! - * @pixi/text - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/text is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$c = function(d, b) { - extendStatics$c = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$c(d, b); - }; - - function __extends$c(d, b) { - extendStatics$c(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** - * Constants that define the type of gradient on text. - * @static - * @constant - * @name TEXT_GRADIENT - * @memberof PIXI - * @type {object} - * @property {number} LINEAR_VERTICAL Vertical gradient - * @property {number} LINEAR_HORIZONTAL Linear gradient - */ - exports.TEXT_GRADIENT = void 0; - (function (TEXT_GRADIENT) { - TEXT_GRADIENT[TEXT_GRADIENT["LINEAR_VERTICAL"] = 0] = "LINEAR_VERTICAL"; - TEXT_GRADIENT[TEXT_GRADIENT["LINEAR_HORIZONTAL"] = 1] = "LINEAR_HORIZONTAL"; - })(exports.TEXT_GRADIENT || (exports.TEXT_GRADIENT = {})); - - // disabling eslint for now, going to rewrite this in v5 - var defaultStyle = { - align: 'left', - breakWords: false, - dropShadow: false, - dropShadowAlpha: 1, - dropShadowAngle: Math.PI / 6, - dropShadowBlur: 0, - dropShadowColor: 'black', - dropShadowDistance: 5, - fill: 'black', - fillGradientType: exports.TEXT_GRADIENT.LINEAR_VERTICAL, - fillGradientStops: [], - fontFamily: 'Arial', - fontSize: 26, - fontStyle: 'normal', - fontVariant: 'normal', - fontWeight: 'normal', - letterSpacing: 0, - lineHeight: 0, - lineJoin: 'miter', - miterLimit: 10, - padding: 0, - stroke: 'black', - strokeThickness: 0, - textBaseline: 'alphabetic', - trim: false, - whiteSpace: 'pre', - wordWrap: false, - wordWrapWidth: 100, - leading: 0, - }; - var genericFontFamilies = [ - 'serif', - 'sans-serif', - 'monospace', - 'cursive', - 'fantasy', - 'system-ui' ]; - /** - * A TextStyle Object contains information to decorate a Text objects. - * - * An instance can be shared between multiple Text objects; then changing the style will update all text objects using it. - * - * A tool can be used to generate a text style [here](https://pixijs.io/pixi-text-style). - * - * @memberof PIXI - */ - var TextStyle = /** @class */ (function () { - /** - * @param {object} [style] - The style parameters - * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), - * does not affect single line text - * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it - * needs wordWrap to be set to true - * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text - * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow - * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow - * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius - * @param {string|number} [style.dropShadowColor='black'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' - * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow - * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas - * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient - * eg ['#000000','#FFFFFF'] - * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} - * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours - * to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} - * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set - * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. - * @param {string|string[]} [style.fontFamily='Arial'] - The font family - * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, - * equivalents are '26px','20pt','160%' or '1.6em') - * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') - * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') - * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', - * '200', '300', '400', '500', '600', '700', '800' or '900') - * @param {number} [style.leading=0] - The space between lines - * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 - * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses - * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve - * spiked text issues. Possible values "miter" (creates a sharp corner), "round" (creates a round corner) or "bevel" - * (creates a squared corner). - * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce - * or increase the spikiness of rendered text. - * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from - * happening by adding padding to all sides of the text. - * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke - * e.g 'blue', '#FCFF00' - * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. - * Default is 0 (no stroke) - * @param {boolean} [style.trim=false] - Trim transparent borders - * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. - * @param {string} [style.whiteSpace='pre'] - Determines whether newlines & spaces are collapsed or preserved "normal" - * (collapse, collapse), "pre" (preserve, preserve) | "pre-line" (preserve, collapse). It needs wordWrap to be set to true - * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used - * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true - */ - function TextStyle(style) { - this.styleID = 0; - this.reset(); - deepCopyProperties(this, style, style); - } - /** - * Creates a new TextStyle object with the same values as this one. - * Note that the only the properties of the object are cloned. - * - * @return New cloned TextStyle object - */ - TextStyle.prototype.clone = function () { - var clonedProperties = {}; - deepCopyProperties(clonedProperties, this, defaultStyle); - return new TextStyle(clonedProperties); - }; - /** Resets all properties to the defaults specified in TextStyle.prototype._default */ - TextStyle.prototype.reset = function () { - deepCopyProperties(this, defaultStyle, defaultStyle); - }; - Object.defineProperty(TextStyle.prototype, "align", { - /** - * Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text - * - * @member {string} - */ - get: function () { - return this._align; - }, - set: function (align) { - if (this._align !== align) { - this._align = align; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "breakWords", { - /** Indicates if lines can be wrapped within words, it needs wordWrap to be set to true. */ - get: function () { - return this._breakWords; - }, - set: function (breakWords) { - if (this._breakWords !== breakWords) { - this._breakWords = breakWords; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "dropShadow", { - /** Set a drop shadow for the text. */ - get: function () { - return this._dropShadow; - }, - set: function (dropShadow) { - if (this._dropShadow !== dropShadow) { - this._dropShadow = dropShadow; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "dropShadowAlpha", { - /** Set alpha for the drop shadow. */ - get: function () { - return this._dropShadowAlpha; - }, - set: function (dropShadowAlpha) { - if (this._dropShadowAlpha !== dropShadowAlpha) { - this._dropShadowAlpha = dropShadowAlpha; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "dropShadowAngle", { - /** Set a angle of the drop shadow. */ - get: function () { - return this._dropShadowAngle; - }, - set: function (dropShadowAngle) { - if (this._dropShadowAngle !== dropShadowAngle) { - this._dropShadowAngle = dropShadowAngle; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "dropShadowBlur", { - /** Set a shadow blur radius. */ - get: function () { - return this._dropShadowBlur; - }, - set: function (dropShadowBlur) { - if (this._dropShadowBlur !== dropShadowBlur) { - this._dropShadowBlur = dropShadowBlur; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "dropShadowColor", { - /** A fill style to be used on the dropshadow e.g 'red', '#00FF00'. */ - get: function () { - return this._dropShadowColor; - }, - set: function (dropShadowColor) { - var outputColor = getColor(dropShadowColor); - if (this._dropShadowColor !== outputColor) { - this._dropShadowColor = outputColor; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "dropShadowDistance", { - /** Set a distance of the drop shadow. */ - get: function () { - return this._dropShadowDistance; - }, - set: function (dropShadowDistance) { - if (this._dropShadowDistance !== dropShadowDistance) { - this._dropShadowDistance = dropShadowDistance; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "fill", { - /** - * A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'. - * - * Can be an array to create a gradient eg ['#000000','#FFFFFF'] - * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} - * - * @member {string|string[]|number|number[]|CanvasGradient|CanvasPattern} - */ - get: function () { - return this._fill; - }, - set: function (fill) { - // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as - // the setter converts to string. See this thread for more details: - // https://github.com/microsoft/TypeScript/issues/2521 - // TODO: Not sure if getColor works properly with CanvasGradient and/or CanvasPattern, can't pass in - // without casting here. - var outputColor = getColor(fill); - if (this._fill !== outputColor) { - this._fill = outputColor; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "fillGradientType", { - /** - * If fill is an array of colours to create a gradient, this can change the type/direction of the gradient. - * - * @see PIXI.TEXT_GRADIENT - */ - get: function () { - return this._fillGradientType; - }, - set: function (fillGradientType) { - if (this._fillGradientType !== fillGradientType) { - this._fillGradientType = fillGradientType; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "fillGradientStops", { - /** - * If fill is an array of colours to create a gradient, this array can set the stop points - * (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. - */ - get: function () { - return this._fillGradientStops; - }, - set: function (fillGradientStops) { - if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) { - this._fillGradientStops = fillGradientStops; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "fontFamily", { - /** The font family. */ - get: function () { - return this._fontFamily; - }, - set: function (fontFamily) { - if (this.fontFamily !== fontFamily) { - this._fontFamily = fontFamily; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "fontSize", { - /** - * The font size - * (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em') - */ - get: function () { - return this._fontSize; - }, - set: function (fontSize) { - if (this._fontSize !== fontSize) { - this._fontSize = fontSize; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "fontStyle", { - /** - * The font style - * ('normal', 'italic' or 'oblique') - * - * @member {string} - */ - get: function () { - return this._fontStyle; - }, - set: function (fontStyle) { - if (this._fontStyle !== fontStyle) { - this._fontStyle = fontStyle; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "fontVariant", { - /** - * The font variant - * ('normal' or 'small-caps') - * - * @member {string} - */ - get: function () { - return this._fontVariant; - }, - set: function (fontVariant) { - if (this._fontVariant !== fontVariant) { - this._fontVariant = fontVariant; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "fontWeight", { - /** - * The font weight - * ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900') - * - * @member {string} - */ - get: function () { - return this._fontWeight; - }, - set: function (fontWeight) { - if (this._fontWeight !== fontWeight) { - this._fontWeight = fontWeight; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "letterSpacing", { - /** The amount of spacing between letters, default is 0. */ - get: function () { - return this._letterSpacing; - }, - set: function (letterSpacing) { - if (this._letterSpacing !== letterSpacing) { - this._letterSpacing = letterSpacing; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "lineHeight", { - /** The line height, a number that represents the vertical space that a letter uses. */ - get: function () { - return this._lineHeight; - }, - set: function (lineHeight) { - if (this._lineHeight !== lineHeight) { - this._lineHeight = lineHeight; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "leading", { - /** The space between lines. */ - get: function () { - return this._leading; - }, - set: function (leading) { - if (this._leading !== leading) { - this._leading = leading; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "lineJoin", { - /** - * The lineJoin property sets the type of corner created, it can resolve spiked text issues. - * Default is 'miter' (creates a sharp corner). - * - * @member {string} - */ - get: function () { - return this._lineJoin; - }, - set: function (lineJoin) { - if (this._lineJoin !== lineJoin) { - this._lineJoin = lineJoin; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "miterLimit", { - /** - * The miter limit to use when using the 'miter' lineJoin mode. - * - * This can reduce or increase the spikiness of rendered text. - */ - get: function () { - return this._miterLimit; - }, - set: function (miterLimit) { - if (this._miterLimit !== miterLimit) { - this._miterLimit = miterLimit; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "padding", { - /** - * Occasionally some fonts are cropped. Adding some padding will prevent this from happening - * by adding padding to all sides of the text. - */ - get: function () { - return this._padding; - }, - set: function (padding) { - if (this._padding !== padding) { - this._padding = padding; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "stroke", { - /** - * A canvas fillstyle that will be used on the text stroke - * e.g 'blue', '#FCFF00' - */ - get: function () { - return this._stroke; - }, - set: function (stroke) { - // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as - // the setter converts to string. See this thread for more details: - // https://github.com/microsoft/TypeScript/issues/2521 - var outputColor = getColor(stroke); - if (this._stroke !== outputColor) { - this._stroke = outputColor; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "strokeThickness", { - /** - * A number that represents the thickness of the stroke. - * - * @default 0 - */ - get: function () { - return this._strokeThickness; - }, - set: function (strokeThickness) { - if (this._strokeThickness !== strokeThickness) { - this._strokeThickness = strokeThickness; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "textBaseline", { - /** - * The baseline of the text that is rendered. - * - * @member {string} - */ - get: function () { - return this._textBaseline; - }, - set: function (textBaseline) { - if (this._textBaseline !== textBaseline) { - this._textBaseline = textBaseline; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "trim", { - /** Trim transparent borders. */ - get: function () { - return this._trim; - }, - set: function (trim) { - if (this._trim !== trim) { - this._trim = trim; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "whiteSpace", { - /** - * How newlines and spaces should be handled. - * Default is 'pre' (preserve, preserve). - * - * value | New lines | Spaces - * --- | --- | --- - * 'normal' | Collapse | Collapse - * 'pre' | Preserve | Preserve - * 'pre-line' | Preserve | Collapse - * - * @member {string} - */ - get: function () { - return this._whiteSpace; - }, - set: function (whiteSpace) { - if (this._whiteSpace !== whiteSpace) { - this._whiteSpace = whiteSpace; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "wordWrap", { - /** Indicates if word wrap should be used. */ - get: function () { - return this._wordWrap; - }, - set: function (wordWrap) { - if (this._wordWrap !== wordWrap) { - this._wordWrap = wordWrap; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "wordWrapWidth", { - /** The width at which text will wrap, it needs wordWrap to be set to true. */ - get: function () { - return this._wordWrapWidth; - }, - set: function (wordWrapWidth) { - if (this._wordWrapWidth !== wordWrapWidth) { - this._wordWrapWidth = wordWrapWidth; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - /** - * Generates a font style string to use for `TextMetrics.measureFont()`. - * - * @return Font style string, for passing to `TextMetrics.measureFont()` - */ - TextStyle.prototype.toFontString = function () { - // build canvas api font setting from individual components. Convert a numeric this.fontSize to px - var fontSizeString = (typeof this.fontSize === 'number') ? this.fontSize + "px" : this.fontSize; - // Clean-up fontFamily property by quoting each font name - // this will support font names with spaces - var fontFamilies = this.fontFamily; - if (!Array.isArray(this.fontFamily)) { - fontFamilies = this.fontFamily.split(','); - } - for (var i = fontFamilies.length - 1; i >= 0; i--) { - // Trim any extra white-space - var fontFamily = fontFamilies[i].trim(); - // Check if font already contains strings - if (!(/([\"\'])[^\'\"]+\1/).test(fontFamily) && genericFontFamilies.indexOf(fontFamily) < 0) { - fontFamily = "\"" + fontFamily + "\""; - } - fontFamilies[i] = fontFamily; - } - return this.fontStyle + " " + this.fontVariant + " " + this.fontWeight + " " + fontSizeString + " " + fontFamilies.join(','); - }; - return TextStyle; - }()); - /** - * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. - * @private - * @param color - * @return The color as a string. - */ - function getSingleColor(color) { - if (typeof color === 'number') { - return hex2string(color); - } - else if (typeof color === 'string') { - if (color.indexOf('0x') === 0) { - color = color.replace('0x', '#'); - } - } - return color; - } - function getColor(color) { - if (!Array.isArray(color)) { - return getSingleColor(color); - } - else { - for (var i = 0; i < color.length; ++i) { - color[i] = getSingleColor(color[i]); - } - return color; - } - } - /** - * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. - * This version can also convert array of colors - * @private - * @param array1 - First array to compare - * @param array2 - Second array to compare - * @return Do the arrays contain the same values in the same order - */ - function areArraysEqual(array1, array2) { - if (!Array.isArray(array1) || !Array.isArray(array2)) { - return false; - } - if (array1.length !== array2.length) { - return false; - } - for (var i = 0; i < array1.length; ++i) { - if (array1[i] !== array2[i]) { - return false; - } - } - return true; - } - /** - * Utility function to ensure that object properties are copied by value, and not by reference - * @private - * @param target - Target object to copy properties into - * @param source - Source object for the properties to copy - * @param propertyObj - Object containing properties names we want to loop over - */ - function deepCopyProperties(target, source, propertyObj) { - for (var prop in propertyObj) { - if (Array.isArray(source[prop])) { - target[prop] = source[prop].slice(); - } - else { - target[prop] = source[prop]; - } - } - } - - // Default settings used for all getContext calls - var contextSettings = { - // TextMetrics requires getImageData readback for measuring fonts. - willReadFrequently: true, - }; - /** - * The TextMetrics object represents the measurement of a block of text with a specified style. - * - * ```js - * let style = new PIXI.TextStyle({fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}) - * let textMetrics = PIXI.TextMetrics.measureText('Your text', style) - * ``` - * @memberof PIXI - */ - var TextMetrics = /** @class */ (function () { - /** - * @param text - the text that was measured - * @param style - the style that was measured - * @param width - the measured width of the text - * @param height - the measured height of the text - * @param lines - an array of the lines of text broken by new lines and wrapping if specified in style - * @param lineWidths - an array of the line widths for each line matched to `lines` - * @param lineHeight - the measured line height for this style - * @param maxLineWidth - the maximum line width for all measured lines - * @param {PIXI.IFontMetrics} fontProperties - the font properties object from TextMetrics.measureFont - */ - function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) { - this.text = text; - this.style = style; - this.width = width; - this.height = height; - this.lines = lines; - this.lineWidths = lineWidths; - this.lineHeight = lineHeight; - this.maxLineWidth = maxLineWidth; - this.fontProperties = fontProperties; - } - /** - * Measures the supplied string of text and returns a Rectangle. - * @param text - The text to measure. - * @param style - The text style to use for measuring - * @param wordWrap - Override for if word-wrap should be applied to the text. - * @param canvas - optional specification of the canvas to use for measuring. - * @returns Measured width and height of the text. - */ - TextMetrics.measureText = function (text, style, wordWrap, canvas) { - if (canvas === void 0) { canvas = TextMetrics._canvas; } - wordWrap = (wordWrap === undefined || wordWrap === null) ? style.wordWrap : wordWrap; - var font = style.toFontString(); - var fontProperties = TextMetrics.measureFont(font); - // fallback in case UA disallow canvas data extraction - // (toDataURI, getImageData functions) - if (fontProperties.fontSize === 0) { - fontProperties.fontSize = style.fontSize; - fontProperties.ascent = style.fontSize; - } - var context = canvas.getContext('2d', contextSettings); - context.font = font; - var outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text; - var lines = outputText.split(/(?:\r\n|\r|\n)/); - var lineWidths = new Array(lines.length); - var maxLineWidth = 0; - for (var i = 0; i < lines.length; i++) { - var lineWidth = context.measureText(lines[i]).width + ((lines[i].length - 1) * style.letterSpacing); - lineWidths[i] = lineWidth; - maxLineWidth = Math.max(maxLineWidth, lineWidth); - } - var width = maxLineWidth + style.strokeThickness; - if (style.dropShadow) { - width += style.dropShadowDistance; - } - var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; - var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) - + ((lines.length - 1) * (lineHeight + style.leading)); - if (style.dropShadow) { - height += style.dropShadowDistance; - } - return new TextMetrics(text, style, width, height, lines, lineWidths, lineHeight + style.leading, maxLineWidth, fontProperties); - }; - /** - * Applies newlines to a string to have it optimally fit into the horizontal - * bounds set by the Text object's wordWrapWidth property. - * @param text - String to apply word wrapping to - * @param style - the style to use when wrapping - * @param canvas - optional specification of the canvas to use for measuring. - * @returns New string with new lines applied where required - */ - TextMetrics.wordWrap = function (text, style, canvas) { - if (canvas === void 0) { canvas = TextMetrics._canvas; } - var context = canvas.getContext('2d', contextSettings); - var width = 0; - var line = ''; - var lines = ''; - var cache = Object.create(null); - var letterSpacing = style.letterSpacing, whiteSpace = style.whiteSpace; - // How to handle whitespaces - var collapseSpaces = TextMetrics.collapseSpaces(whiteSpace); - var collapseNewlines = TextMetrics.collapseNewlines(whiteSpace); - // whether or not spaces may be added to the beginning of lines - var canPrependSpaces = !collapseSpaces; - // There is letterSpacing after every char except the last one - // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_! - // so for convenience the above needs to be compared to width + 1 extra letterSpace - // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!_ - // ________________________________________________ - // And then the final space is simply no appended to each line - var wordWrapWidth = style.wordWrapWidth + letterSpacing; - // break text into words, spaces and newline chars - var tokens = TextMetrics.tokenize(text); - for (var i = 0; i < tokens.length; i++) { - // get the word, space or newlineChar - var token = tokens[i]; - // if word is a new line - if (TextMetrics.isNewline(token)) { - // keep the new line - if (!collapseNewlines) { - lines += TextMetrics.addLine(line); - canPrependSpaces = !collapseSpaces; - line = ''; - width = 0; - continue; - } - // if we should collapse new lines - // we simply convert it into a space - token = ' '; - } - // if we should collapse repeated whitespaces - if (collapseSpaces) { - // check both this and the last tokens for spaces - var currIsBreakingSpace = TextMetrics.isBreakingSpace(token); - var lastIsBreakingSpace = TextMetrics.isBreakingSpace(line[line.length - 1]); - if (currIsBreakingSpace && lastIsBreakingSpace) { - continue; - } - } - // get word width from cache if possible - var tokenWidth = TextMetrics.getFromCache(token, letterSpacing, cache, context); - // word is longer than desired bounds - if (tokenWidth > wordWrapWidth) { - // if we are not already at the beginning of a line - if (line !== '') { - // start newlines for overflow words - lines += TextMetrics.addLine(line); - line = ''; - width = 0; - } - // break large word over multiple lines - if (TextMetrics.canBreakWords(token, style.breakWords)) { - // break word into characters - var characters = TextMetrics.wordWrapSplit(token); - // loop the characters - for (var j = 0; j < characters.length; j++) { - var char = characters[j]; - var k = 1; - // we are not at the end of the token - while (characters[j + k]) { - var nextChar = characters[j + k]; - var lastChar = char[char.length - 1]; - // should not split chars - if (!TextMetrics.canBreakChars(lastChar, nextChar, token, j, style.breakWords)) { - // combine chars & move forward one - char += nextChar; - } - else { - break; - } - k++; - } - j += char.length - 1; - var characterWidth = TextMetrics.getFromCache(char, letterSpacing, cache, context); - if (characterWidth + width > wordWrapWidth) { - lines += TextMetrics.addLine(line); - canPrependSpaces = false; - line = ''; - width = 0; - } - line += char; - width += characterWidth; - } - } - // run word out of the bounds - else { - // if there are words in this line already - // finish that line and start a new one - if (line.length > 0) { - lines += TextMetrics.addLine(line); - line = ''; - width = 0; - } - var isLastToken = i === tokens.length - 1; - // give it its own line if it's not the end - lines += TextMetrics.addLine(token, !isLastToken); - canPrependSpaces = false; - line = ''; - width = 0; - } - } - // word could fit - else { - // word won't fit because of existing words - // start a new line - if (tokenWidth + width > wordWrapWidth) { - // if its a space we don't want it - canPrependSpaces = false; - // add a new line - lines += TextMetrics.addLine(line); - // start a new line - line = ''; - width = 0; - } - // don't add spaces to the beginning of lines - if (line.length > 0 || !TextMetrics.isBreakingSpace(token) || canPrependSpaces) { - // add the word to the current line - line += token; - // update width counter - width += tokenWidth; - } - } - } - lines += TextMetrics.addLine(line, false); - return lines; - }; - /** - * Convienience function for logging each line added during the wordWrap method. - * @param line - The line of text to add - * @param newLine - Add new line character to end - * @returns A formatted line - */ - TextMetrics.addLine = function (line, newLine) { - if (newLine === void 0) { newLine = true; } - line = TextMetrics.trimRight(line); - line = (newLine) ? line + "\n" : line; - return line; - }; - /** - * Gets & sets the widths of calculated characters in a cache object - * @param key - The key - * @param letterSpacing - The letter spacing - * @param cache - The cache - * @param context - The canvas context - * @returns The from cache. - */ - TextMetrics.getFromCache = function (key, letterSpacing, cache, context) { - var width = cache[key]; - if (typeof width !== 'number') { - var spacing = ((key.length) * letterSpacing); - width = context.measureText(key).width + spacing; - cache[key] = width; - } - return width; - }; - /** - * Determines whether we should collapse breaking spaces. - * @param whiteSpace - The TextStyle property whiteSpace - * @returns Should collapse - */ - TextMetrics.collapseSpaces = function (whiteSpace) { - return (whiteSpace === 'normal' || whiteSpace === 'pre-line'); - }; - /** - * Determines whether we should collapse newLine chars. - * @param whiteSpace - The white space - * @returns should collapse - */ - TextMetrics.collapseNewlines = function (whiteSpace) { - return (whiteSpace === 'normal'); - }; - /** - * Trims breaking whitespaces from string. - * @param text - The text - * @returns Trimmed string - */ - TextMetrics.trimRight = function (text) { - if (typeof text !== 'string') { - return ''; - } - for (var i = text.length - 1; i >= 0; i--) { - var char = text[i]; - if (!TextMetrics.isBreakingSpace(char)) { - break; - } - text = text.slice(0, -1); - } - return text; - }; - /** - * Determines if char is a newline. - * @param char - The character - * @returns True if newline, False otherwise. - */ - TextMetrics.isNewline = function (char) { - if (typeof char !== 'string') { - return false; - } - return (TextMetrics._newlines.indexOf(char.charCodeAt(0)) >= 0); - }; - /** - * Determines if char is a breaking whitespace. - * - * It allows one to determine whether char should be a breaking whitespace - * For example certain characters in CJK langs or numbers. - * It must return a boolean. - * @param char - The character - * @param [_nextChar] - The next character - * @returns True if whitespace, False otherwise. - */ - TextMetrics.isBreakingSpace = function (char, _nextChar) { - if (typeof char !== 'string') { - return false; - } - return (TextMetrics._breakingSpaces.indexOf(char.charCodeAt(0)) >= 0); - }; - /** - * Splits a string into words, breaking-spaces and newLine characters - * @param text - The text - * @returns A tokenized array - */ - TextMetrics.tokenize = function (text) { - var tokens = []; - var token = ''; - if (typeof text !== 'string') { - return tokens; - } - for (var i = 0; i < text.length; i++) { - var char = text[i]; - var nextChar = text[i + 1]; - if (TextMetrics.isBreakingSpace(char, nextChar) || TextMetrics.isNewline(char)) { - if (token !== '') { - tokens.push(token); - token = ''; - } - tokens.push(char); - continue; - } - token += char; - } - if (token !== '') { - tokens.push(token); - } - return tokens; - }; - /** - * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. - * - * It allows one to customise which words should break - * Examples are if the token is CJK or numbers. - * It must return a boolean. - * @param _token - The token - * @param breakWords - The style attr break words - * @returns Whether to break word or not - */ - TextMetrics.canBreakWords = function (_token, breakWords) { - return breakWords; - }; - /** - * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. - * - * It allows one to determine whether a pair of characters - * should be broken by newlines - * For example certain characters in CJK langs or numbers. - * It must return a boolean. - * @param _char - The character - * @param _nextChar - The next character - * @param _token - The token/word the characters are from - * @param _index - The index in the token of the char - * @param _breakWords - The style attr break words - * @returns whether to break word or not - */ - TextMetrics.canBreakChars = function (_char, _nextChar, _token, _index, _breakWords) { - return true; - }; - /** - * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. - * - * It is called when a token (usually a word) has to be split into separate pieces - * in order to determine the point to break a word. - * It must return an array of characters. - * @example - * // Correctly splits emojis, eg "🤪🤪" will result in two element array, each with one emoji. - * TextMetrics.wordWrapSplit = (token) => [...token]; - * @param token - The token to split - * @returns The characters of the token - */ - TextMetrics.wordWrapSplit = function (token) { - return token.split(''); - }; - /** - * Calculates the ascent, descent and fontSize of a given font-style - * @param font - String representing the style of the font - * @returns Font properties object - */ - TextMetrics.measureFont = function (font) { - // as this method is used for preparing assets, don't recalculate things if we don't need to - if (TextMetrics._fonts[font]) { - return TextMetrics._fonts[font]; - } - var properties = { - ascent: 0, - descent: 0, - fontSize: 0, - }; - var canvas = TextMetrics._canvas; - var context = TextMetrics._context; - context.font = font; - var metricsString = TextMetrics.METRICS_STRING + TextMetrics.BASELINE_SYMBOL; - var width = Math.ceil(context.measureText(metricsString).width); - var baseline = Math.ceil(context.measureText(TextMetrics.BASELINE_SYMBOL).width); - var height = Math.ceil(TextMetrics.HEIGHT_MULTIPLIER * baseline); - baseline = baseline * TextMetrics.BASELINE_MULTIPLIER | 0; - canvas.width = width; - canvas.height = height; - context.fillStyle = '#f00'; - context.fillRect(0, 0, width, height); - context.font = font; - context.textBaseline = 'alphabetic'; - context.fillStyle = '#000'; - context.fillText(metricsString, 0, baseline); - var imagedata = context.getImageData(0, 0, width, height).data; - var pixels = imagedata.length; - var line = width * 4; - var i = 0; - var idx = 0; - var stop = false; - // ascent. scan from top to bottom until we find a non red pixel - for (i = 0; i < baseline; ++i) { - for (var j = 0; j < line; j += 4) { - if (imagedata[idx + j] !== 255) { - stop = true; - break; - } - } - if (!stop) { - idx += line; - } - else { - break; - } - } - properties.ascent = baseline - i; - idx = pixels - line; - stop = false; - // descent. scan from bottom to top until we find a non red pixel - for (i = height; i > baseline; --i) { - for (var j = 0; j < line; j += 4) { - if (imagedata[idx + j] !== 255) { - stop = true; - break; - } - } - if (!stop) { - idx -= line; - } - else { - break; - } - } - properties.descent = i - baseline; - properties.fontSize = properties.ascent + properties.descent; - TextMetrics._fonts[font] = properties; - return properties; - }; - /** - * Clear font metrics in metrics cache. - * @param {string} [font] - font name. If font name not set then clear cache for all fonts. - */ - TextMetrics.clearMetrics = function (font) { - if (font === void 0) { font = ''; } - if (font) { - delete TextMetrics._fonts[font]; - } - else { - TextMetrics._fonts = {}; - } - }; - Object.defineProperty(TextMetrics, "_canvas", { - /** - * Cached canvas element for measuring text - * TODO: this should be private, but isn't because of backward compat, will fix later. - * @ignore - */ - get: function () { - if (!TextMetrics.__canvas) { - var canvas = void 0; - try { - // OffscreenCanvas2D measureText can be up to 40% faster. - var c = new OffscreenCanvas(0, 0); - var context = c.getContext('2d', contextSettings); - if (context && context.measureText) { - TextMetrics.__canvas = c; - return c; - } - canvas = settings.ADAPTER.createCanvas(); - } - catch (ex) { - canvas = settings.ADAPTER.createCanvas(); - } - canvas.width = canvas.height = 10; - TextMetrics.__canvas = canvas; - } - return TextMetrics.__canvas; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextMetrics, "_context", { - /** - * TODO: this should be private, but isn't because of backward compat, will fix later. - * @ignore - */ - get: function () { - if (!TextMetrics.__context) { - TextMetrics.__context = TextMetrics._canvas.getContext('2d', contextSettings); - } - return TextMetrics.__context; - }, - enumerable: false, - configurable: true - }); - return TextMetrics; - }()); - /** - * Internal return object for {@link PIXI.TextMetrics.measureFont `TextMetrics.measureFont`}. - * @typedef {object} FontMetrics - * @property {number} ascent - The ascent distance - * @property {number} descent - The descent distance - * @property {number} fontSize - Font size from ascent to descent - * @memberof PIXI.TextMetrics - * @private - */ - /** - * Cache of {@see PIXI.TextMetrics.FontMetrics} objects. - * @memberof PIXI.TextMetrics - * @type {object} - * @private - */ - TextMetrics._fonts = {}; - /** - * String used for calculate font metrics. - * These characters are all tall to help calculate the height required for text. - * @static - * @memberof PIXI.TextMetrics - * @name METRICS_STRING - * @type {string} - * @default |ÉqÅ - */ - TextMetrics.METRICS_STRING = '|ÉqÅ'; - /** - * Baseline symbol for calculate font metrics. - * @static - * @memberof PIXI.TextMetrics - * @name BASELINE_SYMBOL - * @type {string} - * @default M - */ - TextMetrics.BASELINE_SYMBOL = 'M'; - /** - * Baseline multiplier for calculate font metrics. - * @static - * @memberof PIXI.TextMetrics - * @name BASELINE_MULTIPLIER - * @type {number} - * @default 1.4 - */ - TextMetrics.BASELINE_MULTIPLIER = 1.4; - /** - * Height multiplier for setting height of canvas to calculate font metrics. - * @static - * @memberof PIXI.TextMetrics - * @name HEIGHT_MULTIPLIER - * @type {number} - * @default 2.00 - */ - TextMetrics.HEIGHT_MULTIPLIER = 2.0; - /** - * Cache of new line chars. - * @memberof PIXI.TextMetrics - * @type {number[]} - * @private - */ - TextMetrics._newlines = [ - 0x000A, - 0x000D ]; - /** - * Cache of breaking spaces. - * @memberof PIXI.TextMetrics - * @type {number[]} - * @private - */ - TextMetrics._breakingSpaces = [ - 0x0009, - 0x0020, - 0x2000, - 0x2001, - 0x2002, - 0x2003, - 0x2004, - 0x2005, - 0x2006, - 0x2008, - 0x2009, - 0x200A, - 0x205F, - 0x3000 ]; - /** - * A number, or a string containing a number. - * @memberof PIXI - * @typedef {object} IFontMetrics - * @property {number} ascent - Font ascent - * @property {number} descent - Font descent - * @property {number} fontSize - Font size - */ - - var defaultDestroyOptions = { - texture: true, - children: false, - baseTexture: true, - }; - /** - * A Text Object will create a line or multiple lines of text. - * - * The text is created using the [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API). - * - * The primary advantage of this class over BitmapText is that you have great control over the style of the text, - * which you can change at runtime. - * - * The primary disadvantages is that each piece of text has it's own texture, which can use more memory. - * When text changes, this texture has to be re-generated and re-uploaded to the GPU, taking up time. - * - * To split a line you can use '\n' in your text string, or, on the `style` object, - * change its `wordWrap` property to true and and give the `wordWrapWidth` property a value. - * - * A Text can be created directly from a string and a style object, - * which can be generated [here](https://pixijs.io/pixi-text-style). - * - * ```js - * let text = new PIXI.Text('This is a PixiJS text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); - * ``` - * @memberof PIXI - */ - var Text = /** @class */ (function (_super) { - __extends$c(Text, _super); - /** - * @param text - The string that you would like the text to display - * @param {object|PIXI.TextStyle} [style] - The style parameters - * @param canvas - The canvas element for drawing text - */ - function Text(text, style, canvas) { - var _this = this; - var ownCanvas = false; - if (!canvas) { - canvas = settings.ADAPTER.createCanvas(); - ownCanvas = true; - } - canvas.width = 3; - canvas.height = 3; - var texture = Texture.from(canvas); - texture.orig = new Rectangle(); - texture.trim = new Rectangle(); - _this = _super.call(this, texture) || this; - _this._ownCanvas = ownCanvas; - _this.canvas = canvas; - _this.context = canvas.getContext('2d', { - // required for trimming to work without warnings - willReadFrequently: true, - }); - _this._resolution = settings.RESOLUTION; - _this._autoResolution = true; - _this._text = null; - _this._style = null; - _this._styleListener = null; - _this._font = ''; - _this.text = text; - _this.style = style; - _this.localStyleID = -1; - return _this; - } - /** - * Renders text to its canvas, and updates its texture. - * - * By default this is used internally to ensure the texture is correct before rendering, - * but it can be used called externally, for example from this class to 'pre-generate' the texture from a piece of text, - * and then shared across multiple Sprites. - * @param respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. - */ - Text.prototype.updateText = function (respectDirty) { - var style = this._style; - // check if style has changed.. - if (this.localStyleID !== style.styleID) { - this.dirty = true; - this.localStyleID = style.styleID; - } - if (!this.dirty && respectDirty) { - return; - } - this._font = this._style.toFontString(); - var context = this.context; - var measured = TextMetrics.measureText(this._text || ' ', this._style, this._style.wordWrap, this.canvas); - var width = measured.width; - var height = measured.height; - var lines = measured.lines; - var lineHeight = measured.lineHeight; - var lineWidths = measured.lineWidths; - var maxLineWidth = measured.maxLineWidth; - var fontProperties = measured.fontProperties; - this.canvas.width = Math.ceil(Math.ceil((Math.max(1, width) + (style.padding * 2))) * this._resolution); - this.canvas.height = Math.ceil(Math.ceil((Math.max(1, height) + (style.padding * 2))) * this._resolution); - context.scale(this._resolution, this._resolution); - context.clearRect(0, 0, this.canvas.width, this.canvas.height); - context.font = this._font; - context.lineWidth = style.strokeThickness; - context.textBaseline = style.textBaseline; - context.lineJoin = style.lineJoin; - context.miterLimit = style.miterLimit; - var linePositionX; - var linePositionY; - // require 2 passes if a shadow; the first to draw the drop shadow, the second to draw the text - var passesCount = style.dropShadow ? 2 : 1; - // For v4, we drew text at the colours of the drop shadow underneath the normal text. This gave the correct zIndex, - // but features such as alpha and shadowblur did not look right at all, since we were using actual text as a shadow. - // - // For v5.0.0, we moved over to just use the canvas API for drop shadows, which made them look much nicer and more - // visually please, but now because the stroke is drawn and then the fill, drop shadows would appear on both the fill - // and the stroke; and fill drop shadows would appear over the top of the stroke. - // - // For v5.1.1, the new route is to revert to v4 style of drawing text first to get the drop shadows underneath normal - // text, but instead drawing text in the correct location, we'll draw it off screen (-paddingY), and then adjust the - // drop shadow so only that appears on screen (+paddingY). Now we'll have the correct draw order of the shadow - // beneath the text, whilst also having the proper text shadow styling. - for (var i = 0; i < passesCount; ++i) { - var isShadowPass = style.dropShadow && i === 0; - // we only want the drop shadow, so put text way off-screen - var dsOffsetText = isShadowPass ? Math.ceil(Math.max(1, height) + (style.padding * 2)) : 0; - var dsOffsetShadow = dsOffsetText * this._resolution; - if (isShadowPass) { - // On Safari, text with gradient and drop shadows together do not position correctly - // if the scale of the canvas is not 1: https://bugs.webkit.org/show_bug.cgi?id=197689 - // Therefore we'll set the styles to be a plain black whilst generating this drop shadow - context.fillStyle = 'black'; - context.strokeStyle = 'black'; - var dropShadowColor = style.dropShadowColor; - var rgb = hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : string2hex(dropShadowColor)); - var dropShadowBlur = style.dropShadowBlur * this._resolution; - var dropShadowDistance = style.dropShadowDistance * this._resolution; - context.shadowColor = "rgba(" + rgb[0] * 255 + "," + rgb[1] * 255 + "," + rgb[2] * 255 + "," + style.dropShadowAlpha + ")"; - context.shadowBlur = dropShadowBlur; - context.shadowOffsetX = Math.cos(style.dropShadowAngle) * dropShadowDistance; - context.shadowOffsetY = (Math.sin(style.dropShadowAngle) * dropShadowDistance) + dsOffsetShadow; - } - else { - // set canvas text styles - context.fillStyle = this._generateFillStyle(style, lines, measured); - // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as - // the setter converts to string. See this thread for more details: - // https://github.com/microsoft/TypeScript/issues/2521 - context.strokeStyle = style.stroke; - context.shadowColor = 'black'; - context.shadowBlur = 0; - context.shadowOffsetX = 0; - context.shadowOffsetY = 0; - } - var linePositionYShift = (lineHeight - fontProperties.fontSize) / 2; - if (!Text.nextLineHeightBehavior || lineHeight - fontProperties.fontSize < 0) { - linePositionYShift = 0; - } - // draw lines line by line - for (var i_1 = 0; i_1 < lines.length; i_1++) { - linePositionX = style.strokeThickness / 2; - linePositionY = ((style.strokeThickness / 2) + (i_1 * lineHeight)) + fontProperties.ascent - + linePositionYShift; - if (style.align === 'right') { - linePositionX += maxLineWidth - lineWidths[i_1]; - } - else if (style.align === 'center') { - linePositionX += (maxLineWidth - lineWidths[i_1]) / 2; - } - if (style.stroke && style.strokeThickness) { - this.drawLetterSpacing(lines[i_1], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText, true); - } - if (style.fill) { - this.drawLetterSpacing(lines[i_1], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText); - } - } - } - this.updateTexture(); - }; - /** - * Render the text with letter-spacing. - * @param text - The text to draw - * @param x - Horizontal position to draw the text - * @param y - Vertical position to draw the text - * @param isStroke - Is this drawing for the outside stroke of the - * text? If not, it's for the inside fill - */ - Text.prototype.drawLetterSpacing = function (text, x, y, isStroke) { - if (isStroke === void 0) { isStroke = false; } - var style = this._style; - // letterSpacing of 0 means normal - var letterSpacing = style.letterSpacing; - // Checking that we can use moddern canvas2D api - // https://developer.chrome.com/origintrials/#/view_trial/3585991203293757441 - // note: this is unstable API, Chrome less 94 use a `textLetterSpacing`, newest use a letterSpacing - // eslint-disable-next-line max-len - var supportLetterSpacing = Text.experimentalLetterSpacing - && ('letterSpacing' in CanvasRenderingContext2D.prototype - || 'textLetterSpacing' in CanvasRenderingContext2D.prototype); - if (letterSpacing === 0 || supportLetterSpacing) { - if (supportLetterSpacing) { - this.context.letterSpacing = letterSpacing; - this.context.textLetterSpacing = letterSpacing; - } - if (isStroke) { - this.context.strokeText(text, x, y); - } - else { - this.context.fillText(text, x, y); - } - return; - } - var currentPosition = x; - // Using Array.from correctly splits characters whilst keeping emoji together. - // This is not supported on IE as it requires ES6, so regular text splitting occurs. - // This also doesn't account for emoji that are multiple emoji put together to make something else. - // Handling all of this would require a big library itself. - // https://medium.com/@giltayar/iterating-over-emoji-characters-the-es6-way-f06e4589516 - // https://github.com/orling/grapheme-splitter - var stringArray = Array.from ? Array.from(text) : text.split(''); - var previousWidth = this.context.measureText(text).width; - var currentWidth = 0; - for (var i = 0; i < stringArray.length; ++i) { - var currentChar = stringArray[i]; - if (isStroke) { - this.context.strokeText(currentChar, currentPosition, y); - } - else { - this.context.fillText(currentChar, currentPosition, y); - } - var textStr = ''; - for (var j = i + 1; j < stringArray.length; ++j) { - textStr += stringArray[j]; - } - currentWidth = this.context.measureText(textStr).width; - currentPosition += previousWidth - currentWidth + letterSpacing; - previousWidth = currentWidth; - } - }; - /** Updates texture size based on canvas size. */ - Text.prototype.updateTexture = function () { - var canvas = this.canvas; - if (this._style.trim) { - var trimmed = trimCanvas(canvas); - if (trimmed.data) { - canvas.width = trimmed.width; - canvas.height = trimmed.height; - this.context.putImageData(trimmed.data, 0, 0); - } - } - var texture = this._texture; - var style = this._style; - var padding = style.trim ? 0 : style.padding; - var baseTexture = texture.baseTexture; - texture.trim.width = texture._frame.width = canvas.width / this._resolution; - texture.trim.height = texture._frame.height = canvas.height / this._resolution; - texture.trim.x = -padding; - texture.trim.y = -padding; - texture.orig.width = texture._frame.width - (padding * 2); - texture.orig.height = texture._frame.height - (padding * 2); - // call sprite onTextureUpdate to update scale if _width or _height were set - this._onTextureUpdate(); - baseTexture.setRealSize(canvas.width, canvas.height, this._resolution); - texture.updateUvs(); - this.dirty = false; - }; - /** - * Renders the object using the WebGL renderer - * @param renderer - The renderer - */ - Text.prototype._render = function (renderer) { - if (this._autoResolution && this._resolution !== renderer.resolution) { - this._resolution = renderer.resolution; - this.dirty = true; - } - this.updateText(true); - _super.prototype._render.call(this, renderer); - }; - /** Updates the transform on all children of this container for rendering. */ - Text.prototype.updateTransform = function () { - this.updateText(true); - _super.prototype.updateTransform.call(this); - }; - Text.prototype.getBounds = function (skipUpdate, rect) { - this.updateText(true); - if (this._textureID === -1) { - // texture was updated: recalculate transforms - skipUpdate = false; - } - return _super.prototype.getBounds.call(this, skipUpdate, rect); - }; - /** - * Gets the local bounds of the text object. - * @param rect - The output rectangle. - * @returns The bounds. - */ - Text.prototype.getLocalBounds = function (rect) { - this.updateText(true); - return _super.prototype.getLocalBounds.call(this, rect); - }; - /** Calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. */ - Text.prototype._calculateBounds = function () { - this.calculateVertices(); - // if we have already done this on THIS frame. - this._bounds.addQuad(this.vertexData); - }; - /** - * Generates the fill style. Can automatically generate a gradient based on the fill style being an array - * @param style - The style. - * @param lines - The lines of text. - * @param metrics - * @returns The fill style - */ - Text.prototype._generateFillStyle = function (style, lines, metrics) { - // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as - // the setter converts to string. See this thread for more details: - // https://github.com/microsoft/TypeScript/issues/2521 - var fillStyle = style.fill; - if (!Array.isArray(fillStyle)) { - return fillStyle; - } - else if (fillStyle.length === 1) { - return fillStyle[0]; - } - // the gradient will be evenly spaced out according to how large the array is. - // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 - var gradient; - // a dropshadow will enlarge the canvas and result in the gradient being - // generated with the incorrect dimensions - var dropShadowCorrection = (style.dropShadow) ? style.dropShadowDistance : 0; - // should also take padding into account, padding can offset the gradient - var padding = style.padding || 0; - var width = (this.canvas.width / this._resolution) - dropShadowCorrection - (padding * 2); - var height = (this.canvas.height / this._resolution) - dropShadowCorrection - (padding * 2); - // make a copy of the style settings, so we can manipulate them later - var fill = fillStyle.slice(); - var fillGradientStops = style.fillGradientStops.slice(); - // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 - if (!fillGradientStops.length) { - var lengthPlus1 = fill.length + 1; - for (var i = 1; i < lengthPlus1; ++i) { - fillGradientStops.push(i / lengthPlus1); - } - } - // stop the bleeding of the last gradient on the line above to the top gradient of the this line - // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 - fill.unshift(fillStyle[0]); - fillGradientStops.unshift(0); - fill.push(fillStyle[fillStyle.length - 1]); - fillGradientStops.push(1); - if (style.fillGradientType === exports.TEXT_GRADIENT.LINEAR_VERTICAL) { - // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas - gradient = this.context.createLinearGradient(width / 2, padding, width / 2, height + padding); - // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect - // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 - // Actual height of the text itself, not counting spacing for lineHeight/leading/dropShadow etc - var textHeight = metrics.fontProperties.fontSize + style.strokeThickness; - for (var i = 0; i < lines.length; i++) { - var lastLineBottom = (metrics.lineHeight * (i - 1)) + textHeight; - var thisLineTop = metrics.lineHeight * i; - var thisLineGradientStart = thisLineTop; - // Handle case where last & this line overlap - if (i > 0 && lastLineBottom > thisLineTop) { - thisLineGradientStart = (thisLineTop + lastLineBottom) / 2; - } - var thisLineBottom = thisLineTop + textHeight; - var nextLineTop = metrics.lineHeight * (i + 1); - var thisLineGradientEnd = thisLineBottom; - // Handle case where this & next line overlap - if (i + 1 < lines.length && nextLineTop < thisLineBottom) { - thisLineGradientEnd = (thisLineBottom + nextLineTop) / 2; - } - // textHeight, but as a 0-1 size in global gradient stop space - var gradStopLineHeight = (thisLineGradientEnd - thisLineGradientStart) / height; - for (var j = 0; j < fill.length; j++) { - // 0-1 stop point for the current line, multiplied to global space afterwards - var lineStop = 0; - if (typeof fillGradientStops[j] === 'number') { - lineStop = fillGradientStops[j]; - } - else { - lineStop = j / fill.length; - } - var globalStop = Math.min(1, Math.max(0, (thisLineGradientStart / height) + (lineStop * gradStopLineHeight))); - // There's potential for floating point precision issues at the seams between gradient repeats. - globalStop = Number(globalStop.toFixed(5)); - gradient.addColorStop(globalStop, fill[j]); - } - } - } - else { - // start the gradient at the center left of the canvas, and end at the center right of the canvas - gradient = this.context.createLinearGradient(padding, height / 2, width + padding, height / 2); - // can just evenly space out the gradients in this case, as multiple lines makes no difference - // to an even left to right gradient - var totalIterations = fill.length + 1; - var currentIteration = 1; - for (var i = 0; i < fill.length; i++) { - var stop = void 0; - if (typeof fillGradientStops[i] === 'number') { - stop = fillGradientStops[i]; - } - else { - stop = currentIteration / totalIterations; - } - gradient.addColorStop(stop, fill[i]); - currentIteration++; - } - } - return gradient; - }; - /** - * Destroys this text object. - * - * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as - * the majority of the time the texture will not be shared with any other Sprites. - * @param options - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their - * destroy method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well - * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well - */ - Text.prototype.destroy = function (options) { - if (typeof options === 'boolean') { - options = { children: options }; - } - options = Object.assign({}, defaultDestroyOptions, options); - _super.prototype.destroy.call(this, options); - // set canvas width and height to 0 to workaround memory leak in Safari < 13 - // https://stackoverflow.com/questions/52532614/total-canvas-memory-use-exceeds-the-maximum-limit-safari-12 - if (this._ownCanvas) { - this.canvas.height = this.canvas.width = 0; - } - // make sure to reset the context and canvas.. dont want this hanging around in memory! - this.context = null; - this.canvas = null; - this._style = null; - }; - Object.defineProperty(Text.prototype, "width", { - /** The width of the Text, setting this will actually modify the scale to achieve the value set. */ - get: function () { - this.updateText(true); - return Math.abs(this.scale.x) * this._texture.orig.width; - }, - set: function (value) { - this.updateText(true); - var s = sign(this.scale.x) || 1; - this.scale.x = s * value / this._texture.orig.width; - this._width = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Text.prototype, "height", { - /** The height of the Text, setting this will actually modify the scale to achieve the value set. */ - get: function () { - this.updateText(true); - return Math.abs(this.scale.y) * this._texture.orig.height; - }, - set: function (value) { - this.updateText(true); - var s = sign(this.scale.y) || 1; - this.scale.y = s * value / this._texture.orig.height; - this._height = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Text.prototype, "style", { - /** - * Set the style of the text. - * - * Set up an event listener to listen for changes on the style object and mark the text as dirty. - */ - get: function () { - // TODO: Can't have different types for getter and setter. The getter shouldn't have the ITextStyle - // since the setter creates the TextStyle. See this thread for more details: - // https://github.com/microsoft/TypeScript/issues/2521 - return this._style; - }, - set: function (style) { - style = style || {}; - if (style instanceof TextStyle) { - this._style = style; - } - else { - this._style = new TextStyle(style); - } - this.localStyleID = -1; - this.dirty = true; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Text.prototype, "text", { - /** Set the copy for the text object. To split a line you can use '\n'. */ - get: function () { - return this._text; - }, - set: function (text) { - text = String(text === null || text === undefined ? '' : text); - if (this._text === text) { - return; - } - this._text = text; - this.dirty = true; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Text.prototype, "resolution", { - /** - * The resolution / device pixel ratio of the canvas. - * - * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually. - * @default 1 - */ - get: function () { - return this._resolution; - }, - set: function (value) { - this._autoResolution = false; - if (this._resolution === value) { - return; - } - this._resolution = value; - this.dirty = true; - }, - enumerable: false, - configurable: true - }); - /** - * New behavior for `lineHeight` that's meant to mimic HTML text. A value of `true` will - * make sure the first baseline is offset by the `lineHeight` value if it is greater than `fontSize`. - * A value of `false` will use the legacy behavior and not change the baseline of the first line. - * In the next major release, we'll enable this by default. - */ - Text.nextLineHeightBehavior = false; - /** - * New rendering behavior for letter-spacing which uses Chrome's new native API. This will - * lead to more accurate letter-spacing results because it does not try to manually draw - * each character. However, this Chrome API is experimental and may not serve all cases yet. - */ - Text.experimentalLetterSpacing = false; - return Text; - }(Sprite)); - - /*! - * @pixi/prepare - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/prepare is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Default number of uploads per frame using prepare plugin. - * @static - * @memberof PIXI.settings - * @name UPLOADS_PER_FRAME - * @type {number} - * @default 4 - */ - settings.UPLOADS_PER_FRAME = 4; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$b = function(d, b) { - extendStatics$b = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$b(d, b); - }; - - function __extends$b(d, b) { - extendStatics$b(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** - * CountLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified - * number of items per frame. - * @memberof PIXI - */ - var CountLimiter = /** @class */ (function () { - /** - * @param maxItemsPerFrame - The maximum number of items that can be prepared each frame. - */ - function CountLimiter(maxItemsPerFrame) { - this.maxItemsPerFrame = maxItemsPerFrame; - this.itemsLeft = 0; - } - /** Resets any counting properties to start fresh on a new frame. */ - CountLimiter.prototype.beginFrame = function () { - this.itemsLeft = this.maxItemsPerFrame; - }; - /** - * Checks to see if another item can be uploaded. This should only be called once per item. - * @returns If the item is allowed to be uploaded. - */ - CountLimiter.prototype.allowedToUpload = function () { - return this.itemsLeft-- > 0; - }; - return CountLimiter; - }()); - - /** - * Built-in hook to find multiple textures from objects like AnimatedSprites. - * @private - * @param item - Display object to check - * @param queue - Collection of items to upload - * @returns If a PIXI.Texture object was found. - */ - function findMultipleBaseTextures(item, queue) { - var result = false; - // Objects with multiple textures - if (item && item._textures && item._textures.length) { - for (var i = 0; i < item._textures.length; i++) { - if (item._textures[i] instanceof Texture) { - var baseTexture = item._textures[i].baseTexture; - if (queue.indexOf(baseTexture) === -1) { - queue.push(baseTexture); - result = true; - } - } - } - } - return result; - } - /** - * Built-in hook to find BaseTextures from Texture. - * @private - * @param item - Display object to check - * @param queue - Collection of items to upload - * @returns If a PIXI.Texture object was found. - */ - function findBaseTexture(item, queue) { - if (item.baseTexture instanceof BaseTexture) { - var texture = item.baseTexture; - if (queue.indexOf(texture) === -1) { - queue.push(texture); - } - return true; - } - return false; - } - /** - * Built-in hook to find textures from objects. - * @private - * @param item - Display object to check - * @param queue - Collection of items to upload - * @returns If a PIXI.Texture object was found. - */ - function findTexture(item, queue) { - if (item._texture && item._texture instanceof Texture) { - var texture = item._texture.baseTexture; - if (queue.indexOf(texture) === -1) { - queue.push(texture); - } - return true; - } - return false; - } - /** - * Built-in hook to draw PIXI.Text to its texture. - * @private - * @param _helper - Not used by this upload handler - * @param item - Item to check - * @returns If item was uploaded. - */ - function drawText(_helper, item) { - if (item instanceof Text) { - // updating text will return early if it is not dirty - item.updateText(true); - return true; - } - return false; - } - /** - * Built-in hook to calculate a text style for a PIXI.Text object. - * @private - * @param _helper - Not used by this upload handler - * @param item - Item to check - * @returns If item was uploaded. - */ - function calculateTextStyle(_helper, item) { - if (item instanceof TextStyle) { - var font = item.toFontString(); - TextMetrics.measureFont(font); - return true; - } - return false; - } - /** - * Built-in hook to find Text objects. - * @private - * @param item - Display object to check - * @param queue - Collection of items to upload - * @returns if a PIXI.Text object was found. - */ - function findText(item, queue) { - if (item instanceof Text) { - // push the text style to prepare it - this can be really expensive - if (queue.indexOf(item.style) === -1) { - queue.push(item.style); - } - // also push the text object so that we can render it (to canvas/texture) if needed - if (queue.indexOf(item) === -1) { - queue.push(item); - } - // also push the Text's texture for upload to GPU - var texture = item._texture.baseTexture; - if (queue.indexOf(texture) === -1) { - queue.push(texture); - } - return true; - } - return false; - } - /** - * Built-in hook to find TextStyle objects. - * @private - * @param item - Display object to check - * @param queue - Collection of items to upload - * @returns If a PIXI.TextStyle object was found. - */ - function findTextStyle(item, queue) { - if (item instanceof TextStyle) { - if (queue.indexOf(item) === -1) { - queue.push(item); - } - return true; - } - return false; - } - /** - * The prepare manager provides functionality to upload content to the GPU. - * - * BasePrepare handles basic queuing functionality and is extended by - * {@link PIXI.Prepare} and {@link PIXI.CanvasPrepare} - * to provide preparation capabilities specific to their respective renderers. - * @example - * // Create a sprite - * const sprite = PIXI.Sprite.from('something.png'); - * - * // Load object into GPU - * app.renderer.plugins.prepare.upload(sprite, () => { - * - * //Texture(s) has been uploaded to GPU - * app.stage.addChild(sprite); - * - * }) - * @abstract - * @memberof PIXI - */ - var BasePrepare = /** @class */ (function () { - /** - * @param {PIXI.AbstractRenderer} renderer - A reference to the current renderer - */ - function BasePrepare(renderer) { - var _this = this; - this.limiter = new CountLimiter(settings.UPLOADS_PER_FRAME); - this.renderer = renderer; - this.uploadHookHelper = null; - this.queue = []; - this.addHooks = []; - this.uploadHooks = []; - this.completes = []; - this.ticking = false; - this.delayedTick = function () { - // unlikely, but in case we were destroyed between tick() and delayedTick() - if (!_this.queue) { - return; - } - _this.prepareItems(); - }; - // hooks to find the correct texture - this.registerFindHook(findText); - this.registerFindHook(findTextStyle); - this.registerFindHook(findMultipleBaseTextures); - this.registerFindHook(findBaseTexture); - this.registerFindHook(findTexture); - // upload hooks - this.registerUploadHook(drawText); - this.registerUploadHook(calculateTextStyle); - } - /** @ignore */ - BasePrepare.prototype.upload = function (item, done) { - var _this = this; - if (typeof item === 'function') { - done = item; - item = null; - } - if (done) { - deprecation('6.5.0', 'BasePrepare.upload callback is deprecated, use the return Promise instead.'); - } - return new Promise(function (resolve) { - // If a display object, search for items - // that we could upload - if (item) { - _this.add(item); - } - // TODO: remove done callback and just use resolve - var complete = function () { - done === null || done === void 0 ? void 0 : done(); - resolve(); - }; - // Get the items for upload from the display - if (_this.queue.length) { - _this.completes.push(complete); - if (!_this.ticking) { - _this.ticking = true; - Ticker.system.addOnce(_this.tick, _this, exports.UPDATE_PRIORITY.UTILITY); - } - } - else { - complete(); - } - }); - }; - /** - * Handle tick update - * @private - */ - BasePrepare.prototype.tick = function () { - setTimeout(this.delayedTick, 0); - }; - /** - * Actually prepare items. This is handled outside of the tick because it will take a while - * and we do NOT want to block the current animation frame from rendering. - * @private - */ - BasePrepare.prototype.prepareItems = function () { - this.limiter.beginFrame(); - // Upload the graphics - while (this.queue.length && this.limiter.allowedToUpload()) { - var item = this.queue[0]; - var uploaded = false; - if (item && !item._destroyed) { - for (var i = 0, len = this.uploadHooks.length; i < len; i++) { - if (this.uploadHooks[i](this.uploadHookHelper, item)) { - this.queue.shift(); - uploaded = true; - break; - } - } - } - if (!uploaded) { - this.queue.shift(); - } - } - // We're finished - if (!this.queue.length) { - this.ticking = false; - var completes = this.completes.slice(0); - this.completes.length = 0; - for (var i = 0, len = completes.length; i < len; i++) { - completes[i](); - } - } - else { - // if we are not finished, on the next rAF do this again - Ticker.system.addOnce(this.tick, this, exports.UPDATE_PRIORITY.UTILITY); - } - }; - /** - * Adds hooks for finding items. - * @param {Function} addHook - Function call that takes two parameters: `item:*, queue:Array` - * function must return `true` if it was able to add item to the queue. - * @returns Instance of plugin for chaining. - */ - BasePrepare.prototype.registerFindHook = function (addHook) { - if (addHook) { - this.addHooks.push(addHook); - } - return this; - }; - /** - * Adds hooks for uploading items. - * @param {Function} uploadHook - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and - * function must return `true` if it was able to handle upload of item. - * @returns Instance of plugin for chaining. - */ - BasePrepare.prototype.registerUploadHook = function (uploadHook) { - if (uploadHook) { - this.uploadHooks.push(uploadHook); - } - return this; - }; - /** - * Manually add an item to the uploading queue. - * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to - * add to the queue - * @returns Instance of plugin for chaining. - */ - BasePrepare.prototype.add = function (item) { - // Add additional hooks for finding elements on special - // types of objects that - for (var i = 0, len = this.addHooks.length; i < len; i++) { - if (this.addHooks[i](item, this.queue)) { - break; - } - } - // Get children recursively - if (item instanceof Container) { - for (var i = item.children.length - 1; i >= 0; i--) { - this.add(item.children[i]); - } - } - return this; - }; - /** Destroys the plugin, don't use after this. */ - BasePrepare.prototype.destroy = function () { - if (this.ticking) { - Ticker.system.remove(this.tick, this); - } - this.ticking = false; - this.addHooks = null; - this.uploadHooks = null; - this.renderer = null; - this.completes = null; - this.queue = null; - this.limiter = null; - this.uploadHookHelper = null; - }; - return BasePrepare; - }()); - - /** - * Built-in hook to upload PIXI.Texture objects to the GPU. - * @private - * @param renderer - instance of the webgl renderer - * @param item - Item to check - * @returns If item was uploaded. - */ - function uploadBaseTextures(renderer, item) { - if (item instanceof BaseTexture) { - // if the texture already has a GL texture, then the texture has been prepared or rendered - // before now. If the texture changed, then the changer should be calling texture.update() which - // reuploads the texture without need for preparing it again - if (!item._glTextures[renderer.CONTEXT_UID]) { - renderer.texture.bind(item); - } - return true; - } - return false; - } - /** - * Built-in hook to upload PIXI.Graphics to the GPU. - * @private - * @param renderer - instance of the webgl renderer - * @param item - Item to check - * @returns If item was uploaded. - */ - function uploadGraphics(renderer, item) { - if (!(item instanceof Graphics)) { - return false; - } - var geometry = item.geometry; - // update dirty graphics to get batches - item.finishPoly(); - geometry.updateBatches(); - var batches = geometry.batches; - // upload all textures found in styles - for (var i = 0; i < batches.length; i++) { - var texture = batches[i].style.texture; - if (texture) { - uploadBaseTextures(renderer, texture.baseTexture); - } - } - // if its not batchable - update vao for particular shader - if (!geometry.batchable) { - renderer.geometry.bind(geometry, item._resolveDirectShader(renderer)); - } - return true; - } - /** - * Built-in hook to find graphics. - * @private - * @param item - Display object to check - * @param queue - Collection of items to upload - * @returns if a PIXI.Graphics object was found. - */ - function findGraphics(item, queue) { - if (item instanceof Graphics) { - queue.push(item); - return true; - } - return false; - } - /** - * The prepare plugin provides renderer-specific plugins for pre-rendering DisplayObjects. These plugins are useful for - * asynchronously preparing and uploading to the GPU assets, textures, graphics waiting to be displayed. - * - * Do not instantiate this plugin directly. It is available from the `renderer.plugins` property. - * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. - * @example - * // Create a new application - * const app = new PIXI.Application(); - * document.body.appendChild(app.view); - * - * // Don't start rendering right away - * app.stop(); - * - * // create a display object - * const rect = new PIXI.Graphics() - * .beginFill(0x00ff00) - * .drawRect(40, 40, 200, 200); - * - * // Add to the stage - * app.stage.addChild(rect); - * - * // Don't start rendering until the graphic is uploaded to the GPU - * app.renderer.plugins.prepare.upload(app.stage, () => { - * app.start(); - * }); - * @memberof PIXI - */ - var Prepare = /** @class */ (function (_super) { - __extends$b(Prepare, _super); - /** - * @param {PIXI.Renderer} renderer - A reference to the current renderer - */ - function Prepare(renderer) { - var _this = _super.call(this, renderer) || this; - _this.uploadHookHelper = _this.renderer; - // Add textures and graphics to upload - _this.registerFindHook(findGraphics); - _this.registerUploadHook(uploadBaseTextures); - _this.registerUploadHook(uploadGraphics); - return _this; - } - /** @ignore */ - Prepare.extension = { - name: 'prepare', - type: exports.ExtensionType.RendererPlugin, - }; - return Prepare; - }(BasePrepare)); - - /** - * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified - * number of milliseconds per frame. - * @memberof PIXI - */ - var TimeLimiter = /** @class */ (function () { - /** @param maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. */ - function TimeLimiter(maxMilliseconds) { - this.maxMilliseconds = maxMilliseconds; - this.frameStart = 0; - } - /** Resets any counting properties to start fresh on a new frame. */ - TimeLimiter.prototype.beginFrame = function () { - this.frameStart = Date.now(); - }; - /** - * Checks to see if another item can be uploaded. This should only be called once per item. - * @returns - If the item is allowed to be uploaded. - */ - TimeLimiter.prototype.allowedToUpload = function () { - return Date.now() - this.frameStart < this.maxMilliseconds; - }; - return TimeLimiter; - }()); - - /*! - * @pixi/spritesheet - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/spritesheet is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Utility class for maintaining reference to a collection - * of Textures on a single Spritesheet. - * - * To access a sprite sheet from your code you may pass its JSON data file to Pixi's loader: - * - * ```js - * PIXI.Loader.shared.add("images/spritesheet.json").load(setup); - * - * function setup() { - * let sheet = PIXI.Loader.shared.resources["images/spritesheet.json"].spritesheet; - * ... - * } - * ``` - * - * Alternately, you may circumvent the loader by instantiating the Spritesheet directly: - * ```js - * const sheet = new PIXI.Spritesheet(texture, spritesheetData); - * await sheet.parse(); - * console.log('Spritesheet ready to use!'); - * ``` - * - * With the `sheet.textures` you can create Sprite objects,`sheet.animations` can be used to create an AnimatedSprite. - * - * Sprite sheets can be packed using tools like {@link https://codeandweb.com/texturepacker|TexturePacker}, - * {@link https://renderhjs.net/shoebox/|Shoebox} or {@link https://github.com/krzysztof-o/spritesheet.js|Spritesheet.js}. - * Default anchor points (see {@link PIXI.Texture#defaultAnchor}) and grouping of animation sprites are currently only - * supported by TexturePacker. - * @memberof PIXI - */ - var Spritesheet = /** @class */ (function () { - /** - * @param texture - Reference to the source BaseTexture object. - * @param {object} data - Spritesheet image data. - * @param resolutionFilename - The filename to consider when determining - * the resolution of the spritesheet. If not provided, the imageUrl will - * be used on the BaseTexture. - */ - function Spritesheet(texture, data, resolutionFilename) { - if (resolutionFilename === void 0) { resolutionFilename = null; } - /** For multi-packed spritesheets, this contains a reference to all the other spritesheets it depends on. */ - this.linkedSheets = []; - this._texture = texture instanceof Texture ? texture : null; - this.baseTexture = texture instanceof BaseTexture ? texture : this._texture.baseTexture; - this.textures = {}; - this.animations = {}; - this.data = data; - var resource = this.baseTexture.resource; - this.resolution = this._updateResolution(resolutionFilename || (resource ? resource.url : null)); - this._frames = this.data.frames; - this._frameKeys = Object.keys(this._frames); - this._batchIndex = 0; - this._callback = null; - } - /** - * Generate the resolution from the filename or fallback - * to the meta.scale field of the JSON data. - * @param resolutionFilename - The filename to use for resolving - * the default resolution. - * @returns Resolution to use for spritesheet. - */ - Spritesheet.prototype._updateResolution = function (resolutionFilename) { - if (resolutionFilename === void 0) { resolutionFilename = null; } - var scale = this.data.meta.scale; - // Use a defaultValue of `null` to check if a url-based resolution is set - var resolution = getResolutionOfUrl(resolutionFilename, null); - // No resolution found via URL - if (resolution === null) { - // Use the scale value or default to 1 - resolution = scale !== undefined ? parseFloat(scale) : 1; - } - // For non-1 resolutions, update baseTexture - if (resolution !== 1) { - this.baseTexture.setResolution(resolution); - } - return resolution; - }; - /** @ignore */ - Spritesheet.prototype.parse = function (callback) { - var _this = this; - if (callback) { - deprecation('6.5.0', 'Spritesheet.parse callback is deprecated, use the return Promise instead.'); - } - return new Promise(function (resolve) { - _this._callback = function (textures) { - callback === null || callback === void 0 ? void 0 : callback(textures); - resolve(textures); - }; - _this._batchIndex = 0; - if (_this._frameKeys.length <= Spritesheet.BATCH_SIZE) { - _this._processFrames(0); - _this._processAnimations(); - _this._parseComplete(); - } - else { - _this._nextBatch(); - } - }); - }; - /** - * Process a batch of frames - * @param initialFrameIndex - The index of frame to start. - */ - Spritesheet.prototype._processFrames = function (initialFrameIndex) { - var frameIndex = initialFrameIndex; - var maxFrames = Spritesheet.BATCH_SIZE; - while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { - var i = this._frameKeys[frameIndex]; - var data = this._frames[i]; - var rect = data.frame; - if (rect) { - var frame = null; - var trim = null; - var sourceSize = data.trimmed !== false && data.sourceSize - ? data.sourceSize : data.frame; - var orig = new Rectangle(0, 0, Math.floor(sourceSize.w) / this.resolution, Math.floor(sourceSize.h) / this.resolution); - if (data.rotated) { - frame = new Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.h) / this.resolution, Math.floor(rect.w) / this.resolution); - } - else { - frame = new Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution); - } - // Check to see if the sprite is trimmed - if (data.trimmed !== false && data.spriteSourceSize) { - trim = new Rectangle(Math.floor(data.spriteSourceSize.x) / this.resolution, Math.floor(data.spriteSourceSize.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution); - } - this.textures[i] = new Texture(this.baseTexture, frame, orig, trim, data.rotated ? 2 : 0, data.anchor); - // lets also add the frame to pixi's global cache for 'from' and 'fromLoader' functions - Texture.addToCache(this.textures[i], i); - } - frameIndex++; - } - }; - /** Parse animations config. */ - Spritesheet.prototype._processAnimations = function () { - var animations = this.data.animations || {}; - for (var animName in animations) { - this.animations[animName] = []; - for (var i = 0; i < animations[animName].length; i++) { - var frameName = animations[animName][i]; - this.animations[animName].push(this.textures[frameName]); - } - } - }; - /** The parse has completed. */ - Spritesheet.prototype._parseComplete = function () { - var callback = this._callback; - this._callback = null; - this._batchIndex = 0; - callback.call(this, this.textures); - }; - /** Begin the next batch of textures. */ - Spritesheet.prototype._nextBatch = function () { - var _this = this; - this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); - this._batchIndex++; - setTimeout(function () { - if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) { - _this._nextBatch(); - } - else { - _this._processAnimations(); - _this._parseComplete(); - } - }, 0); - }; - /** - * Destroy Spritesheet and don't use after this. - * @param {boolean} [destroyBase=false] - Whether to destroy the base texture as well - */ - Spritesheet.prototype.destroy = function (destroyBase) { - var _a; - if (destroyBase === void 0) { destroyBase = false; } - for (var i in this.textures) { - this.textures[i].destroy(); - } - this._frames = null; - this._frameKeys = null; - this.data = null; - this.textures = null; - if (destroyBase) { - (_a = this._texture) === null || _a === void 0 ? void 0 : _a.destroy(); - this.baseTexture.destroy(); - } - this._texture = null; - this.baseTexture = null; - this.linkedSheets = []; - }; - /** The maximum number of Textures to build per process. */ - Spritesheet.BATCH_SIZE = 1000; - return Spritesheet; - }()); - /** - * Reference to Spritesheet object created. - * @member {PIXI.Spritesheet} spritesheet - * @memberof PIXI.LoaderResource - * @instance - */ - /** - * Dictionary of textures from Spritesheet. - * @member {Object} textures - * @memberof PIXI.LoaderResource - * @instance - */ - - /** - * {@link PIXI.Loader} middleware for loading texture atlases that have been created with - * TexturePacker or similar JSON-based spritesheet. - * - * This middleware automatically generates Texture resources. - * - * If you're using Webpack or other bundlers and plan on bundling the atlas' JSON, - * use the {@link PIXI.Spritesheet} class to directly parse the JSON. - * - * The Loader's image Resource name is automatically appended with `"_image"`. - * If a Resource with this name is already loaded, the Loader will skip parsing the - * Spritesheet. The code below will generate an internal Loader Resource called `"myatlas_image"`. - * @example - * loader.add('myatlas', 'path/to/myatlas.json'); - * loader.load(() => { - * loader.resources.myatlas; // atlas JSON resource - * loader.resources.myatlas_image; // atlas Image resource - * }); - * @memberof PIXI - */ - var SpritesheetLoader = /** @class */ (function () { - function SpritesheetLoader() { - } - /** - * Called after a resource is loaded. - * @see PIXI.Loader.loaderMiddleware - * @param resource - * @param next - */ - SpritesheetLoader.use = function (resource, next) { - var _a, _b; - // because this is middleware, it execute in loader context. `this` = loader - var loader = this; - var imageResourceName = resource.name + "_image"; - // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists - if (!resource.data - || resource.type !== exports.LoaderResource.TYPE.JSON - || !resource.data.frames - || loader.resources[imageResourceName]) { - next(); - return; - } - // Check and add the multi atlas - // Heavily influenced and based on https://github.com/rocket-ua/pixi-tps-loader/blob/master/src/ResourceLoader.js - // eslint-disable-next-line camelcase - var multiPacks = (_b = (_a = resource.data) === null || _a === void 0 ? void 0 : _a.meta) === null || _b === void 0 ? void 0 : _b.related_multi_packs; - if (Array.isArray(multiPacks)) { - var _loop_1 = function (item) { - if (typeof item !== 'string') { - return "continue"; - } - var itemName = item.replace('.json', ''); - var itemUrl = url.resolve(resource.url.replace(loader.baseUrl, ''), item); - // Check if the file wasn't already added as multipacks are redundant - if (loader.resources[itemName] - || Object.values(loader.resources).some(function (r) { return url.format(url.parse(r.url)) === itemUrl; })) { - return "continue"; - } - var options = { - crossOrigin: resource.crossOrigin, - loadType: exports.LoaderResource.LOAD_TYPE.XHR, - xhrType: exports.LoaderResource.XHR_RESPONSE_TYPE.JSON, - parentResource: resource, - metadata: resource.metadata - }; - loader.add(itemName, itemUrl, options); - }; - for (var _i = 0, multiPacks_1 = multiPacks; _i < multiPacks_1.length; _i++) { - var item = multiPacks_1[_i]; - _loop_1(item); - } - } - var loadOptions = { - crossOrigin: resource.crossOrigin, - metadata: resource.metadata.imageMetadata, - parentResource: resource, - }; - var resourcePath = SpritesheetLoader.getResourcePath(resource, loader.baseUrl); - // load the image for this sheet - loader.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { - if (res.error) { - next(res.error); - return; - } - var spritesheet = new Spritesheet(res.texture, resource.data, resource.url); - spritesheet.parse().then(function () { - resource.spritesheet = spritesheet; - resource.textures = spritesheet.textures; - next(); - }); - }); - }; - /** - * Get the spritesheets root path - * @param resource - Resource to check path - * @param baseUrl - Base root url - */ - SpritesheetLoader.getResourcePath = function (resource, baseUrl) { - // Prepend url path unless the resource image is a data url - if (resource.isDataUrl) { - return resource.data.meta.image; - } - return url.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image); - }; - /** @ignore */ - SpritesheetLoader.extension = exports.ExtensionType.Loader; - return SpritesheetLoader; - }()); - - /*! - * @pixi/sprite-tiling - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/sprite-tiling is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$a = function(d, b) { - extendStatics$a = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$a(d, b); - }; - - function __extends$a(d, b) { - extendStatics$a(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var tempPoint$1 = new Point(); - /** - * A tiling sprite is a fast way of rendering a tiling image. - * @memberof PIXI - */ - var TilingSprite = /** @class */ (function (_super) { - __extends$a(TilingSprite, _super); - /** - * @param texture - The texture of the tiling sprite. - * @param width - The width of the tiling sprite. - * @param height - The height of the tiling sprite. - */ - function TilingSprite(texture, width, height) { - if (width === void 0) { width = 100; } - if (height === void 0) { height = 100; } - var _this = _super.call(this, texture) || this; - _this.tileTransform = new Transform(); - // The width of the tiling sprite - _this._width = width; - // The height of the tiling sprite - _this._height = height; - _this.uvMatrix = _this.texture.uvMatrix || new TextureMatrix(texture); - /** - * Plugin that is responsible for rendering this element. - * Allows to customize the rendering process without overriding '_render' method. - * @default 'tilingSprite' - */ - _this.pluginName = 'tilingSprite'; - _this.uvRespectAnchor = false; - return _this; - } - Object.defineProperty(TilingSprite.prototype, "clampMargin", { - /** - * Changes frame clamping in corresponding textureTransform, shortcut - * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas - * @default 0.5 - * @member {number} - */ - get: function () { - return this.uvMatrix.clampMargin; - }, - set: function (value) { - this.uvMatrix.clampMargin = value; - this.uvMatrix.update(true); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TilingSprite.prototype, "tileScale", { - /** The scaling of the image that is being tiled. */ - get: function () { - return this.tileTransform.scale; - }, - set: function (value) { - this.tileTransform.scale.copyFrom(value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TilingSprite.prototype, "tilePosition", { - /** The offset of the image that is being tiled. */ - get: function () { - return this.tileTransform.position; - }, - set: function (value) { - this.tileTransform.position.copyFrom(value); - }, - enumerable: false, - configurable: true - }); - /** - * @protected - */ - TilingSprite.prototype._onTextureUpdate = function () { - if (this.uvMatrix) { - this.uvMatrix.texture = this._texture; - } - this._cachedTint = 0xFFFFFF; - }; - /** - * Renders the object using the WebGL renderer - * @param renderer - The renderer - */ - TilingSprite.prototype._render = function (renderer) { - // tweak our texture temporarily.. - var texture = this._texture; - if (!texture || !texture.valid) { - return; - } - this.tileTransform.updateLocalTransform(); - this.uvMatrix.update(); - renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); - renderer.plugins[this.pluginName].render(this); - }; - /** Updates the bounds of the tiling sprite. */ - TilingSprite.prototype._calculateBounds = function () { - var minX = this._width * -this._anchor._x; - var minY = this._height * -this._anchor._y; - var maxX = this._width * (1 - this._anchor._x); - var maxY = this._height * (1 - this._anchor._y); - this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); - }; - /** - * Gets the local bounds of the sprite object. - * @param rect - Optional output rectangle. - * @returns The bounds. - */ - TilingSprite.prototype.getLocalBounds = function (rect) { - // we can do a fast local bounds if the sprite has no children! - if (this.children.length === 0) { - this._bounds.minX = this._width * -this._anchor._x; - this._bounds.minY = this._height * -this._anchor._y; - this._bounds.maxX = this._width * (1 - this._anchor._x); - this._bounds.maxY = this._height * (1 - this._anchor._y); - if (!rect) { - if (!this._localBoundsRect) { - this._localBoundsRect = new Rectangle(); - } - rect = this._localBoundsRect; - } - return this._bounds.getRectangle(rect); - } - return _super.prototype.getLocalBounds.call(this, rect); - }; - /** - * Checks if a point is inside this tiling sprite. - * @param point - The point to check. - * @returns Whether or not the sprite contains the point. - */ - TilingSprite.prototype.containsPoint = function (point) { - this.worldTransform.applyInverse(point, tempPoint$1); - var width = this._width; - var height = this._height; - var x1 = -width * this.anchor._x; - if (tempPoint$1.x >= x1 && tempPoint$1.x < x1 + width) { - var y1 = -height * this.anchor._y; - if (tempPoint$1.y >= y1 && tempPoint$1.y < y1 + height) { - return true; - } - } - return false; - }; - /** - * Destroys this sprite and optionally its texture and children - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy - * method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well - * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well - */ - TilingSprite.prototype.destroy = function (options) { - _super.prototype.destroy.call(this, options); - this.tileTransform = null; - this.uvMatrix = null; - }; - /** - * Helper function that creates a new tiling sprite based on the source you provide. - * The source can be - frame id, image url, video url, canvas element, video element, base texture - * @static - * @param {string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from - * @param {object} options - See {@link PIXI.BaseTexture}'s constructor for options. - * @param {number} options.width - required width of the tiling sprite - * @param {number} options.height - required height of the tiling sprite - * @returns {PIXI.TilingSprite} The newly created texture - */ - TilingSprite.from = function (source, options) { - var texture = (source instanceof Texture) - ? source - : Texture.from(source, options); - return new TilingSprite(texture, options.width, options.height); - }; - Object.defineProperty(TilingSprite.prototype, "width", { - /** The width of the sprite, setting this will actually modify the scale to achieve the value set. */ - get: function () { - return this._width; - }, - set: function (value) { - this._width = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TilingSprite.prototype, "height", { - /** The height of the TilingSprite, setting this will actually modify the scale to achieve the value set. */ - get: function () { - return this._height; - }, - set: function (value) { - this._height = value; - }, - enumerable: false, - configurable: true - }); - return TilingSprite; - }(Sprite)); - - var fragmentSimpleSrc = "#version 100\n#define SHADER_NAME Tiling-Sprite-Simple-100\n\nprecision lowp float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 texSample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = texSample * uColor;\n}\n"; - - var gl1VertexSrc = "#version 100\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n"; - - var gl1FragmentSrc = "#version 100\n#ifdef GL_EXT_shader_texture_lod\n #extension GL_EXT_shader_texture_lod : enable\n#endif\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = vTextureCoord + ceil(uClampOffset - vTextureCoord);\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n vec2 unclamped = coord;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n #ifdef GL_EXT_shader_texture_lod\n vec4 texSample = unclamped == coord\n ? texture2D(uSampler, coord) \n : texture2DLodEXT(uSampler, coord, 0);\n #else\n vec4 texSample = texture2D(uSampler, coord);\n #endif\n\n gl_FragColor = texSample * uColor;\n}\n"; - - var gl2VertexSrc = "#version 300 es\n#define SHADER_NAME Tiling-Sprite-300\n\nprecision lowp float;\n\nin vec2 aVertexPosition;\nin vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nout vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n"; - - var gl2FragmentSrc = "#version 300 es\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nin vec2 vTextureCoord;\n\nout vec4 fragmentColor;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = vTextureCoord + ceil(uClampOffset - vTextureCoord);\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n vec2 unclamped = coord;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 texSample = texture(uSampler, coord, unclamped == coord ? 0.0f : -32.0f);// lod-bias very negative to force lod 0\n\n fragmentColor = texSample * uColor;\n}\n"; - - var tempMat = new Matrix(); - /** - * WebGL renderer plugin for tiling sprites - * @class - * @memberof PIXI - * @extends PIXI.ObjectRenderer - */ - var TilingSpriteRenderer = /** @class */ (function (_super) { - __extends$a(TilingSpriteRenderer, _super); - /** - * constructor for renderer - * @param {PIXI.Renderer} renderer - The renderer this tiling awesomeness works for. - */ - function TilingSpriteRenderer(renderer) { - var _this = _super.call(this, renderer) || this; - // WebGL version is not available during initialization! - renderer.runners.contextChange.add(_this); - _this.quad = new QuadUv(); - /** - * The WebGL state in which this renderer will work. - * @member {PIXI.State} - * @readonly - */ - _this.state = State.for2d(); - return _this; - } - /** Creates shaders when context is initialized. */ - TilingSpriteRenderer.prototype.contextChange = function () { - var renderer = this.renderer; - var uniforms = { globals: renderer.globalUniforms }; - this.simpleShader = Shader.from(gl1VertexSrc, fragmentSimpleSrc, uniforms); - this.shader = renderer.context.webGLVersion > 1 - ? Shader.from(gl2VertexSrc, gl2FragmentSrc, uniforms) - : Shader.from(gl1VertexSrc, gl1FragmentSrc, uniforms); - }; - /** - * @param {PIXI.TilingSprite} ts - tilingSprite to be rendered - */ - TilingSpriteRenderer.prototype.render = function (ts) { - var renderer = this.renderer; - var quad = this.quad; - var vertices = quad.vertices; - vertices[0] = vertices[6] = (ts._width) * -ts.anchor.x; - vertices[1] = vertices[3] = ts._height * -ts.anchor.y; - vertices[2] = vertices[4] = (ts._width) * (1.0 - ts.anchor.x); - vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); - var anchorX = ts.uvRespectAnchor ? ts.anchor.x : 0; - var anchorY = ts.uvRespectAnchor ? ts.anchor.y : 0; - vertices = quad.uvs; - vertices[0] = vertices[6] = -anchorX; - vertices[1] = vertices[3] = -anchorY; - vertices[2] = vertices[4] = 1.0 - anchorX; - vertices[5] = vertices[7] = 1.0 - anchorY; - quad.invalidate(); - var tex = ts._texture; - var baseTex = tex.baseTexture; - var premultiplied = baseTex.alphaMode > 0; - var lt = ts.tileTransform.localTransform; - var uv = ts.uvMatrix; - var isSimple = baseTex.isPowerOfTwo - && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; - // auto, force repeat wrapMode for big tiling textures - if (isSimple) { - if (!baseTex._glTextures[renderer.CONTEXT_UID]) { - if (baseTex.wrapMode === exports.WRAP_MODES.CLAMP) { - baseTex.wrapMode = exports.WRAP_MODES.REPEAT; - } - } - else { - isSimple = baseTex.wrapMode !== exports.WRAP_MODES.CLAMP; - } - } - var shader = isSimple ? this.simpleShader : this.shader; - var w = tex.width; - var h = tex.height; - var W = ts._width; - var H = ts._height; - tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); - // that part is the same as above: - // tempMat.identity(); - // tempMat.scale(tex.width, tex.height); - // tempMat.prepend(lt); - // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); - tempMat.invert(); - if (isSimple) { - tempMat.prepend(uv.mapCoord); - } - else { - shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); - shader.uniforms.uClampFrame = uv.uClampFrame; - shader.uniforms.uClampOffset = uv.uClampOffset; - } - shader.uniforms.uTransform = tempMat.toArray(true); - shader.uniforms.uColor = premultiplyTintToRgba(ts.tint, ts.worldAlpha, shader.uniforms.uColor, premultiplied); - shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); - shader.uniforms.uSampler = tex; - renderer.shader.bind(shader); - renderer.geometry.bind(quad); - this.state.blendMode = correctBlendMode(ts.blendMode, premultiplied); - renderer.state.set(this.state); - renderer.geometry.draw(this.renderer.gl.TRIANGLES, 6, 0); - }; - /** @ignore */ - TilingSpriteRenderer.extension = { - name: 'tilingSprite', - type: exports.ExtensionType.RendererPlugin, - }; - return TilingSpriteRenderer; - }(ObjectRenderer)); - - /*! - * @pixi/mesh - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/mesh is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$9 = function(d, b) { - extendStatics$9 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$9(d, b); - }; - - function __extends$9(d, b) { - extendStatics$9(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** - * Class controls cache for UV mapping from Texture normal space to BaseTexture normal space. - * @memberof PIXI - */ - var MeshBatchUvs = /** @class */ (function () { - /** - * @param uvBuffer - Buffer with normalized uv's - * @param uvMatrix - Material UV matrix - */ - function MeshBatchUvs(uvBuffer, uvMatrix) { - this.uvBuffer = uvBuffer; - this.uvMatrix = uvMatrix; - this.data = null; - this._bufferUpdateId = -1; - this._textureUpdateId = -1; - this._updateID = 0; - } - /** - * Updates - * @param forceUpdate - force the update - */ - MeshBatchUvs.prototype.update = function (forceUpdate) { - if (!forceUpdate - && this._bufferUpdateId === this.uvBuffer._updateID - && this._textureUpdateId === this.uvMatrix._updateID) { - return; - } - this._bufferUpdateId = this.uvBuffer._updateID; - this._textureUpdateId = this.uvMatrix._updateID; - var data = this.uvBuffer.data; - if (!this.data || this.data.length !== data.length) { - this.data = new Float32Array(data.length); - } - this.uvMatrix.multiplyUvs(data, this.data); - this._updateID++; - }; - return MeshBatchUvs; - }()); - - var tempPoint = new Point(); - var tempPolygon = new Polygon(); - /** - * Base mesh class. - * - * This class empowers you to have maximum flexibility to render any kind of WebGL visuals you can think of. - * This class assumes a certain level of WebGL knowledge. - * If you know a bit this should abstract enough away to make your life easier! - * - * Pretty much ALL WebGL can be broken down into the following: - * - Geometry - The structure and data for the mesh. This can include anything from positions, uvs, normals, colors etc.. - * - Shader - This is the shader that PixiJS will render the geometry with (attributes in the shader must match the geometry) - * - State - This is the state of WebGL required to render the mesh. - * - * Through a combination of the above elements you can render anything you want, 2D or 3D! - * @memberof PIXI - */ - var Mesh = /** @class */ (function (_super) { - __extends$9(Mesh, _super); - /** - * @param geometry - The geometry the mesh will use. - * @param {PIXI.MeshMaterial} shader - The shader the mesh will use. - * @param state - The state that the WebGL context is required to be in to render the mesh - * if no state is provided, uses {@link PIXI.State.for2d} to create a 2D state for PixiJS. - * @param drawMode - The drawMode, can be any of the {@link PIXI.DRAW_MODES} constants. - */ - function Mesh(geometry, shader, state, drawMode) { - if (drawMode === void 0) { drawMode = exports.DRAW_MODES.TRIANGLES; } - var _this = _super.call(this) || this; - _this.geometry = geometry; - _this.shader = shader; - _this.state = state || State.for2d(); - _this.drawMode = drawMode; - _this.start = 0; - _this.size = 0; - _this.uvs = null; - _this.indices = null; - _this.vertexData = new Float32Array(1); - _this.vertexDirty = -1; - _this._transformID = -1; - _this._roundPixels = settings.ROUND_PIXELS; - _this.batchUvs = null; - return _this; - } - Object.defineProperty(Mesh.prototype, "geometry", { - /** - * Includes vertex positions, face indices, normals, colors, UVs, and - * custom attributes within buffers, reducing the cost of passing all - * this data to the GPU. Can be shared between multiple Mesh objects. - */ - get: function () { - return this._geometry; - }, - set: function (value) { - if (this._geometry === value) { - return; - } - if (this._geometry) { - this._geometry.refCount--; - if (this._geometry.refCount === 0) { - this._geometry.dispose(); - } - } - this._geometry = value; - if (this._geometry) { - this._geometry.refCount++; - } - this.vertexDirty = -1; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Mesh.prototype, "uvBuffer", { - /** - * To change mesh uv's, change its uvBuffer data and increment its _updateID. - * @readonly - */ - get: function () { - return this.geometry.buffers[1]; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Mesh.prototype, "verticesBuffer", { - /** - * To change mesh vertices, change its uvBuffer data and increment its _updateID. - * Incrementing _updateID is optional because most of Mesh objects do it anyway. - * @readonly - */ - get: function () { - return this.geometry.buffers[0]; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Mesh.prototype, "material", { - get: function () { - return this.shader; - }, - /** Alias for {@link PIXI.Mesh#shader}. */ - set: function (value) { - this.shader = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Mesh.prototype, "blendMode", { - get: function () { - return this.state.blendMode; - }, - /** - * The blend mode to be applied to the Mesh. Apply a value of - * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. - * @default PIXI.BLEND_MODES.NORMAL; - */ - set: function (value) { - this.state.blendMode = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Mesh.prototype, "roundPixels", { - get: function () { - return this._roundPixels; - }, - /** - * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. - * Advantages can include sharper image quality (like text) and faster rendering on canvas. - * The main disadvantage is movement of objects may appear less smooth. - * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} - * @default false - */ - set: function (value) { - if (this._roundPixels !== value) { - this._transformID = -1; - } - this._roundPixels = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Mesh.prototype, "tint", { - /** - * The multiply tint applied to the Mesh. This is a hex value. A value of - * `0xFFFFFF` will remove any tint effect. - * - * Null for non-MeshMaterial shaders - * @default 0xFFFFFF - */ - get: function () { - return 'tint' in this.shader ? this.shader.tint : null; - }, - set: function (value) { - this.shader.tint = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Mesh.prototype, "texture", { - /** The texture that the Mesh uses. Null for non-MeshMaterial shaders */ - get: function () { - return 'texture' in this.shader ? this.shader.texture : null; - }, - set: function (value) { - this.shader.texture = value; - }, - enumerable: false, - configurable: true - }); - /** - * Standard renderer draw. - * @param renderer - Instance to renderer. - */ - Mesh.prototype._render = function (renderer) { - // set properties for batching.. - // TODO could use a different way to grab verts? - var vertices = this.geometry.buffers[0].data; - var shader = this.shader; - // TODO benchmark check for attribute size.. - if (shader.batchable - && this.drawMode === exports.DRAW_MODES.TRIANGLES - && vertices.length < Mesh.BATCHABLE_SIZE * 2) { - this._renderToBatch(renderer); - } - else { - this._renderDefault(renderer); - } - }; - /** - * Standard non-batching way of rendering. - * @param renderer - Instance to renderer. - */ - Mesh.prototype._renderDefault = function (renderer) { - var shader = this.shader; - shader.alpha = this.worldAlpha; - if (shader.update) { - shader.update(); - } - renderer.batch.flush(); - // bind and sync uniforms.. - shader.uniforms.translationMatrix = this.transform.worldTransform.toArray(true); - renderer.shader.bind(shader); - // set state.. - renderer.state.set(this.state); - // bind the geometry... - renderer.geometry.bind(this.geometry, shader); - // then render it - renderer.geometry.draw(this.drawMode, this.size, this.start, this.geometry.instanceCount); - }; - /** - * Rendering by using the Batch system. - * @param renderer - Instance to renderer. - */ - Mesh.prototype._renderToBatch = function (renderer) { - var geometry = this.geometry; - var shader = this.shader; - if (shader.uvMatrix) { - shader.uvMatrix.update(); - this.calculateUvs(); - } - // set properties for batching.. - this.calculateVertices(); - this.indices = geometry.indexBuffer.data; - this._tintRGB = shader._tintRGB; - this._texture = shader.texture; - var pluginName = this.material.pluginName; - renderer.batch.setObjectRenderer(renderer.plugins[pluginName]); - renderer.plugins[pluginName].render(this); - }; - /** Updates vertexData field based on transform and vertices. */ - Mesh.prototype.calculateVertices = function () { - var geometry = this.geometry; - var verticesBuffer = geometry.buffers[0]; - var vertices = verticesBuffer.data; - var vertexDirtyId = verticesBuffer._updateID; - if (vertexDirtyId === this.vertexDirty && this._transformID === this.transform._worldID) { - return; - } - this._transformID = this.transform._worldID; - if (this.vertexData.length !== vertices.length) { - this.vertexData = new Float32Array(vertices.length); - } - var wt = this.transform.worldTransform; - var a = wt.a; - var b = wt.b; - var c = wt.c; - var d = wt.d; - var tx = wt.tx; - var ty = wt.ty; - var vertexData = this.vertexData; - for (var i = 0; i < vertexData.length / 2; i++) { - var x = vertices[(i * 2)]; - var y = vertices[(i * 2) + 1]; - vertexData[(i * 2)] = (a * x) + (c * y) + tx; - vertexData[(i * 2) + 1] = (b * x) + (d * y) + ty; - } - if (this._roundPixels) { - var resolution = settings.RESOLUTION; - for (var i = 0; i < vertexData.length; ++i) { - vertexData[i] = Math.round((vertexData[i] * resolution | 0) / resolution); - } - } - this.vertexDirty = vertexDirtyId; - }; - /** Updates uv field based on from geometry uv's or batchUvs. */ - Mesh.prototype.calculateUvs = function () { - var geomUvs = this.geometry.buffers[1]; - var shader = this.shader; - if (!shader.uvMatrix.isSimple) { - if (!this.batchUvs) { - this.batchUvs = new MeshBatchUvs(geomUvs, shader.uvMatrix); - } - this.batchUvs.update(); - this.uvs = this.batchUvs.data; - } - else { - this.uvs = geomUvs.data; - } - }; - /** - * Updates the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. - * there must be a aVertexPosition attribute present in the geometry for bounds to be calculated correctly. - */ - Mesh.prototype._calculateBounds = function () { - this.calculateVertices(); - this._bounds.addVertexData(this.vertexData, 0, this.vertexData.length); - }; - /** - * Tests if a point is inside this mesh. Works only for PIXI.DRAW_MODES.TRIANGLES. - * @param point - The point to test. - * @returns - The result of the test. - */ - Mesh.prototype.containsPoint = function (point) { - if (!this.getBounds().contains(point.x, point.y)) { - return false; - } - this.worldTransform.applyInverse(point, tempPoint); - var vertices = this.geometry.getBuffer('aVertexPosition').data; - var points = tempPolygon.points; - var indices = this.geometry.getIndex().data; - var len = indices.length; - var step = this.drawMode === 4 ? 3 : 1; - for (var i = 0; i + 2 < len; i += step) { - var ind0 = indices[i] * 2; - var ind1 = indices[i + 1] * 2; - var ind2 = indices[i + 2] * 2; - points[0] = vertices[ind0]; - points[1] = vertices[ind0 + 1]; - points[2] = vertices[ind1]; - points[3] = vertices[ind1 + 1]; - points[4] = vertices[ind2]; - points[5] = vertices[ind2 + 1]; - if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { - return true; - } - } - return false; - }; - Mesh.prototype.destroy = function (options) { - _super.prototype.destroy.call(this, options); - if (this._cachedTexture) { - this._cachedTexture.destroy(); - this._cachedTexture = null; - } - this.geometry = null; - this.shader = null; - this.state = null; - this.uvs = null; - this.indices = null; - this.vertexData = null; - }; - /** The maximum number of vertices to consider batchable. Generally, the complexity of the geometry. */ - Mesh.BATCHABLE_SIZE = 100; - return Mesh; - }(Container)); - - var fragment$5 = "varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n"; - - var vertex$2 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTextureMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\n}\n"; - - /** - * Slightly opinionated default shader for PixiJS 2D objects. - * @memberof PIXI - */ - var MeshMaterial = /** @class */ (function (_super) { - __extends$9(MeshMaterial, _super); - /** - * @param uSampler - Texture that material uses to render. - * @param options - Additional options - * @param {number} [options.alpha=1] - Default alpha. - * @param {number} [options.tint=0xFFFFFF] - Default tint. - * @param {string} [options.pluginName='batch'] - Renderer plugin for batching. - * @param {PIXI.Program} [options.program=0xFFFFFF] - Custom program. - * @param {object} [options.uniforms] - Custom uniforms. - */ - function MeshMaterial(uSampler, options) { - var _this = this; - var uniforms = { - uSampler: uSampler, - alpha: 1, - uTextureMatrix: Matrix.IDENTITY, - uColor: new Float32Array([1, 1, 1, 1]), - }; - // Set defaults - options = Object.assign({ - tint: 0xFFFFFF, - alpha: 1, - pluginName: 'batch', - }, options); - if (options.uniforms) { - Object.assign(uniforms, options.uniforms); - } - _this = _super.call(this, options.program || Program.from(vertex$2, fragment$5), uniforms) || this; - _this._colorDirty = false; - _this.uvMatrix = new TextureMatrix(uSampler); - _this.batchable = options.program === undefined; - _this.pluginName = options.pluginName; - _this.tint = options.tint; - _this.alpha = options.alpha; - return _this; - } - Object.defineProperty(MeshMaterial.prototype, "texture", { - /** Reference to the texture being rendered. */ - get: function () { - return this.uniforms.uSampler; - }, - set: function (value) { - if (this.uniforms.uSampler !== value) { - if (!this.uniforms.uSampler.baseTexture.alphaMode !== !value.baseTexture.alphaMode) { - this._colorDirty = true; - } - this.uniforms.uSampler = value; - this.uvMatrix.texture = value; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(MeshMaterial.prototype, "alpha", { - get: function () { - return this._alpha; - }, - /** - * This gets automatically set by the object using this. - * @default 1 - */ - set: function (value) { - if (value === this._alpha) - { return; } - this._alpha = value; - this._colorDirty = true; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(MeshMaterial.prototype, "tint", { - get: function () { - return this._tint; - }, - /** - * Multiply tint for the material. - * @default 0xFFFFFF - */ - set: function (value) { - if (value === this._tint) - { return; } - this._tint = value; - this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); - this._colorDirty = true; - }, - enumerable: false, - configurable: true - }); - /** Gets called automatically by the Mesh. Intended to be overridden for custom {@link MeshMaterial} objects. */ - MeshMaterial.prototype.update = function () { - if (this._colorDirty) { - this._colorDirty = false; - var baseTexture = this.texture.baseTexture; - premultiplyTintToRgba(this._tint, this._alpha, this.uniforms.uColor, baseTexture.alphaMode); - } - if (this.uvMatrix.update()) { - this.uniforms.uTextureMatrix = this.uvMatrix.mapCoord; - } - }; - return MeshMaterial; - }(Shader)); - - /** - * Standard 2D geometry used in PixiJS. - * - * Geometry can be defined without passing in a style or data if required. - * - * ```js - * const geometry = new PIXI.Geometry(); - * - * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2); - * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1], 2); - * geometry.addIndex([0,1,2,1,3,2]); - * - * ``` - * @memberof PIXI - */ - var MeshGeometry = /** @class */ (function (_super) { - __extends$9(MeshGeometry, _super); - /** - * @param {Float32Array|number[]} [vertices] - Positional data on geometry. - * @param {Float32Array|number[]} [uvs] - Texture UVs. - * @param {Uint16Array|number[]} [index] - IndexBuffer - */ - function MeshGeometry(vertices, uvs, index) { - var _this = _super.call(this) || this; - var verticesBuffer = new Buffer(vertices); - var uvsBuffer = new Buffer(uvs, true); - var indexBuffer = new Buffer(index, true, true); - _this.addAttribute('aVertexPosition', verticesBuffer, 2, false, exports.TYPES.FLOAT) - .addAttribute('aTextureCoord', uvsBuffer, 2, false, exports.TYPES.FLOAT) - .addIndex(indexBuffer); - _this._updateId = -1; - return _this; - } - Object.defineProperty(MeshGeometry.prototype, "vertexDirtyId", { - /** - * If the vertex position is updated. - * @readonly - * @private - */ - get: function () { - return this.buffers[0]._updateID; - }, - enumerable: false, - configurable: true - }); - return MeshGeometry; - }(Geometry)); - - /*! - * @pixi/text-bitmap - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/text-bitmap is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$8 = function(d, b) { - extendStatics$8 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$8(d, b); - }; - - function __extends$8(d, b) { - extendStatics$8(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /* eslint-disable max-len */ - /** - * Normalized parsed data from .fnt files. - * @memberof PIXI - */ - var BitmapFontData = /** @class */ (function () { - function BitmapFontData() { - this.info = []; - this.common = []; - this.page = []; - this.char = []; - this.kerning = []; - this.distanceField = []; - } - return BitmapFontData; - }()); - - /** - * BitmapFont format that's Text-based. - * @private - */ - var TextFormat = /** @class */ (function () { - function TextFormat() { - } - /** - * Check if resource refers to txt font data. - * @param data - * @returns - True if resource could be treated as font data, false otherwise. - */ - TextFormat.test = function (data) { - return typeof data === 'string' && data.indexOf('info face=') === 0; - }; - /** - * Convert text font data to a javascript object. - * @param txt - Raw string data to be converted - * @returns - Parsed font data - */ - TextFormat.parse = function (txt) { - // Retrieve data item - var items = txt.match(/^[a-z]+\s+.+$/gm); - var rawData = { - info: [], - common: [], - page: [], - char: [], - chars: [], - kerning: [], - kernings: [], - distanceField: [], - }; - for (var i in items) { - // Extract item name - var name = items[i].match(/^[a-z]+/gm)[0]; - // Extract item attribute list as string ex.: "width=10" - var attributeList = items[i].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm); - // Convert attribute list into an object - var itemData = {}; - for (var i_1 in attributeList) { - // Split key-value pairs - var split = attributeList[i_1].split('='); - var key = split[0]; - // Remove eventual quotes from value - var strValue = split[1].replace(/"/gm, ''); - // Try to convert value into float - var floatValue = parseFloat(strValue); - // Use string value case float value is NaN - var value = isNaN(floatValue) ? strValue : floatValue; - itemData[key] = value; - } - // Push current item to the resulting data - rawData[name].push(itemData); - } - var font = new BitmapFontData(); - rawData.info.forEach(function (info) { return font.info.push({ - face: info.face, - size: parseInt(info.size, 10), - }); }); - rawData.common.forEach(function (common) { return font.common.push({ - lineHeight: parseInt(common.lineHeight, 10), - }); }); - rawData.page.forEach(function (page) { return font.page.push({ - id: parseInt(page.id, 10), - file: page.file, - }); }); - rawData.char.forEach(function (char) { return font.char.push({ - id: parseInt(char.id, 10), - page: parseInt(char.page, 10), - x: parseInt(char.x, 10), - y: parseInt(char.y, 10), - width: parseInt(char.width, 10), - height: parseInt(char.height, 10), - xoffset: parseInt(char.xoffset, 10), - yoffset: parseInt(char.yoffset, 10), - xadvance: parseInt(char.xadvance, 10), - }); }); - rawData.kerning.forEach(function (kerning) { return font.kerning.push({ - first: parseInt(kerning.first, 10), - second: parseInt(kerning.second, 10), - amount: parseInt(kerning.amount, 10), - }); }); - rawData.distanceField.forEach(function (df) { return font.distanceField.push({ - distanceRange: parseInt(df.distanceRange, 10), - fieldType: df.fieldType, - }); }); - return font; - }; - return TextFormat; - }()); - - /** - * BitmapFont format that's XML-based. - * @private - */ - var XMLFormat = /** @class */ (function () { - function XMLFormat() { - } - /** - * Check if resource refers to xml font data. - * @param data - * @returns - True if resource could be treated as font data, false otherwise. - */ - XMLFormat.test = function (data) { - return data instanceof XMLDocument - && data.getElementsByTagName('page').length - && data.getElementsByTagName('info')[0].getAttribute('face') !== null; - }; - /** - * Convert the XML into BitmapFontData that we can use. - * @param xml - * @returns - Data to use for BitmapFont - */ - XMLFormat.parse = function (xml) { - var data = new BitmapFontData(); - var info = xml.getElementsByTagName('info'); - var common = xml.getElementsByTagName('common'); - var page = xml.getElementsByTagName('page'); - var char = xml.getElementsByTagName('char'); - var kerning = xml.getElementsByTagName('kerning'); - var distanceField = xml.getElementsByTagName('distanceField'); - for (var i = 0; i < info.length; i++) { - data.info.push({ - face: info[i].getAttribute('face'), - size: parseInt(info[i].getAttribute('size'), 10), - }); - } - for (var i = 0; i < common.length; i++) { - data.common.push({ - lineHeight: parseInt(common[i].getAttribute('lineHeight'), 10), - }); - } - for (var i = 0; i < page.length; i++) { - data.page.push({ - id: parseInt(page[i].getAttribute('id'), 10) || 0, - file: page[i].getAttribute('file'), - }); - } - for (var i = 0; i < char.length; i++) { - var letter = char[i]; - data.char.push({ - id: parseInt(letter.getAttribute('id'), 10), - page: parseInt(letter.getAttribute('page'), 10) || 0, - x: parseInt(letter.getAttribute('x'), 10), - y: parseInt(letter.getAttribute('y'), 10), - width: parseInt(letter.getAttribute('width'), 10), - height: parseInt(letter.getAttribute('height'), 10), - xoffset: parseInt(letter.getAttribute('xoffset'), 10), - yoffset: parseInt(letter.getAttribute('yoffset'), 10), - xadvance: parseInt(letter.getAttribute('xadvance'), 10), - }); - } - for (var i = 0; i < kerning.length; i++) { - data.kerning.push({ - first: parseInt(kerning[i].getAttribute('first'), 10), - second: parseInt(kerning[i].getAttribute('second'), 10), - amount: parseInt(kerning[i].getAttribute('amount'), 10), - }); - } - for (var i = 0; i < distanceField.length; i++) { - data.distanceField.push({ - fieldType: distanceField[i].getAttribute('fieldType'), - distanceRange: parseInt(distanceField[i].getAttribute('distanceRange'), 10), - }); - } - return data; - }; - return XMLFormat; - }()); - - /** - * BitmapFont format that's XML-based. - * @private - */ - var XMLStringFormat = /** @class */ (function () { - function XMLStringFormat() { - } - /** - * Check if resource refers to text xml font data. - * @param data - * @returns - True if resource could be treated as font data, false otherwise. - */ - XMLStringFormat.test = function (data) { - if (typeof data === 'string' && data.indexOf('') > -1) { - var xml = new globalThis.DOMParser().parseFromString(data, 'text/xml'); - return XMLFormat.test(xml); - } - return false; - }; - /** - * Convert the text XML into BitmapFontData that we can use. - * @param xmlTxt - * @returns - Data to use for BitmapFont - */ - XMLStringFormat.parse = function (xmlTxt) { - var xml = new globalThis.DOMParser().parseFromString(xmlTxt, 'text/xml'); - return XMLFormat.parse(xml); - }; - return XMLStringFormat; - }()); - - // Registered formats, maybe make this extensible in the future? - var formats = [ - TextFormat, - XMLFormat, - XMLStringFormat ]; - /** - * Auto-detect BitmapFont parsing format based on data. - * @private - * @param {any} data - Data to detect format - * @returns {any} Format or null - */ - function autoDetectFormat(data) { - for (var i = 0; i < formats.length; i++) { - if (formats[i].test(data)) { - return formats[i]; - } - } - return null; - } - - // TODO: Prevent code duplication b/w generateFillStyle & Text#generateFillStyle - /** - * Generates the fill style. Can automatically generate a gradient based on the fill style being an array - * @private - * @param canvas - * @param context - * @param {object} style - The style. - * @param resolution - * @param {string[]} lines - The lines of text. - * @param metrics - * @returns {string|number|CanvasGradient} The fill style - */ - function generateFillStyle(canvas, context, style, resolution, lines, metrics) { - // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as - // the setter converts to string. See this thread for more details: - // https://github.com/microsoft/TypeScript/issues/2521 - var fillStyle = style.fill; - if (!Array.isArray(fillStyle)) { - return fillStyle; - } - else if (fillStyle.length === 1) { - return fillStyle[0]; - } - // the gradient will be evenly spaced out according to how large the array is. - // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 - var gradient; - // a dropshadow will enlarge the canvas and result in the gradient being - // generated with the incorrect dimensions - var dropShadowCorrection = (style.dropShadow) ? style.dropShadowDistance : 0; - // should also take padding into account, padding can offset the gradient - var padding = style.padding || 0; - var width = (canvas.width / resolution) - dropShadowCorrection - (padding * 2); - var height = (canvas.height / resolution) - dropShadowCorrection - (padding * 2); - // make a copy of the style settings, so we can manipulate them later - var fill = fillStyle.slice(); - var fillGradientStops = style.fillGradientStops.slice(); - // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 - if (!fillGradientStops.length) { - var lengthPlus1 = fill.length + 1; - for (var i = 1; i < lengthPlus1; ++i) { - fillGradientStops.push(i / lengthPlus1); - } - } - // stop the bleeding of the last gradient on the line above to the top gradient of the this line - // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 - fill.unshift(fillStyle[0]); - fillGradientStops.unshift(0); - fill.push(fillStyle[fillStyle.length - 1]); - fillGradientStops.push(1); - if (style.fillGradientType === exports.TEXT_GRADIENT.LINEAR_VERTICAL) { - // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas - gradient = context.createLinearGradient(width / 2, padding, width / 2, height + padding); - // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect - // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 - // There's potential for floating point precision issues at the seams between gradient repeats. - // The loop below generates the stops in order, so track the last generated one to prevent - // floating point precision from making us go the teeniest bit backwards, resulting in - // the first and last colors getting swapped. - var lastIterationStop = 0; - // Actual height of the text itself, not counting spacing for lineHeight/leading/dropShadow etc - var textHeight = metrics.fontProperties.fontSize + style.strokeThickness; - // textHeight, but as a 0-1 size in global gradient stop space - var gradStopLineHeight = textHeight / height; - for (var i = 0; i < lines.length; i++) { - var thisLineTop = metrics.lineHeight * i; - for (var j = 0; j < fill.length; j++) { - // 0-1 stop point for the current line, multiplied to global space afterwards - var lineStop = 0; - if (typeof fillGradientStops[j] === 'number') { - lineStop = fillGradientStops[j]; - } - else { - lineStop = j / fill.length; - } - var globalStop = (thisLineTop / height) + (lineStop * gradStopLineHeight); - // Prevent color stop generation going backwards from floating point imprecision - var clampedStop = Math.max(lastIterationStop, globalStop); - clampedStop = Math.min(clampedStop, 1); // Cap at 1 as well for safety's sake to avoid a possible throw. - gradient.addColorStop(clampedStop, fill[j]); - lastIterationStop = clampedStop; - } - } - } - else { - // start the gradient at the center left of the canvas, and end at the center right of the canvas - gradient = context.createLinearGradient(padding, height / 2, width + padding, height / 2); - // can just evenly space out the gradients in this case, as multiple lines makes no difference - // to an even left to right gradient - var totalIterations = fill.length + 1; - var currentIteration = 1; - for (var i = 0; i < fill.length; i++) { - var stop = void 0; - if (typeof fillGradientStops[i] === 'number') { - stop = fillGradientStops[i]; - } - else { - stop = currentIteration / totalIterations; - } - gradient.addColorStop(stop, fill[i]); - currentIteration++; - } - } - return gradient; - } - - // TODO: Prevent code duplication b/w drawGlyph & Text#updateText - /** - * Draws the glyph `metrics.text` on the given canvas. - * - * Ignored because not directly exposed. - * @ignore - * @param {HTMLCanvasElement} canvas - * @param {CanvasRenderingContext2D} context - * @param {TextMetrics} metrics - * @param {number} x - * @param {number} y - * @param {number} resolution - * @param {TextStyle} style - */ - function drawGlyph(canvas, context, metrics, x, y, resolution, style) { - var char = metrics.text; - var fontProperties = metrics.fontProperties; - context.translate(x, y); - context.scale(resolution, resolution); - var tx = style.strokeThickness / 2; - var ty = -(style.strokeThickness / 2); - context.font = style.toFontString(); - context.lineWidth = style.strokeThickness; - context.textBaseline = style.textBaseline; - context.lineJoin = style.lineJoin; - context.miterLimit = style.miterLimit; - // set canvas text styles - context.fillStyle = generateFillStyle(canvas, context, style, resolution, [char], metrics); - context.strokeStyle = style.stroke; - if (style.dropShadow) { - var dropShadowColor = style.dropShadowColor; - var rgb = hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : string2hex(dropShadowColor)); - var dropShadowBlur = style.dropShadowBlur * resolution; - var dropShadowDistance = style.dropShadowDistance * resolution; - context.shadowColor = "rgba(" + rgb[0] * 255 + "," + rgb[1] * 255 + "," + rgb[2] * 255 + "," + style.dropShadowAlpha + ")"; - context.shadowBlur = dropShadowBlur; - context.shadowOffsetX = Math.cos(style.dropShadowAngle) * dropShadowDistance; - context.shadowOffsetY = Math.sin(style.dropShadowAngle) * dropShadowDistance; - } - else { - context.shadowColor = 'black'; - context.shadowBlur = 0; - context.shadowOffsetX = 0; - context.shadowOffsetY = 0; - } - if (style.stroke && style.strokeThickness) { - context.strokeText(char, tx, ty + metrics.lineHeight - fontProperties.descent); - } - if (style.fill) { - context.fillText(char, tx, ty + metrics.lineHeight - fontProperties.descent); - } - context.setTransform(1, 0, 0, 1, 0, 0); // defaults needed for older browsers (e.g. Opera 29) - context.fillStyle = 'rgba(0, 0, 0, 0)'; - } - - /** - * Ponyfill for IE because it doesn't support `Array.from` - * @param text - * @private - */ - function splitTextToCharacters(text) { - return Array.from ? Array.from(text) : text.split(''); - } - - /** - * Processes the passed character set data and returns a flattened array of all the characters. - * - * Ignored because not directly exposed. - * @ignore - * @param {string | string[] | string[][] } chars - * @returns {string[]} the flattened array of characters - */ - function resolveCharacters(chars) { - // Split the chars string into individual characters - if (typeof chars === 'string') { - chars = [chars]; - } - // Handle an array of characters+ranges - var result = []; - for (var i = 0, j = chars.length; i < j; i++) { - var item = chars[i]; - // Handle range delimited by start/end chars - if (Array.isArray(item)) { - if (item.length !== 2) { - throw new Error("[BitmapFont]: Invalid character range length, expecting 2 got " + item.length + "."); - } - var startCode = item[0].charCodeAt(0); - var endCode = item[1].charCodeAt(0); - if (endCode < startCode) { - throw new Error('[BitmapFont]: Invalid character range.'); - } - for (var i_1 = startCode, j_1 = endCode; i_1 <= j_1; i_1++) { - result.push(String.fromCharCode(i_1)); - } - } - // Handle a character set string - else { - result.push.apply(result, splitTextToCharacters(item)); - } - } - if (result.length === 0) { - throw new Error('[BitmapFont]: Empty set when resolving characters.'); - } - return result; - } - - /** - * Ponyfill for IE because it doesn't support `codePointAt` - * @param str - * @private - */ - function extractCharCode(str) { - return str.codePointAt ? str.codePointAt(0) : str.charCodeAt(0); - } - - /** - * BitmapFont represents a typeface available for use with the BitmapText class. Use the `install` - * method for adding a font to be used. - * @memberof PIXI - */ - var BitmapFont = /** @class */ (function () { - /** - * @param data - * @param textures - * @param ownsTextures - Setting to `true` will destroy page textures - * when the font is uninstalled. - */ - function BitmapFont(data, textures, ownsTextures) { - var _a, _b; - var info = data.info[0]; - var common = data.common[0]; - var page = data.page[0]; - var distanceField = data.distanceField[0]; - var res = getResolutionOfUrl(page.file); - var pageTextures = {}; - this._ownsTextures = ownsTextures; - this.font = info.face; - this.size = info.size; - this.lineHeight = common.lineHeight / res; - this.chars = {}; - this.pageTextures = pageTextures; - // Convert the input Texture, Textures or object - // into a page Texture lookup by "id" - for (var i = 0; i < data.page.length; i++) { - var _c = data.page[i], id = _c.id, file = _c.file; - pageTextures[id] = textures instanceof Array - ? textures[i] : textures[file]; - // only MSDF and SDF fonts need no-premultiplied-alpha - if ((distanceField === null || distanceField === void 0 ? void 0 : distanceField.fieldType) && distanceField.fieldType !== 'none') { - pageTextures[id].baseTexture.alphaMode = exports.ALPHA_MODES.NO_PREMULTIPLIED_ALPHA; - pageTextures[id].baseTexture.mipmap = exports.MIPMAP_MODES.OFF; - } - } - // parse letters - for (var i = 0; i < data.char.length; i++) { - var _d = data.char[i], id = _d.id, page_1 = _d.page; - var _e = data.char[i], x = _e.x, y = _e.y, width = _e.width, height = _e.height, xoffset = _e.xoffset, yoffset = _e.yoffset, xadvance = _e.xadvance; - x /= res; - y /= res; - width /= res; - height /= res; - xoffset /= res; - yoffset /= res; - xadvance /= res; - var rect = new Rectangle(x + (pageTextures[page_1].frame.x / res), y + (pageTextures[page_1].frame.y / res), width, height); - this.chars[id] = { - xOffset: xoffset, - yOffset: yoffset, - xAdvance: xadvance, - kerning: {}, - texture: new Texture(pageTextures[page_1].baseTexture, rect), - page: page_1, - }; - } - // parse kernings - for (var i = 0; i < data.kerning.length; i++) { - var _f = data.kerning[i], first = _f.first, second = _f.second, amount = _f.amount; - first /= res; - second /= res; - amount /= res; - if (this.chars[second]) { - this.chars[second].kerning[first] = amount; - } - } - // Store distance field information - this.distanceFieldRange = distanceField === null || distanceField === void 0 ? void 0 : distanceField.distanceRange; - this.distanceFieldType = (_b = (_a = distanceField === null || distanceField === void 0 ? void 0 : distanceField.fieldType) === null || _a === void 0 ? void 0 : _a.toLowerCase()) !== null && _b !== void 0 ? _b : 'none'; - } - /** Remove references to created glyph textures. */ - BitmapFont.prototype.destroy = function () { - for (var id in this.chars) { - this.chars[id].texture.destroy(); - this.chars[id].texture = null; - } - for (var id in this.pageTextures) { - if (this._ownsTextures) { - this.pageTextures[id].destroy(true); - } - this.pageTextures[id] = null; - } - // Set readonly null. - this.chars = null; - this.pageTextures = null; - }; - /** - * Register a new bitmap font. - * @param data - The - * characters map that could be provided as xml or raw string. - * @param textures - List of textures for each page. - * @param ownsTextures - Set to `true` to destroy page textures - * when the font is uninstalled. By default fonts created with - * `BitmapFont.from` or from the `BitmapFontLoader` are `true`. - * @returns {PIXI.BitmapFont} Result font object with font, size, lineHeight - * and char fields. - */ - BitmapFont.install = function (data, textures, ownsTextures) { - var fontData; - if (data instanceof BitmapFontData) { - fontData = data; - } - else { - var format = autoDetectFormat(data); - if (!format) { - throw new Error('Unrecognized data format for font.'); - } - fontData = format.parse(data); - } - // Single texture, convert to list - if (textures instanceof Texture) { - textures = [textures]; - } - var font = new BitmapFont(fontData, textures, ownsTextures); - BitmapFont.available[font.font] = font; - return font; - }; - /** - * Remove bitmap font by name. - * @param name - Name of the font to uninstall. - */ - BitmapFont.uninstall = function (name) { - var font = BitmapFont.available[name]; - if (!font) { - throw new Error("No font found named '" + name + "'"); - } - font.destroy(); - delete BitmapFont.available[name]; - }; - /** - * Generates a bitmap-font for the given style and character set. This does not support - * kernings yet. With `style` properties, only the following non-layout properties are used: - * - * - {@link PIXI.TextStyle#dropShadow|dropShadow} - * - {@link PIXI.TextStyle#dropShadowDistance|dropShadowDistance} - * - {@link PIXI.TextStyle#dropShadowColor|dropShadowColor} - * - {@link PIXI.TextStyle#dropShadowBlur|dropShadowBlur} - * - {@link PIXI.TextStyle#dropShadowAngle|dropShadowAngle} - * - {@link PIXI.TextStyle#fill|fill} - * - {@link PIXI.TextStyle#fillGradientStops|fillGradientStops} - * - {@link PIXI.TextStyle#fillGradientType|fillGradientType} - * - {@link PIXI.TextStyle#fontFamily|fontFamily} - * - {@link PIXI.TextStyle#fontSize|fontSize} - * - {@link PIXI.TextStyle#fontVariant|fontVariant} - * - {@link PIXI.TextStyle#fontWeight|fontWeight} - * - {@link PIXI.TextStyle#lineJoin|lineJoin} - * - {@link PIXI.TextStyle#miterLimit|miterLimit} - * - {@link PIXI.TextStyle#stroke|stroke} - * - {@link PIXI.TextStyle#strokeThickness|strokeThickness} - * - {@link PIXI.TextStyle#textBaseline|textBaseline} - * @param name - The name of the custom font to use with BitmapText. - * @param textStyle - Style options to render with BitmapFont. - * @param options - Setup options for font or name of the font. - * @param {string|string[]|string[][]} [options.chars=PIXI.BitmapFont.ALPHANUMERIC] - characters included - * in the font set. You can also use ranges. For example, `[['a', 'z'], ['A', 'Z'], "!@#$%^&*()~{}[] "]`. - * Don't forget to include spaces ' ' in your character set! - * @param {number} [options.resolution=1] - Render resolution for glyphs. - * @param {number} [options.textureWidth=512] - Optional width of atlas, smaller values to reduce memory. - * @param {number} [options.textureHeight=512] - Optional height of atlas, smaller values to reduce memory. - * @param {number} [options.padding=4] - Padding between glyphs on texture atlas. - * @returns Font generated by style options. - * @example - * PIXI.BitmapFont.from("TitleFont", { - * fontFamily: "Arial", - * fontSize: 12, - * strokeThickness: 2, - * fill: "purple" - * }); - * - * const title = new PIXI.BitmapText("This is the title", { fontName: "TitleFont" }); - */ - BitmapFont.from = function (name, textStyle, options) { - if (!name) { - throw new Error('[BitmapFont] Property `name` is required.'); - } - var _a = Object.assign({}, BitmapFont.defaultOptions, options), chars = _a.chars, padding = _a.padding, resolution = _a.resolution, textureWidth = _a.textureWidth, textureHeight = _a.textureHeight; - var charsList = resolveCharacters(chars); - var style = textStyle instanceof TextStyle ? textStyle : new TextStyle(textStyle); - var lineWidth = textureWidth; - var fontData = new BitmapFontData(); - fontData.info[0] = { - face: style.fontFamily, - size: style.fontSize, - }; - fontData.common[0] = { - lineHeight: style.fontSize, - }; - var positionX = 0; - var positionY = 0; - var canvas; - var context; - var baseTexture; - var maxCharHeight = 0; - var textures = []; - for (var i = 0; i < charsList.length; i++) { - if (!canvas) { - canvas = settings.ADAPTER.createCanvas(); - canvas.width = textureWidth; - canvas.height = textureHeight; - context = canvas.getContext('2d'); - baseTexture = new BaseTexture(canvas, { resolution: resolution }); - textures.push(new Texture(baseTexture)); - fontData.page.push({ - id: textures.length - 1, - file: '', - }); - } - // Measure glyph dimensions - var character = charsList[i]; - var metrics = TextMetrics.measureText(character, style, false, canvas); - var width = metrics.width; - var height = Math.ceil(metrics.height); - // This is ugly - but italics are given more space so they don't overlap - var textureGlyphWidth = Math.ceil((style.fontStyle === 'italic' ? 2 : 1) * width); - // Can't fit char anymore: next canvas please! - if (positionY >= textureHeight - (height * resolution)) { - if (positionY === 0) { - // We don't want user debugging an infinite loop (or do we? :) - throw new Error("[BitmapFont] textureHeight " + textureHeight + "px is too small " - + ("(fontFamily: '" + style.fontFamily + "', fontSize: " + style.fontSize + "px, char: '" + character + "')")); - } - --i; - // Create new atlas once current has filled up - canvas = null; - context = null; - baseTexture = null; - positionY = 0; - positionX = 0; - maxCharHeight = 0; - continue; - } - maxCharHeight = Math.max(height + metrics.fontProperties.descent, maxCharHeight); - // Wrap line once full row has been rendered - if ((textureGlyphWidth * resolution) + positionX >= lineWidth) { - if (positionX === 0) { - // Avoid infinite loop (There can be some very wide char like '\uFDFD'!) - throw new Error("[BitmapFont] textureWidth " + textureWidth + "px is too small " - + ("(fontFamily: '" + style.fontFamily + "', fontSize: " + style.fontSize + "px, char: '" + character + "')")); - } - --i; - positionY += maxCharHeight * resolution; - positionY = Math.ceil(positionY); - positionX = 0; - maxCharHeight = 0; - continue; - } - drawGlyph(canvas, context, metrics, positionX, positionY, resolution, style); - // Unique (numeric) ID mapping to this glyph - var id = extractCharCode(metrics.text); - // Create a texture holding just the glyph - fontData.char.push({ - id: id, - page: textures.length - 1, - x: positionX / resolution, - y: positionY / resolution, - width: textureGlyphWidth, - height: height, - xoffset: 0, - yoffset: 0, - xadvance: Math.ceil(width - - (style.dropShadow ? style.dropShadowDistance : 0) - - (style.stroke ? style.strokeThickness : 0)), - }); - positionX += (textureGlyphWidth + (2 * padding)) * resolution; - positionX = Math.ceil(positionX); - } - if (!(options === null || options === void 0 ? void 0 : options.skipKerning)) { - // Brute-force kerning info, this can be expensive b/c it's an O(n²), - // but we're using measureText which is native and fast. - for (var i = 0, len = charsList.length; i < len; i++) { - var first = charsList[i]; - for (var j = 0; j < len; j++) { - var second = charsList[j]; - var c1 = context.measureText(first).width; - var c2 = context.measureText(second).width; - var total = context.measureText(first + second).width; - var amount = total - (c1 + c2); - if (amount) { - fontData.kerning.push({ - first: extractCharCode(first), - second: extractCharCode(second), - amount: amount, - }); - } - } - } - } - var font = new BitmapFont(fontData, textures, true); - // Make it easier to replace a font - if (BitmapFont.available[name] !== undefined) { - BitmapFont.uninstall(name); - } - BitmapFont.available[name] = font; - return font; - }; - /** - * This character set includes all the letters in the alphabet (both lower- and upper- case). - * @type {string[][]} - * @example - * BitmapFont.from("ExampleFont", style, { chars: BitmapFont.ALPHA }) - */ - BitmapFont.ALPHA = [['a', 'z'], ['A', 'Z'], ' ']; - /** - * This character set includes all decimal digits (from 0 to 9). - * @type {string[][]} - * @example - * BitmapFont.from("ExampleFont", style, { chars: BitmapFont.NUMERIC }) - */ - BitmapFont.NUMERIC = [['0', '9']]; - /** - * This character set is the union of `BitmapFont.ALPHA` and `BitmapFont.NUMERIC`. - * @type {string[][]} - */ - BitmapFont.ALPHANUMERIC = [['a', 'z'], ['A', 'Z'], ['0', '9'], ' ']; - /** - * This character set consists of all the ASCII table. - * @member {string[][]} - * @see http://www.asciitable.com/ - */ - BitmapFont.ASCII = [[' ', '~']]; - /** - * Collection of default options when using `BitmapFont.from`. - * @property {number} [resolution=1] - - * @property {number} [textureWidth=512] - - * @property {number} [textureHeight=512] - - * @property {number} [padding=4] - - * @property {string|string[]|string[][]} chars = PIXI.BitmapFont.ALPHANUMERIC - */ - BitmapFont.defaultOptions = { - resolution: 1, - textureWidth: 512, - textureHeight: 512, - padding: 4, - chars: BitmapFont.ALPHANUMERIC, - }; - /** Collection of available/installed fonts. */ - BitmapFont.available = {}; - return BitmapFont; - }()); - - var msdfFrag = "// Pixi texture info\r\nvarying vec2 vTextureCoord;\r\nuniform sampler2D uSampler;\r\n\r\n// Tint\r\nuniform vec4 uColor;\r\n\r\n// on 2D applications fwidth is screenScale / glyphAtlasScale * distanceFieldRange\r\nuniform float uFWidth;\r\n\r\nvoid main(void) {\r\n\r\n // To stack MSDF and SDF we need a non-pre-multiplied-alpha texture.\r\n vec4 texColor = texture2D(uSampler, vTextureCoord);\r\n\r\n // MSDF\r\n float median = texColor.r + texColor.g + texColor.b -\r\n min(texColor.r, min(texColor.g, texColor.b)) -\r\n max(texColor.r, max(texColor.g, texColor.b));\r\n // SDF\r\n median = min(median, texColor.a);\r\n\r\n float screenPxDistance = uFWidth * (median - 0.5);\r\n float alpha = clamp(screenPxDistance + 0.5, 0.0, 1.0);\r\n if (median < 0.01) {\r\n alpha = 0.0;\r\n } else if (median > 0.99) {\r\n alpha = 1.0;\r\n }\r\n\r\n // NPM Textures, NPM outputs\r\n gl_FragColor = vec4(uColor.rgb, uColor.a * alpha);\r\n\r\n}\r\n"; - - var msdfVert = "// Mesh material default fragment\r\nattribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\nuniform mat3 translationMatrix;\r\nuniform mat3 uTextureMatrix;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\r\n}\r\n"; - - // If we ever need more than two pools, please make a Dict or something better. - var pageMeshDataDefaultPageMeshData = []; - var pageMeshDataMSDFPageMeshData = []; - var charRenderDataPool = []; - /** - * A BitmapText object will create a line or multiple lines of text using bitmap font. - * - * The primary advantage of this class over Text is that all of your textures are pre-generated and loading, - * meaning that rendering is fast, and changing text has no performance implications. - * - * Supporting character sets other than latin, such as CJK languages, may be impractical due to the number of characters. - * - * To split a line you can use '\n', '\r' or '\r\n' in your string. - * - * PixiJS can auto-generate fonts on-the-fly using BitmapFont or use fnt files provided by: - * http://www.angelcode.com/products/bmfont/ for Windows or - * http://www.bmglyph.com/ for Mac. - * - * You can also use SDF, MSDF and MTSDF BitmapFonts for vector-like scaling appearance provided by: - * https://github.com/soimy/msdf-bmfont-xml for SDF and MSDF fnt files or - * https://github.com/Chlumsky/msdf-atlas-gen for SDF, MSDF and MTSDF json files - * - * A BitmapText can only be created when the font is loaded. - * - * ```js - * // in this case the font is in a file called 'desyrel.fnt' - * let bitmapText = new PIXI.BitmapText("text using a fancy font!", { - * fontName: "Desyrel", - * fontSize: 35, - * align: "right" - * }); - * ``` - * @memberof PIXI - */ - var BitmapText = /** @class */ (function (_super) { - __extends$8(BitmapText, _super); - /** - * @param text - A string that you would like the text to display. - * @param style - The style parameters. - * @param {string} style.fontName - The installed BitmapFont name. - * @param {number} [style.fontSize] - The size of the font in pixels, e.g. 24. If undefined, - *. this will default to the BitmapFont size. - * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center', 'right' or 'justify'), - * does not affect single line text. - * @param {number} [style.tint=0xFFFFFF] - The tint color. - * @param {number} [style.letterSpacing=0] - The amount of spacing between letters. - * @param {number} [style.maxWidth=0] - The max width of the text before line wrapping. - */ - function BitmapText(text, style) { - if (style === void 0) { style = {}; } - var _this = _super.call(this) || this; - /** - * Private tracker for the current tint. - * @private - */ - _this._tint = 0xFFFFFF; - // Apply the defaults - var _a = Object.assign({}, BitmapText.styleDefaults, style), align = _a.align, tint = _a.tint, maxWidth = _a.maxWidth, letterSpacing = _a.letterSpacing, fontName = _a.fontName, fontSize = _a.fontSize; - if (!BitmapFont.available[fontName]) { - throw new Error("Missing BitmapFont \"" + fontName + "\""); - } - _this._activePagesMeshData = []; - _this._textWidth = 0; - _this._textHeight = 0; - _this._align = align; - _this._tint = tint; - _this._font = undefined; - _this._fontName = fontName; - _this._fontSize = fontSize; - _this.text = text; - _this._maxWidth = maxWidth; - _this._maxLineHeight = 0; - _this._letterSpacing = letterSpacing; - _this._anchor = new ObservablePoint(function () { _this.dirty = true; }, _this, 0, 0); - _this._roundPixels = settings.ROUND_PIXELS; - _this.dirty = true; - _this._resolution = settings.RESOLUTION; - _this._autoResolution = true; - _this._textureCache = {}; - return _this; - } - /** Renders text and updates it when needed. This should only be called if the BitmapFont is regenerated. */ - BitmapText.prototype.updateText = function () { - var _a; - var data = BitmapFont.available[this._fontName]; - var fontSize = this.fontSize; - var scale = fontSize / data.size; - var pos = new Point(); - var chars = []; - var lineWidths = []; - var lineSpaces = []; - var text = this._text.replace(/(?:\r\n|\r)/g, '\n') || ' '; - var charsInput = splitTextToCharacters(text); - var maxWidth = this._maxWidth * data.size / fontSize; - var pageMeshDataPool = data.distanceFieldType === 'none' - ? pageMeshDataDefaultPageMeshData : pageMeshDataMSDFPageMeshData; - var prevCharCode = null; - var lastLineWidth = 0; - var maxLineWidth = 0; - var line = 0; - var lastBreakPos = -1; - var lastBreakWidth = 0; - var spacesRemoved = 0; - var maxLineHeight = 0; - var spaceCount = 0; - for (var i = 0; i < charsInput.length; i++) { - var char = charsInput[i]; - var charCode = extractCharCode(char); - if ((/(?:\s)/).test(char)) { - lastBreakPos = i; - lastBreakWidth = lastLineWidth; - spaceCount++; - } - if (char === '\r' || char === '\n') { - lineWidths.push(lastLineWidth); - lineSpaces.push(-1); - maxLineWidth = Math.max(maxLineWidth, lastLineWidth); - ++line; - ++spacesRemoved; - pos.x = 0; - pos.y += data.lineHeight; - prevCharCode = null; - spaceCount = 0; - continue; - } - var charData = data.chars[charCode]; - if (!charData) { - continue; - } - if (prevCharCode && charData.kerning[prevCharCode]) { - pos.x += charData.kerning[prevCharCode]; - } - var charRenderData = charRenderDataPool.pop() || { - texture: Texture.EMPTY, - line: 0, - charCode: 0, - prevSpaces: 0, - position: new Point(), - }; - charRenderData.texture = charData.texture; - charRenderData.line = line; - charRenderData.charCode = charCode; - charRenderData.position.x = pos.x + charData.xOffset + (this._letterSpacing / 2); - charRenderData.position.y = pos.y + charData.yOffset; - charRenderData.prevSpaces = spaceCount; - chars.push(charRenderData); - lastLineWidth = charRenderData.position.x - + Math.max(charData.xAdvance - charData.xOffset, charData.texture.orig.width); - pos.x += charData.xAdvance + this._letterSpacing; - maxLineHeight = Math.max(maxLineHeight, (charData.yOffset + charData.texture.height)); - prevCharCode = charCode; - if (lastBreakPos !== -1 && maxWidth > 0 && pos.x > maxWidth) { - ++spacesRemoved; - removeItems(chars, 1 + lastBreakPos - spacesRemoved, 1 + i - lastBreakPos); - i = lastBreakPos; - lastBreakPos = -1; - lineWidths.push(lastBreakWidth); - lineSpaces.push(chars.length > 0 ? chars[chars.length - 1].prevSpaces : 0); - maxLineWidth = Math.max(maxLineWidth, lastBreakWidth); - line++; - pos.x = 0; - pos.y += data.lineHeight; - prevCharCode = null; - spaceCount = 0; - } - } - var lastChar = charsInput[charsInput.length - 1]; - if (lastChar !== '\r' && lastChar !== '\n') { - if ((/(?:\s)/).test(lastChar)) { - lastLineWidth = lastBreakWidth; - } - lineWidths.push(lastLineWidth); - maxLineWidth = Math.max(maxLineWidth, lastLineWidth); - lineSpaces.push(-1); - } - var lineAlignOffsets = []; - for (var i = 0; i <= line; i++) { - var alignOffset = 0; - if (this._align === 'right') { - alignOffset = maxLineWidth - lineWidths[i]; - } - else if (this._align === 'center') { - alignOffset = (maxLineWidth - lineWidths[i]) / 2; - } - else if (this._align === 'justify') { - alignOffset = lineSpaces[i] < 0 ? 0 : (maxLineWidth - lineWidths[i]) / lineSpaces[i]; - } - lineAlignOffsets.push(alignOffset); - } - var lenChars = chars.length; - var pagesMeshData = {}; - var newPagesMeshData = []; - var activePagesMeshData = this._activePagesMeshData; - pageMeshDataPool.push.apply(pageMeshDataPool, activePagesMeshData); - for (var i = 0; i < lenChars; i++) { - var texture = chars[i].texture; - var baseTextureUid = texture.baseTexture.uid; - if (!pagesMeshData[baseTextureUid]) { - var pageMeshData = pageMeshDataPool.pop(); - if (!pageMeshData) { - var geometry = new MeshGeometry(); - var material = void 0; - var meshBlendMode = void 0; - if (data.distanceFieldType === 'none') { - material = new MeshMaterial(Texture.EMPTY); - meshBlendMode = exports.BLEND_MODES.NORMAL; - } - else { - material = new MeshMaterial(Texture.EMPTY, { program: Program.from(msdfVert, msdfFrag), uniforms: { uFWidth: 0 } }); - meshBlendMode = exports.BLEND_MODES.NORMAL_NPM; - } - var mesh = new Mesh(geometry, material); - mesh.blendMode = meshBlendMode; - pageMeshData = { - index: 0, - indexCount: 0, - vertexCount: 0, - uvsCount: 0, - total: 0, - mesh: mesh, - vertices: null, - uvs: null, - indices: null, - }; - } - // reset data.. - pageMeshData.index = 0; - pageMeshData.indexCount = 0; - pageMeshData.vertexCount = 0; - pageMeshData.uvsCount = 0; - pageMeshData.total = 0; - // TODO need to get page texture here somehow.. - var _textureCache = this._textureCache; - _textureCache[baseTextureUid] = _textureCache[baseTextureUid] || new Texture(texture.baseTexture); - pageMeshData.mesh.texture = _textureCache[baseTextureUid]; - pageMeshData.mesh.tint = this._tint; - newPagesMeshData.push(pageMeshData); - pagesMeshData[baseTextureUid] = pageMeshData; - } - pagesMeshData[baseTextureUid].total++; - } - // lets find any previously active pageMeshDatas that are no longer required for - // the updated text (if any), removed and return them to the pool. - for (var i = 0; i < activePagesMeshData.length; i++) { - if (newPagesMeshData.indexOf(activePagesMeshData[i]) === -1) { - this.removeChild(activePagesMeshData[i].mesh); - } - } - // next lets add any new meshes, that have not yet been added to this BitmapText - // we only add if its not already a child of this BitmapObject - for (var i = 0; i < newPagesMeshData.length; i++) { - if (newPagesMeshData[i].mesh.parent !== this) { - this.addChild(newPagesMeshData[i].mesh); - } - } - // active page mesh datas are set to be the new pages added. - this._activePagesMeshData = newPagesMeshData; - for (var i in pagesMeshData) { - var pageMeshData = pagesMeshData[i]; - var total = pageMeshData.total; - // lets only allocate new buffers if we can fit the new text in the current ones.. - // unless that is, we will be batching. Currently batching dose not respect the size property of mesh - if (!(((_a = pageMeshData.indices) === null || _a === void 0 ? void 0 : _a.length) > 6 * total) || pageMeshData.vertices.length < Mesh.BATCHABLE_SIZE * 2) { - pageMeshData.vertices = new Float32Array(4 * 2 * total); - pageMeshData.uvs = new Float32Array(4 * 2 * total); - pageMeshData.indices = new Uint16Array(6 * total); - } - else { - var total_1 = pageMeshData.total; - var vertices = pageMeshData.vertices; - // Clear the garbage at the end of the vertices buffer. This will prevent the bounds miscalculation. - for (var i_1 = total_1 * 4 * 2; i_1 < vertices.length; i_1++) { - vertices[i_1] = 0; - } - } - // as a buffer maybe bigger than the current word, we set the size of the meshMaterial - // to match the number of letters needed - pageMeshData.mesh.size = 6 * total; - } - for (var i = 0; i < lenChars; i++) { - var char = chars[i]; - var offset = char.position.x + (lineAlignOffsets[char.line] * (this._align === 'justify' ? char.prevSpaces : 1)); - if (this._roundPixels) { - offset = Math.round(offset); - } - var xPos = offset * scale; - var yPos = char.position.y * scale; - var texture = char.texture; - var pageMesh = pagesMeshData[texture.baseTexture.uid]; - var textureFrame = texture.frame; - var textureUvs = texture._uvs; - var index = pageMesh.index++; - pageMesh.indices[(index * 6) + 0] = 0 + (index * 4); - pageMesh.indices[(index * 6) + 1] = 1 + (index * 4); - pageMesh.indices[(index * 6) + 2] = 2 + (index * 4); - pageMesh.indices[(index * 6) + 3] = 0 + (index * 4); - pageMesh.indices[(index * 6) + 4] = 2 + (index * 4); - pageMesh.indices[(index * 6) + 5] = 3 + (index * 4); - pageMesh.vertices[(index * 8) + 0] = xPos; - pageMesh.vertices[(index * 8) + 1] = yPos; - pageMesh.vertices[(index * 8) + 2] = xPos + (textureFrame.width * scale); - pageMesh.vertices[(index * 8) + 3] = yPos; - pageMesh.vertices[(index * 8) + 4] = xPos + (textureFrame.width * scale); - pageMesh.vertices[(index * 8) + 5] = yPos + (textureFrame.height * scale); - pageMesh.vertices[(index * 8) + 6] = xPos; - pageMesh.vertices[(index * 8) + 7] = yPos + (textureFrame.height * scale); - pageMesh.uvs[(index * 8) + 0] = textureUvs.x0; - pageMesh.uvs[(index * 8) + 1] = textureUvs.y0; - pageMesh.uvs[(index * 8) + 2] = textureUvs.x1; - pageMesh.uvs[(index * 8) + 3] = textureUvs.y1; - pageMesh.uvs[(index * 8) + 4] = textureUvs.x2; - pageMesh.uvs[(index * 8) + 5] = textureUvs.y2; - pageMesh.uvs[(index * 8) + 6] = textureUvs.x3; - pageMesh.uvs[(index * 8) + 7] = textureUvs.y3; - } - this._textWidth = maxLineWidth * scale; - this._textHeight = (pos.y + data.lineHeight) * scale; - for (var i in pagesMeshData) { - var pageMeshData = pagesMeshData[i]; - // apply anchor - if (this.anchor.x !== 0 || this.anchor.y !== 0) { - var vertexCount = 0; - var anchorOffsetX = this._textWidth * this.anchor.x; - var anchorOffsetY = this._textHeight * this.anchor.y; - for (var i_2 = 0; i_2 < pageMeshData.total; i_2++) { - pageMeshData.vertices[vertexCount++] -= anchorOffsetX; - pageMeshData.vertices[vertexCount++] -= anchorOffsetY; - pageMeshData.vertices[vertexCount++] -= anchorOffsetX; - pageMeshData.vertices[vertexCount++] -= anchorOffsetY; - pageMeshData.vertices[vertexCount++] -= anchorOffsetX; - pageMeshData.vertices[vertexCount++] -= anchorOffsetY; - pageMeshData.vertices[vertexCount++] -= anchorOffsetX; - pageMeshData.vertices[vertexCount++] -= anchorOffsetY; - } - } - this._maxLineHeight = maxLineHeight * scale; - var vertexBuffer = pageMeshData.mesh.geometry.getBuffer('aVertexPosition'); - var textureBuffer = pageMeshData.mesh.geometry.getBuffer('aTextureCoord'); - var indexBuffer = pageMeshData.mesh.geometry.getIndex(); - vertexBuffer.data = pageMeshData.vertices; - textureBuffer.data = pageMeshData.uvs; - indexBuffer.data = pageMeshData.indices; - vertexBuffer.update(); - textureBuffer.update(); - indexBuffer.update(); - } - for (var i = 0; i < chars.length; i++) { - charRenderDataPool.push(chars[i]); - } - this._font = data; - this.dirty = false; - }; - BitmapText.prototype.updateTransform = function () { - this.validate(); - this.containerUpdateTransform(); - }; - BitmapText.prototype._render = function (renderer) { - if (this._autoResolution && this._resolution !== renderer.resolution) { - this._resolution = renderer.resolution; - this.dirty = true; - } - // Update the uniform - var _a = BitmapFont.available[this._fontName], distanceFieldRange = _a.distanceFieldRange, distanceFieldType = _a.distanceFieldType, size = _a.size; - if (distanceFieldType !== 'none') { - // Inject the shader code with the correct value - var _b = this.worldTransform, a = _b.a, b = _b.b, c = _b.c, d = _b.d; - var dx = Math.sqrt((a * a) + (b * b)); - var dy = Math.sqrt((c * c) + (d * d)); - var worldScale = (Math.abs(dx) + Math.abs(dy)) / 2; - var fontScale = this.fontSize / size; - for (var _i = 0, _c = this._activePagesMeshData; _i < _c.length; _i++) { - var mesh = _c[_i]; - mesh.mesh.shader.uniforms.uFWidth = worldScale * distanceFieldRange * fontScale * this._resolution; - } - } - _super.prototype._render.call(this, renderer); - }; - /** - * Validates text before calling parent's getLocalBounds - * @returns - The rectangular bounding area - */ - BitmapText.prototype.getLocalBounds = function () { - this.validate(); - return _super.prototype.getLocalBounds.call(this); - }; - /** - * Updates text when needed - * @private - */ - BitmapText.prototype.validate = function () { - var font = BitmapFont.available[this._fontName]; - if (!font) { - throw new Error("Missing BitmapFont \"" + this._fontName + "\""); - } - if (this._font !== font) { - this.dirty = true; - } - if (this.dirty) { - this.updateText(); - } - }; - Object.defineProperty(BitmapText.prototype, "tint", { - /** - * The tint of the BitmapText object. - * @default 0xffffff - */ - get: function () { - return this._tint; - }, - set: function (value) { - if (this._tint === value) - { return; } - this._tint = value; - for (var i = 0; i < this._activePagesMeshData.length; i++) { - this._activePagesMeshData[i].mesh.tint = value; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "align", { - /** - * The alignment of the BitmapText object. - * @member {string} - * @default 'left' - */ - get: function () { - return this._align; - }, - set: function (value) { - if (this._align !== value) { - this._align = value; - this.dirty = true; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "fontName", { - /** The name of the BitmapFont. */ - get: function () { - return this._fontName; - }, - set: function (value) { - if (!BitmapFont.available[value]) { - throw new Error("Missing BitmapFont \"" + value + "\""); - } - if (this._fontName !== value) { - this._fontName = value; - this.dirty = true; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "fontSize", { - /** The size of the font to display. */ - get: function () { - var _a; - return (_a = this._fontSize) !== null && _a !== void 0 ? _a : BitmapFont.available[this._fontName].size; - }, - set: function (value) { - if (this._fontSize !== value) { - this._fontSize = value; - this.dirty = true; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "anchor", { - /** - * The anchor sets the origin point of the text. - * - * The default is `(0,0)`, this means the text's origin is the top left. - * - * Setting the anchor to `(0.5,0.5)` means the text's origin is centered. - * - * Setting the anchor to `(1,1)` would mean the text's origin point will be the bottom right corner. - */ - get: function () { - return this._anchor; - }, - set: function (value) { - if (typeof value === 'number') { - this._anchor.set(value); - } - else { - this._anchor.copyFrom(value); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "text", { - /** The text of the BitmapText object. */ - get: function () { - return this._text; - }, - set: function (text) { - text = String(text === null || text === undefined ? '' : text); - if (this._text === text) { - return; - } - this._text = text; - this.dirty = true; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "maxWidth", { - /** - * The max width of this bitmap text in pixels. If the text provided is longer than the - * value provided, line breaks will be automatically inserted in the last whitespace. - * Disable by setting the value to 0. - */ - get: function () { - return this._maxWidth; - }, - set: function (value) { - if (this._maxWidth === value) { - return; - } - this._maxWidth = value; - this.dirty = true; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "maxLineHeight", { - /** - * The max line height. This is useful when trying to use the total height of the Text, - * i.e. when trying to vertically align. - * @readonly - */ - get: function () { - this.validate(); - return this._maxLineHeight; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "textWidth", { - /** - * The width of the overall text, different from fontSize, - * which is defined in the style object. - * @readonly - */ - get: function () { - this.validate(); - return this._textWidth; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "letterSpacing", { - /** Additional space between characters. */ - get: function () { - return this._letterSpacing; - }, - set: function (value) { - if (this._letterSpacing !== value) { - this._letterSpacing = value; - this.dirty = true; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "roundPixels", { - /** - * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. - * Advantages can include sharper image quality (like text) and faster rendering on canvas. - * The main disadvantage is movement of objects may appear less smooth. - * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} - * @default PIXI.settings.ROUND_PIXELS - */ - get: function () { - return this._roundPixels; - }, - set: function (value) { - if (value !== this._roundPixels) { - this._roundPixels = value; - this.dirty = true; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "textHeight", { - /** - * The height of the overall text, different from fontSize, - * which is defined in the style object. - * @readonly - */ - get: function () { - this.validate(); - return this._textHeight; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "resolution", { - /** - * The resolution / device pixel ratio of the canvas. - * - * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually. - * @default 1 - */ - get: function () { - return this._resolution; - }, - set: function (value) { - this._autoResolution = false; - if (this._resolution === value) { - return; - } - this._resolution = value; - this.dirty = true; - }, - enumerable: false, - configurable: true - }); - BitmapText.prototype.destroy = function (options) { - var _textureCache = this._textureCache; - var data = BitmapFont.available[this._fontName]; - var pageMeshDataPool = data.distanceFieldType === 'none' - ? pageMeshDataDefaultPageMeshData : pageMeshDataMSDFPageMeshData; - pageMeshDataPool.push.apply(pageMeshDataPool, this._activePagesMeshData); - for (var _i = 0, _a = this._activePagesMeshData; _i < _a.length; _i++) { - var pageMeshData = _a[_i]; - this.removeChild(pageMeshData.mesh); - } - this._activePagesMeshData = []; - // Release references to any cached textures in page pool - pageMeshDataPool - .filter(function (page) { return _textureCache[page.mesh.texture.baseTexture.uid]; }) - .forEach(function (page) { - page.mesh.texture = Texture.EMPTY; - }); - for (var id in _textureCache) { - var texture = _textureCache[id]; - texture.destroy(); - delete _textureCache[id]; - } - this._font = null; - this._textureCache = null; - _super.prototype.destroy.call(this, options); - }; - BitmapText.styleDefaults = { - align: 'left', - tint: 0xFFFFFF, - maxWidth: 0, - letterSpacing: 0, - }; - return BitmapText; - }(Container)); - - /** - * {@link PIXI.Loader Loader} middleware for loading - * bitmap-based fonts suitable for using with {@link PIXI.BitmapText}. - * @memberof PIXI - */ - var BitmapFontLoader = /** @class */ (function () { - function BitmapFontLoader() { - } - /** - * Called when the plugin is installed. - * @see PIXI.extensions.add - */ - BitmapFontLoader.add = function () { - exports.LoaderResource.setExtensionXhrType('fnt', exports.LoaderResource.XHR_RESPONSE_TYPE.TEXT); - }; - /** - * Called after a resource is loaded. - * @see PIXI.Loader.loaderMiddleware - * @param this - * @param {PIXI.LoaderResource} resource - * @param {Function} next - */ - BitmapFontLoader.use = function (resource, next) { - var format = autoDetectFormat(resource.data); - // Resource was not recognised as any of the expected font data format - if (!format) { - next(); - return; - } - var baseUrl = BitmapFontLoader.getBaseUrl(this, resource); - var data = format.parse(resource.data); - var textures = {}; - // Handle completed, when the number of textures - // load is the same number as references in the fnt file - var completed = function (page) { - textures[page.metadata.pageFile] = page.texture; - if (Object.keys(textures).length === data.page.length) { - resource.bitmapFont = BitmapFont.install(data, textures, true); - next(); - } - }; - for (var i = 0; i < data.page.length; ++i) { - var pageFile = data.page[i].file; - var url = baseUrl + pageFile; - var exists = false; - // incase the image is loaded outside - // using the same loader, resource will be available - for (var name in this.resources) { - var bitmapResource = this.resources[name]; - if (bitmapResource.url === url) { - bitmapResource.metadata.pageFile = pageFile; - if (bitmapResource.texture) { - completed(bitmapResource); - } - else { - bitmapResource.onAfterMiddleware.add(completed); - } - exists = true; - break; - } - } - // texture is not loaded, we'll attempt to add - // it to the load and add the texture to the list - if (!exists) { - // Standard loading options for images - var options = { - crossOrigin: resource.crossOrigin, - loadType: exports.LoaderResource.LOAD_TYPE.IMAGE, - metadata: Object.assign({ pageFile: pageFile }, resource.metadata.imageMetadata), - parentResource: resource, - }; - this.add(url, options, completed); - } - } - }; - /** - * Get folder path from a resource. - * @param loader - * @param resource - */ - BitmapFontLoader.getBaseUrl = function (loader, resource) { - var resUrl = !resource.isDataUrl ? BitmapFontLoader.dirname(resource.url) : ''; - if (resource.isDataUrl) { - if (resUrl === '.') { - resUrl = ''; - } - if (loader.baseUrl && resUrl) { - // if baseurl has a trailing slash then add one to resUrl so the replace works below - if (loader.baseUrl.charAt(loader.baseUrl.length - 1) === '/') { - resUrl += '/'; - } - } - } - // remove baseUrl from resUrl - resUrl = resUrl.replace(loader.baseUrl, ''); - // if there is an resUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. - if (resUrl && resUrl.charAt(resUrl.length - 1) !== '/') { - resUrl += '/'; - } - return resUrl; - }; - /** - * Replacement for NodeJS's path.dirname - * @param {string} url - Path to get directory for - */ - BitmapFontLoader.dirname = function (url) { - var dir = url - .replace(/\\/g, '/') // convert windows notation to UNIX notation, URL-safe because it's a forbidden character - .replace(/\/$/, '') // replace trailing slash - .replace(/\/[^\/]*$/, ''); // remove everything after the last - // File request is relative, use current directory - if (dir === url) { - return '.'; - } - // Started with a slash - else if (dir === '') { - return '/'; - } - return dir; - }; - /** @ignore */ - BitmapFontLoader.extension = exports.ExtensionType.Loader; - return BitmapFontLoader; - }()); - - /*! - * @pixi/filter-alpha - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/filter-alpha is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$7 = function(d, b) { - extendStatics$7 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$7(d, b); - }; - - function __extends$7(d, b) { - extendStatics$7(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var fragment$4 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n"; - - /** - * Simplest filter - applies alpha. - * - * Use this instead of Container's alpha property to avoid visual layering of individual elements. - * AlphaFilter applies alpha evenly across the entire display object and any opaque elements it contains. - * If elements are not opaque, they will blend with each other anyway. - * - * Very handy if you want to use common features of all filters: - * - * 1. Assign a blendMode to this filter, blend all elements inside display object with background. - * - * 2. To use clipping in display coordinates, assign a filterArea to the same container that has this filter. - * @memberof PIXI.filters - */ - var AlphaFilter = /** @class */ (function (_super) { - __extends$7(AlphaFilter, _super); - /** - * @param alpha - Amount of alpha from 0 to 1, where 0 is transparent - */ - function AlphaFilter(alpha) { - if (alpha === void 0) { alpha = 1.0; } - var _this = _super.call(this, defaultVertex$1, fragment$4, { uAlpha: 1 }) || this; - _this.alpha = alpha; - return _this; - } - Object.defineProperty(AlphaFilter.prototype, "alpha", { - /** - * Coefficient for alpha multiplication - * @default 1 - */ - get: function () { - return this.uniforms.uAlpha; - }, - set: function (value) { - this.uniforms.uAlpha = value; - }, - enumerable: false, - configurable: true - }); - return AlphaFilter; - }(Filter)); - - /*! - * @pixi/filter-blur - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/filter-blur is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$6 = function(d, b) { - extendStatics$6 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$6(d, b); - }; - - function __extends$6(d, b) { - extendStatics$6(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var vertTemplate = "\n attribute vec2 aVertexPosition;\n\n uniform mat3 projectionMatrix;\n\n uniform float strength;\n\n varying vec2 vBlurTexCoords[%size%];\n\n uniform vec4 inputSize;\n uniform vec4 outputFrame;\n\n vec4 filterVertexPosition( void )\n {\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n }\n\n vec2 filterTextureCoord( void )\n {\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n }\n\n void main(void)\n {\n gl_Position = filterVertexPosition();\n\n vec2 textureCoord = filterTextureCoord();\n %blur%\n }"; - function generateBlurVertSource(kernelSize, x) { - var halfLength = Math.ceil(kernelSize / 2); - var vertSource = vertTemplate; - var blurLoop = ''; - var template; - if (x) { - template = 'vBlurTexCoords[%index%] = textureCoord + vec2(%sampleIndex% * strength, 0.0);'; - } - else { - template = 'vBlurTexCoords[%index%] = textureCoord + vec2(0.0, %sampleIndex% * strength);'; - } - for (var i = 0; i < kernelSize; i++) { - var blur = template.replace('%index%', i.toString()); - blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + ".0"); - blurLoop += blur; - blurLoop += '\n'; - } - vertSource = vertSource.replace('%blur%', blurLoop); - vertSource = vertSource.replace('%size%', kernelSize.toString()); - return vertSource; - } - - var GAUSSIAN_VALUES = { - 5: [0.153388, 0.221461, 0.250301], - 7: [0.071303, 0.131514, 0.189879, 0.214607], - 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], - 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], - 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], - 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448], - }; - var fragTemplate = [ - 'varying vec2 vBlurTexCoords[%size%];', - 'uniform sampler2D uSampler;', - 'void main(void)', - '{', - ' gl_FragColor = vec4(0.0);', - ' %blur%', - '}' ].join('\n'); - function generateBlurFragSource(kernelSize) { - var kernel = GAUSSIAN_VALUES[kernelSize]; - var halfLength = kernel.length; - var fragSource = fragTemplate; - var blurLoop = ''; - var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; - var value; - for (var i = 0; i < kernelSize; i++) { - var blur = template.replace('%index%', i.toString()); - value = i; - if (i >= halfLength) { - value = kernelSize - i - 1; - } - blur = blur.replace('%value%', kernel[value].toString()); - blurLoop += blur; - blurLoop += '\n'; - } - fragSource = fragSource.replace('%blur%', blurLoop); - fragSource = fragSource.replace('%size%', kernelSize.toString()); - return fragSource; - } - - /** - * The BlurFilterPass applies a horizontal or vertical Gaussian blur to an object. - * @memberof PIXI.filters - */ - var BlurFilterPass = /** @class */ (function (_super) { - __extends$6(BlurFilterPass, _super); - /** - * @param horizontal - Do pass along the x-axis (`true`) or y-axis (`false`). - * @param strength - The strength of the blur filter. - * @param quality - The quality of the blur filter. - * @param resolution - The resolution of the blur filter. - * @param kernelSize - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. - */ - function BlurFilterPass(horizontal, strength, quality, resolution, kernelSize) { - if (strength === void 0) { strength = 8; } - if (quality === void 0) { quality = 4; } - if (resolution === void 0) { resolution = settings.FILTER_RESOLUTION; } - if (kernelSize === void 0) { kernelSize = 5; } - var _this = this; - var vertSrc = generateBlurVertSource(kernelSize, horizontal); - var fragSrc = generateBlurFragSource(kernelSize); - _this = _super.call(this, - // vertex shader - vertSrc, - // fragment shader - fragSrc) || this; - _this.horizontal = horizontal; - _this.resolution = resolution; - _this._quality = 0; - _this.quality = quality; - _this.blur = strength; - return _this; - } - /** - * Applies the filter. - * @param filterManager - The manager. - * @param input - The input target. - * @param output - The output target. - * @param clearMode - How to clear - */ - BlurFilterPass.prototype.apply = function (filterManager, input, output, clearMode) { - if (output) { - if (this.horizontal) { - this.uniforms.strength = (1 / output.width) * (output.width / input.width); - } - else { - this.uniforms.strength = (1 / output.height) * (output.height / input.height); - } - } - else { - if (this.horizontal) // eslint-disable-line - { - this.uniforms.strength = (1 / filterManager.renderer.width) * (filterManager.renderer.width / input.width); - } - else { - this.uniforms.strength = (1 / filterManager.renderer.height) * (filterManager.renderer.height / input.height); // eslint-disable-line - } - } - // screen space! - this.uniforms.strength *= this.strength; - this.uniforms.strength /= this.passes; - if (this.passes === 1) { - filterManager.applyFilter(this, input, output, clearMode); - } - else { - var renderTarget = filterManager.getFilterTexture(); - var renderer = filterManager.renderer; - var flip = input; - var flop = renderTarget; - this.state.blend = false; - filterManager.applyFilter(this, flip, flop, exports.CLEAR_MODES.CLEAR); - for (var i = 1; i < this.passes - 1; i++) { - filterManager.bindAndClear(flip, exports.CLEAR_MODES.BLIT); - this.uniforms.uSampler = flop; - var temp = flop; - flop = flip; - flip = temp; - renderer.shader.bind(this); - renderer.geometry.draw(5); - } - this.state.blend = true; - filterManager.applyFilter(this, flop, output, clearMode); - filterManager.returnFilterTexture(renderTarget); - } - }; - Object.defineProperty(BlurFilterPass.prototype, "blur", { - /** - * Sets the strength of both the blur. - * @default 16 - */ - get: function () { - return this.strength; - }, - set: function (value) { - this.padding = 1 + (Math.abs(value) * 2); - this.strength = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlurFilterPass.prototype, "quality", { - /** - * Sets the quality of the blur by modifying the number of passes. More passes means higher - * quality bluring but the lower the performance. - * @default 4 - */ - get: function () { - return this._quality; - }, - set: function (value) { - this._quality = value; - this.passes = value; - }, - enumerable: false, - configurable: true - }); - return BlurFilterPass; - }(Filter)); - - /** - * The BlurFilter applies a Gaussian blur to an object. - * - * The strength of the blur can be set for the x-axis and y-axis separately. - * @memberof PIXI.filters - */ - var BlurFilter = /** @class */ (function (_super) { - __extends$6(BlurFilter, _super); - /** - * @param strength - The strength of the blur filter. - * @param quality - The quality of the blur filter. - * @param [resolution=PIXI.settings.FILTER_RESOLUTION] - The resolution of the blur filter. - * @param kernelSize - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. - */ - function BlurFilter(strength, quality, resolution, kernelSize) { - if (strength === void 0) { strength = 8; } - if (quality === void 0) { quality = 4; } - if (resolution === void 0) { resolution = settings.FILTER_RESOLUTION; } - if (kernelSize === void 0) { kernelSize = 5; } - var _this = _super.call(this) || this; - _this.blurXFilter = new BlurFilterPass(true, strength, quality, resolution, kernelSize); - _this.blurYFilter = new BlurFilterPass(false, strength, quality, resolution, kernelSize); - _this.resolution = resolution; - _this.quality = quality; - _this.blur = strength; - _this.repeatEdgePixels = false; - return _this; - } - /** - * Applies the filter. - * @param filterManager - The manager. - * @param input - The input target. - * @param output - The output target. - * @param clearMode - How to clear - */ - BlurFilter.prototype.apply = function (filterManager, input, output, clearMode) { - var xStrength = Math.abs(this.blurXFilter.strength); - var yStrength = Math.abs(this.blurYFilter.strength); - if (xStrength && yStrength) { - var renderTarget = filterManager.getFilterTexture(); - this.blurXFilter.apply(filterManager, input, renderTarget, exports.CLEAR_MODES.CLEAR); - this.blurYFilter.apply(filterManager, renderTarget, output, clearMode); - filterManager.returnFilterTexture(renderTarget); - } - else if (yStrength) { - this.blurYFilter.apply(filterManager, input, output, clearMode); - } - else { - this.blurXFilter.apply(filterManager, input, output, clearMode); - } - }; - BlurFilter.prototype.updatePadding = function () { - if (this._repeatEdgePixels) { - this.padding = 0; - } - else { - this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; - } - }; - Object.defineProperty(BlurFilter.prototype, "blur", { - /** - * Sets the strength of both the blurX and blurY properties simultaneously - * @default 2 - */ - get: function () { - return this.blurXFilter.blur; - }, - set: function (value) { - this.blurXFilter.blur = this.blurYFilter.blur = value; - this.updatePadding(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlurFilter.prototype, "quality", { - /** - * Sets the number of passes for blur. More passes means higher quality bluring. - * @default 1 - */ - get: function () { - return this.blurXFilter.quality; - }, - set: function (value) { - this.blurXFilter.quality = this.blurYFilter.quality = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlurFilter.prototype, "blurX", { - /** - * Sets the strength of the blurX property - * @default 2 - */ - get: function () { - return this.blurXFilter.blur; - }, - set: function (value) { - this.blurXFilter.blur = value; - this.updatePadding(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlurFilter.prototype, "blurY", { - /** - * Sets the strength of the blurY property - * @default 2 - */ - get: function () { - return this.blurYFilter.blur; - }, - set: function (value) { - this.blurYFilter.blur = value; - this.updatePadding(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlurFilter.prototype, "blendMode", { - /** - * Sets the blendmode of the filter - * @default PIXI.BLEND_MODES.NORMAL - */ - get: function () { - return this.blurYFilter.blendMode; - }, - set: function (value) { - this.blurYFilter.blendMode = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlurFilter.prototype, "repeatEdgePixels", { - /** - * If set to true the edge of the target will be clamped - * @default false - */ - get: function () { - return this._repeatEdgePixels; - }, - set: function (value) { - this._repeatEdgePixels = value; - this.updatePadding(); - }, - enumerable: false, - configurable: true - }); - return BlurFilter; - }(Filter)); - - /*! - * @pixi/filter-color-matrix - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/filter-color-matrix is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$5 = function(d, b) { - extendStatics$5 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$5(d, b); - }; - - function __extends$5(d, b) { - extendStatics$5(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var fragment$3 = "varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n"; - - /** - * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA - * color and alpha values of every pixel on your displayObject to produce a result - * with a new set of RGBA color and alpha values. It's pretty powerful! - * - * ```js - * let colorMatrix = new PIXI.filters.ColorMatrixFilter(); - * container.filters = [colorMatrix]; - * colorMatrix.contrast(2); - * ``` - * @author Clément Chenebault - * @memberof PIXI.filters - */ - var ColorMatrixFilter = /** @class */ (function (_super) { - __extends$5(ColorMatrixFilter, _super); - function ColorMatrixFilter() { - var _this = this; - var uniforms = { - m: new Float32Array([1, 0, 0, 0, 0, - 0, 1, 0, 0, 0, - 0, 0, 1, 0, 0, - 0, 0, 0, 1, 0]), - uAlpha: 1, - }; - _this = _super.call(this, defaultFilterVertex, fragment$3, uniforms) || this; - _this.alpha = 1; - return _this; - } - /** - * Transforms current matrix and set the new one - * @param {number[]} matrix - 5x4 matrix - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype._loadMatrix = function (matrix, multiply) { - if (multiply === void 0) { multiply = false; } - var newMatrix = matrix; - if (multiply) { - this._multiply(newMatrix, this.uniforms.m, matrix); - newMatrix = this._colorMatrix(newMatrix); - } - // set the new matrix - this.uniforms.m = newMatrix; - }; - /** - * Multiplies two mat5's - * @private - * @param out - 5x4 matrix the receiving matrix - * @param a - 5x4 matrix the first operand - * @param b - 5x4 matrix the second operand - * @returns {number[]} 5x4 matrix - */ - ColorMatrixFilter.prototype._multiply = function (out, a, b) { - // Red Channel - out[0] = (a[0] * b[0]) + (a[1] * b[5]) + (a[2] * b[10]) + (a[3] * b[15]); - out[1] = (a[0] * b[1]) + (a[1] * b[6]) + (a[2] * b[11]) + (a[3] * b[16]); - out[2] = (a[0] * b[2]) + (a[1] * b[7]) + (a[2] * b[12]) + (a[3] * b[17]); - out[3] = (a[0] * b[3]) + (a[1] * b[8]) + (a[2] * b[13]) + (a[3] * b[18]); - out[4] = (a[0] * b[4]) + (a[1] * b[9]) + (a[2] * b[14]) + (a[3] * b[19]) + a[4]; - // Green Channel - out[5] = (a[5] * b[0]) + (a[6] * b[5]) + (a[7] * b[10]) + (a[8] * b[15]); - out[6] = (a[5] * b[1]) + (a[6] * b[6]) + (a[7] * b[11]) + (a[8] * b[16]); - out[7] = (a[5] * b[2]) + (a[6] * b[7]) + (a[7] * b[12]) + (a[8] * b[17]); - out[8] = (a[5] * b[3]) + (a[6] * b[8]) + (a[7] * b[13]) + (a[8] * b[18]); - out[9] = (a[5] * b[4]) + (a[6] * b[9]) + (a[7] * b[14]) + (a[8] * b[19]) + a[9]; - // Blue Channel - out[10] = (a[10] * b[0]) + (a[11] * b[5]) + (a[12] * b[10]) + (a[13] * b[15]); - out[11] = (a[10] * b[1]) + (a[11] * b[6]) + (a[12] * b[11]) + (a[13] * b[16]); - out[12] = (a[10] * b[2]) + (a[11] * b[7]) + (a[12] * b[12]) + (a[13] * b[17]); - out[13] = (a[10] * b[3]) + (a[11] * b[8]) + (a[12] * b[13]) + (a[13] * b[18]); - out[14] = (a[10] * b[4]) + (a[11] * b[9]) + (a[12] * b[14]) + (a[13] * b[19]) + a[14]; - // Alpha Channel - out[15] = (a[15] * b[0]) + (a[16] * b[5]) + (a[17] * b[10]) + (a[18] * b[15]); - out[16] = (a[15] * b[1]) + (a[16] * b[6]) + (a[17] * b[11]) + (a[18] * b[16]); - out[17] = (a[15] * b[2]) + (a[16] * b[7]) + (a[17] * b[12]) + (a[18] * b[17]); - out[18] = (a[15] * b[3]) + (a[16] * b[8]) + (a[17] * b[13]) + (a[18] * b[18]); - out[19] = (a[15] * b[4]) + (a[16] * b[9]) + (a[17] * b[14]) + (a[18] * b[19]) + a[19]; - return out; - }; - /** - * Create a Float32 Array and normalize the offset component to 0-1 - * @param {number[]} matrix - 5x4 matrix - * @returns {number[]} 5x4 matrix with all values between 0-1 - */ - ColorMatrixFilter.prototype._colorMatrix = function (matrix) { - // Create a Float32 Array and normalize the offset component to 0-1 - var m = new Float32Array(matrix); - m[4] /= 255; - m[9] /= 255; - m[14] /= 255; - m[19] /= 255; - return m; - }; - /** - * Adjusts brightness - * @param b - value of the brigthness (0-1, where 0 is black) - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.brightness = function (b, multiply) { - var matrix = [ - b, 0, 0, 0, 0, - 0, b, 0, 0, 0, - 0, 0, b, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Sets each channel on the diagonal of the color matrix. - * This can be used to achieve a tinting effect on Containers similar to the tint field of some - * display objects like Sprite, Text, Graphics, and Mesh. - * @param color - Color of the tint. This is a hex value. - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.tint = function (color, multiply) { - var r = (color >> 16) & 0xff; - var g = (color >> 8) & 0xff; - var b = color & 0xff; - var matrix = [ - r / 255, 0, 0, 0, 0, - 0, g / 255, 0, 0, 0, - 0, 0, b / 255, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Set the matrices in grey scales - * @param scale - value of the grey (0-1, where 0 is black) - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.greyscale = function (scale, multiply) { - var matrix = [ - scale, scale, scale, 0, 0, - scale, scale, scale, 0, 0, - scale, scale, scale, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Set the black and white matrice. - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.blackAndWhite = function (multiply) { - var matrix = [ - 0.3, 0.6, 0.1, 0, 0, - 0.3, 0.6, 0.1, 0, 0, - 0.3, 0.6, 0.1, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Set the hue property of the color - * @param rotation - in degrees - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.hue = function (rotation, multiply) { - rotation = (rotation || 0) / 180 * Math.PI; - var cosR = Math.cos(rotation); - var sinR = Math.sin(rotation); - var sqrt = Math.sqrt; - /* a good approximation for hue rotation - This matrix is far better than the versions with magic luminance constants - formerly used here, but also used in the starling framework (flash) and known from this - old part of the internet: quasimondo.com/archives/000565.php - - This new matrix is based on rgb cube rotation in space. Look here for a more descriptive - implementation as a shader not a general matrix: - https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js - - This is the source for the code: - see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 - */ - var w = 1 / 3; - var sqrW = sqrt(w); // weight is - var a00 = cosR + ((1.0 - cosR) * w); - var a01 = (w * (1.0 - cosR)) - (sqrW * sinR); - var a02 = (w * (1.0 - cosR)) + (sqrW * sinR); - var a10 = (w * (1.0 - cosR)) + (sqrW * sinR); - var a11 = cosR + (w * (1.0 - cosR)); - var a12 = (w * (1.0 - cosR)) - (sqrW * sinR); - var a20 = (w * (1.0 - cosR)) - (sqrW * sinR); - var a21 = (w * (1.0 - cosR)) + (sqrW * sinR); - var a22 = cosR + (w * (1.0 - cosR)); - var matrix = [ - a00, a01, a02, 0, 0, - a10, a11, a12, 0, 0, - a20, a21, a22, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Set the contrast matrix, increase the separation between dark and bright - * Increase contrast : shadows darker and highlights brighter - * Decrease contrast : bring the shadows up and the highlights down - * @param amount - value of the contrast (0-1) - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.contrast = function (amount, multiply) { - var v = (amount || 0) + 1; - var o = -0.5 * (v - 1); - var matrix = [ - v, 0, 0, 0, o, - 0, v, 0, 0, o, - 0, 0, v, 0, o, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Set the saturation matrix, increase the separation between colors - * Increase saturation : increase contrast, brightness, and sharpness - * @param amount - The saturation amount (0-1) - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.saturate = function (amount, multiply) { - if (amount === void 0) { amount = 0; } - var x = (amount * 2 / 3) + 1; - var y = ((x - 1) * -0.5); - var matrix = [ - x, y, y, 0, 0, - y, x, y, 0, 0, - y, y, x, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** Desaturate image (remove color) Call the saturate function */ - ColorMatrixFilter.prototype.desaturate = function () { - this.saturate(-1); - }; - /** - * Negative image (inverse of classic rgb matrix) - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.negative = function (multiply) { - var matrix = [ - -1, 0, 0, 1, 0, - 0, -1, 0, 1, 0, - 0, 0, -1, 1, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Sepia image - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.sepia = function (multiply) { - var matrix = [ - 0.393, 0.7689999, 0.18899999, 0, 0, - 0.349, 0.6859999, 0.16799999, 0, 0, - 0.272, 0.5339999, 0.13099999, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Color motion picture process invented in 1916 (thanks Dominic Szablewski) - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.technicolor = function (multiply) { - var matrix = [ - 1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, - -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, - -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Polaroid filter - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.polaroid = function (multiply) { - var matrix = [ - 1.438, -0.062, -0.062, 0, 0, - -0.122, 1.378, -0.122, 0, 0, - -0.016, -0.016, 1.483, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Filter who transforms : Red -> Blue and Blue -> Red - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.toBGR = function (multiply) { - var matrix = [ - 0, 0, 1, 0, 0, - 0, 1, 0, 0, 0, - 1, 0, 0, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.kodachrome = function (multiply) { - var matrix = [ - 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, - -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, - -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Brown delicious browni filter (thanks Dominic Szablewski) - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.browni = function (multiply) { - var matrix = [ - 0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, - -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, - 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Vintage filter (thanks Dominic Szablewski) - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.vintage = function (multiply) { - var matrix = [ - 0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, - 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, - 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * We don't know exactly what it does, kind of gradient map, but funny to play with! - * @param desaturation - Tone values. - * @param toned - Tone values. - * @param lightColor - Tone values, example: `0xFFE580` - * @param darkColor - Tone values, example: `0xFFE580` - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.colorTone = function (desaturation, toned, lightColor, darkColor, multiply) { - desaturation = desaturation || 0.2; - toned = toned || 0.15; - lightColor = lightColor || 0xFFE580; - darkColor = darkColor || 0x338000; - var lR = ((lightColor >> 16) & 0xFF) / 255; - var lG = ((lightColor >> 8) & 0xFF) / 255; - var lB = (lightColor & 0xFF) / 255; - var dR = ((darkColor >> 16) & 0xFF) / 255; - var dG = ((darkColor >> 8) & 0xFF) / 255; - var dB = (darkColor & 0xFF) / 255; - var matrix = [ - 0.3, 0.59, 0.11, 0, 0, - lR, lG, lB, desaturation, 0, - dR, dG, dB, toned, 0, - lR - dR, lG - dG, lB - dB, 0, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Night effect - * @param intensity - The intensity of the night effect. - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.night = function (intensity, multiply) { - intensity = intensity || 0.1; - var matrix = [ - intensity * (-2.0), -intensity, 0, 0, 0, - -intensity, 0, intensity, 0, 0, - 0, intensity, intensity * 2.0, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Predator effect - * - * Erase the current matrix by setting a new indepent one - * @param amount - how much the predator feels his future victim - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.predator = function (amount, multiply) { - var matrix = [ - // row 1 - 11.224130630493164 * amount, - -4.794486999511719 * amount, - -2.8746118545532227 * amount, - 0 * amount, - 0.40342438220977783 * amount, - // row 2 - -3.6330697536468506 * amount, - 9.193157196044922 * amount, - -2.951810836791992 * amount, - 0 * amount, - -1.316135048866272 * amount, - // row 3 - -3.2184197902679443 * amount, - -4.2375030517578125 * amount, - 7.476448059082031 * amount, - 0 * amount, - 0.8044459223747253 * amount, - // row 4 - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * LSD effect - * - * Multiply the current matrix - * @param multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.lsd = function (multiply) { - var matrix = [ - 2, -0.4, 0.5, 0, 0, - -0.5, 2, -0.4, 0, 0, - -0.4, -0.5, 3, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** Erase the current matrix by setting the default one. */ - ColorMatrixFilter.prototype.reset = function () { - var matrix = [ - 1, 0, 0, 0, 0, - 0, 1, 0, 0, 0, - 0, 0, 1, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, false); - }; - Object.defineProperty(ColorMatrixFilter.prototype, "matrix", { - /** - * The matrix of the color matrix filter - * @member {number[]} - * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] - */ - get: function () { - return this.uniforms.m; - }, - set: function (value) { - this.uniforms.m = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ColorMatrixFilter.prototype, "alpha", { - /** - * The opacity value to use when mixing the original and resultant colors. - * - * When the value is 0, the original color is used without modification. - * When the value is 1, the result color is used. - * When in the range (0, 1) the color is interpolated between the original and result by this amount. - * @default 1 - */ - get: function () { - return this.uniforms.uAlpha; - }, - set: function (value) { - this.uniforms.uAlpha = value; - }, - enumerable: false, - configurable: true - }); - return ColorMatrixFilter; - }(Filter)); - // Americanized alias - ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; - - /*! - * @pixi/filter-displacement - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/filter-displacement is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$4 = function(d, b) { - extendStatics$4 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$4(d, b); - }; - - function __extends$4(d, b) { - extendStatics$4(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var fragment$2 = "varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\nuniform mat2 rotation;\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform highp vec4 inputSize;\nuniform vec4 inputClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy = scale * inputSize.zw * (rotation * map.xy);\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), inputClamp.xy, inputClamp.zw));\n}\n"; - - var vertex$1 = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n\tgl_Position = filterVertexPosition();\n\tvTextureCoord = filterTextureCoord();\n\tvFilterCoord = ( filterMatrix * vec3( vTextureCoord, 1.0) ).xy;\n}\n"; - - /** - * The DisplacementFilter class uses the pixel values from the specified texture - * (called the displacement map) to perform a displacement of an object. - * - * You can use this filter to apply all manor of crazy warping effects. - * Currently the `r` property of the texture is used to offset the `x` - * and the `g` property of the texture is used to offset the `y`. - * - * The way it works is it uses the values of the displacement map to look up the - * correct pixels to output. This means it's not technically moving the original. - * Instead, it's starting at the output and asking "which pixel from the original goes here". - * For example, if a displacement map pixel has `red = 1` and the filter scale is `20`, - * this filter will output the pixel approximately 20 pixels to the right of the original. - * @memberof PIXI.filters - */ - var DisplacementFilter = /** @class */ (function (_super) { - __extends$4(DisplacementFilter, _super); - /** - * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) - * @param scale - The scale of the displacement - */ - function DisplacementFilter(sprite, scale) { - var _this = this; - var maskMatrix = new Matrix(); - sprite.renderable = false; - _this = _super.call(this, vertex$1, fragment$2, { - mapSampler: sprite._texture, - filterMatrix: maskMatrix, - scale: { x: 1, y: 1 }, - rotation: new Float32Array([1, 0, 0, 1]), - }) || this; - _this.maskSprite = sprite; - _this.maskMatrix = maskMatrix; - if (scale === null || scale === undefined) { - scale = 20; - } - /** - * scaleX, scaleY for displacements - * @member {PIXI.Point} - */ - _this.scale = new Point(scale, scale); - return _this; - } - /** - * Applies the filter. - * @param filterManager - The manager. - * @param input - The input target. - * @param output - The output target. - * @param clearMode - clearMode. - */ - DisplacementFilter.prototype.apply = function (filterManager, input, output, clearMode) { - // fill maskMatrix with _normalized sprite texture coords_ - this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); - this.uniforms.scale.x = this.scale.x; - this.uniforms.scale.y = this.scale.y; - // Extract rotation from world transform - var wt = this.maskSprite.worldTransform; - var lenX = Math.sqrt((wt.a * wt.a) + (wt.b * wt.b)); - var lenY = Math.sqrt((wt.c * wt.c) + (wt.d * wt.d)); - if (lenX !== 0 && lenY !== 0) { - this.uniforms.rotation[0] = wt.a / lenX; - this.uniforms.rotation[1] = wt.b / lenX; - this.uniforms.rotation[2] = wt.c / lenY; - this.uniforms.rotation[3] = wt.d / lenY; - } - // draw the filter... - filterManager.applyFilter(this, input, output, clearMode); - }; - Object.defineProperty(DisplacementFilter.prototype, "map", { - /** The texture used for the displacement map. Must be power of 2 sized texture. */ - get: function () { - return this.uniforms.mapSampler; - }, - set: function (value) { - this.uniforms.mapSampler = value; - }, - enumerable: false, - configurable: true - }); - return DisplacementFilter; - }(Filter)); - - /*! - * @pixi/filter-fxaa - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/filter-fxaa is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$3 = function(d, b) { - extendStatics$3 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$3(d, b); - }; - - function __extends$3(d, b) { - extendStatics$3(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var vertex = "\nattribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvoid texcoords(vec2 fragCoord, vec2 inverseVP,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = filterVertexPosition();\n\n vFragCoord = aVertexPosition * outputFrame.zw;\n\n texcoords(vFragCoord, inputSize.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}\n"; - - var fragment$1 = "varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\nuniform sampler2D uSampler;\nuniform highp vec4 inputSize;\n\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it's\n unsupported by WebGL.\n\n --\n\n From:\n https://github.com/mitsuhiko/webgl-meincraft\n\n Copyright (c) 2011 by Armin Ronacher.\n\n Some rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n\n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 inverseVP,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n\n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n\n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec4 color;\n\n color = fxaa(uSampler, vFragCoord, inputSize.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n"; - - /** - * Basic FXAA (Fast Approximate Anti-Aliasing) implementation based on the code on geeks3d.com - * with the modification that the texture2DLod stuff was removed since it is unsupported by WebGL. - * @see https://github.com/mitsuhiko/webgl-meincraft - * @memberof PIXI.filters - */ - var FXAAFilter = /** @class */ (function (_super) { - __extends$3(FXAAFilter, _super); - function FXAAFilter() { - // TODO - needs work - return _super.call(this, vertex, fragment$1) || this; - } - return FXAAFilter; - }(Filter)); - - /*! - * @pixi/filter-noise - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/filter-noise is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$2 = function(d, b) { - extendStatics$2 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$2(d, b); - }; - - function __extends$2(d, b) { - extendStatics$2(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var fragment = "precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n"; - - /** - * A Noise effect filter. - * - * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js - * @memberof PIXI.filters - * @author Vico @vicocotea - */ - var NoiseFilter = /** @class */ (function (_super) { - __extends$2(NoiseFilter, _super); - /** - * @param {number} [noise=0.5] - The noise intensity, should be a normalized value in the range [0, 1]. - * @param {number} [seed] - A random seed for the noise generation. Default is `Math.random()`. - */ - function NoiseFilter(noise, seed) { - if (noise === void 0) { noise = 0.5; } - if (seed === void 0) { seed = Math.random(); } - var _this = _super.call(this, defaultFilterVertex, fragment, { - uNoise: 0, - uSeed: 0, - }) || this; - _this.noise = noise; - _this.seed = seed; - return _this; - } - Object.defineProperty(NoiseFilter.prototype, "noise", { - /** - * The amount of noise to apply, this value should be in the range (0, 1]. - * @default 0.5 - */ - get: function () { - return this.uniforms.uNoise; - }, - set: function (value) { - this.uniforms.uNoise = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(NoiseFilter.prototype, "seed", { - /** A seed value to apply to the random noise generation. `Math.random()` is a good value to use. */ - get: function () { - return this.uniforms.uSeed; - }, - set: function (value) { - this.uniforms.uSeed = value; - }, - enumerable: false, - configurable: true - }); - return NoiseFilter; - }(Filter)); - - /*! - * @pixi/mixin-cache-as-bitmap - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/mixin-cache-as-bitmap is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - var _tempMatrix = new Matrix(); - DisplayObject.prototype._cacheAsBitmap = false; - DisplayObject.prototype._cacheData = null; - DisplayObject.prototype._cacheAsBitmapResolution = null; - DisplayObject.prototype._cacheAsBitmapMultisample = exports.MSAA_QUALITY.NONE; - // figured there's no point adding ALL the extra variables to prototype. - // this model can hold the information needed. This can also be generated on demand as - // most objects are not cached as bitmaps. - /** - * @class - * @ignore - * @private - */ - var CacheData = /** @class */ (function () { - function CacheData() { - this.textureCacheId = null; - this.originalRender = null; - this.originalRenderCanvas = null; - this.originalCalculateBounds = null; - this.originalGetLocalBounds = null; - this.originalUpdateTransform = null; - this.originalDestroy = null; - this.originalMask = null; - this.originalFilterArea = null; - this.originalContainsPoint = null; - this.sprite = null; - } - return CacheData; - }()); - Object.defineProperties(DisplayObject.prototype, { - /** - * The resolution to use for cacheAsBitmap. By default this will use the renderer's resolution - * but can be overriden for performance. Lower values will reduce memory usage at the expense - * of render quality. A falsey value of `null` or `0` will default to the renderer's resolution. - * If `cacheAsBitmap` is set to `true`, this will re-render with the new resolution. - * @member {number} cacheAsBitmapResolution - * @memberof PIXI.DisplayObject# - * @default null - */ - cacheAsBitmapResolution: { - get: function () { - return this._cacheAsBitmapResolution; - }, - set: function (resolution) { - if (resolution === this._cacheAsBitmapResolution) { - return; - } - this._cacheAsBitmapResolution = resolution; - if (this.cacheAsBitmap) { - // Toggle to re-render at the new resolution - this.cacheAsBitmap = false; - this.cacheAsBitmap = true; - } - }, - }, - /** - * The number of samples to use for cacheAsBitmap. If set to `null`, the renderer's - * sample count is used. - * If `cacheAsBitmap` is set to `true`, this will re-render with the new number of samples. - * @member {number} cacheAsBitmapMultisample - * @memberof PIXI.DisplayObject# - * @default PIXI.MSAA_QUALITY.NONE - */ - cacheAsBitmapMultisample: { - get: function () { - return this._cacheAsBitmapMultisample; - }, - set: function (multisample) { - if (multisample === this._cacheAsBitmapMultisample) { - return; - } - this._cacheAsBitmapMultisample = multisample; - if (this.cacheAsBitmap) { - // Toggle to re-render with new multisample - this.cacheAsBitmap = false; - this.cacheAsBitmap = true; - } - }, - }, - /** - * Set this to true if you want this display object to be cached as a bitmap. - * This basically takes a snap shot of the display object as it is at that moment. It can - * provide a performance benefit for complex static displayObjects. - * To remove simply set this property to `false` - * - * IMPORTANT GOTCHA - Make sure that all your textures are preloaded BEFORE setting this property to true - * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. - * @member {boolean} - * @memberof PIXI.DisplayObject# - */ - cacheAsBitmap: { - get: function () { - return this._cacheAsBitmap; - }, - set: function (value) { - if (this._cacheAsBitmap === value) { - return; - } - this._cacheAsBitmap = value; - var data; - if (value) { - if (!this._cacheData) { - this._cacheData = new CacheData(); - } - data = this._cacheData; - data.originalRender = this.render; - data.originalRenderCanvas = this.renderCanvas; - data.originalUpdateTransform = this.updateTransform; - data.originalCalculateBounds = this.calculateBounds; - data.originalGetLocalBounds = this.getLocalBounds; - data.originalDestroy = this.destroy; - data.originalContainsPoint = this.containsPoint; - data.originalMask = this._mask; - data.originalFilterArea = this.filterArea; - this.render = this._renderCached; - this.renderCanvas = this._renderCachedCanvas; - this.destroy = this._cacheAsBitmapDestroy; - } - else { - data = this._cacheData; - if (data.sprite) { - this._destroyCachedDisplayObject(); - } - this.render = data.originalRender; - this.renderCanvas = data.originalRenderCanvas; - this.calculateBounds = data.originalCalculateBounds; - this.getLocalBounds = data.originalGetLocalBounds; - this.destroy = data.originalDestroy; - this.updateTransform = data.originalUpdateTransform; - this.containsPoint = data.originalContainsPoint; - this._mask = data.originalMask; - this.filterArea = data.originalFilterArea; - } - }, - }, - }); - /** - * Renders a cached version of the sprite with WebGL - * @private - * @method _renderCached - * @memberof PIXI.DisplayObject# - * @param {PIXI.Renderer} renderer - the WebGL renderer - */ - DisplayObject.prototype._renderCached = function _renderCached(renderer) { - if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { - return; - } - this._initCachedDisplayObject(renderer); - this._cacheData.sprite.transform._worldID = this.transform._worldID; - this._cacheData.sprite.worldAlpha = this.worldAlpha; - this._cacheData.sprite._render(renderer); - }; - /** - * Prepares the WebGL renderer to cache the sprite - * @private - * @method _initCachedDisplayObject - * @memberof PIXI.DisplayObject# - * @param {PIXI.Renderer} renderer - the WebGL renderer - */ - DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { - var _a; - if (this._cacheData && this._cacheData.sprite) { - return; - } - // make sure alpha is set to 1 otherwise it will get rendered as invisible! - var cacheAlpha = this.alpha; - this.alpha = 1; - // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) - renderer.batch.flush(); - // this.filters= []; - // next we find the dimensions of the untransformed object - // this function also calls updatetransform on all its children as part of the measuring. - // This means we don't need to update the transform again in this function - // TODO pass an object to clone too? saves having to create a new one each time! - var bounds = this.getLocalBounds(null, true).clone(); - // add some padding! - if (this.filters && this.filters.length) { - var padding = this.filters[0].padding; - bounds.pad(padding); - } - bounds.ceil(settings.RESOLUTION); - // for now we cache the current renderTarget that the WebGL renderer is currently using. - // this could be more elegant.. - var cachedRenderTexture = renderer.renderTexture.current; - var cachedSourceFrame = renderer.renderTexture.sourceFrame.clone(); - var cachedDestinationFrame = renderer.renderTexture.destinationFrame.clone(); - var cachedProjectionTransform = renderer.projection.transform; - // We also store the filter stack - I will definitely look to change how this works a little later down the line. - // const stack = renderer.filterManager.filterStack; - // this renderTexture will be used to store the cached DisplayObject - var renderTexture = RenderTexture.create({ - width: bounds.width, - height: bounds.height, - resolution: this.cacheAsBitmapResolution || renderer.resolution, - multisample: (_a = this.cacheAsBitmapMultisample) !== null && _a !== void 0 ? _a : renderer.multisample, - }); - var textureCacheId = "cacheAsBitmap_" + uid(); - this._cacheData.textureCacheId = textureCacheId; - BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId); - Texture.addToCache(renderTexture, textureCacheId); - // need to set // - var m = this.transform.localTransform.copyTo(_tempMatrix).invert().translate(-bounds.x, -bounds.y); - // set all properties to there original so we can render to a texture - this.render = this._cacheData.originalRender; - renderer.render(this, { renderTexture: renderTexture, clear: true, transform: m, skipUpdateTransform: false }); - renderer.framebuffer.blit(); - // now restore the state be setting the new properties - renderer.projection.transform = cachedProjectionTransform; - renderer.renderTexture.bind(cachedRenderTexture, cachedSourceFrame, cachedDestinationFrame); - // renderer.filterManager.filterStack = stack; - this.render = this._renderCached; - // the rest is the same as for Canvas - this.updateTransform = this.displayObjectUpdateTransform; - this.calculateBounds = this._calculateCachedBounds; - this.getLocalBounds = this._getCachedLocalBounds; - this._mask = null; - this.filterArea = null; - this.alpha = cacheAlpha; - // create our cached sprite - var cachedSprite = new Sprite(renderTexture); - cachedSprite.transform.worldTransform = this.transform.worldTransform; - cachedSprite.anchor.x = -(bounds.x / bounds.width); - cachedSprite.anchor.y = -(bounds.y / bounds.height); - cachedSprite.alpha = cacheAlpha; - cachedSprite._bounds = this._bounds; - this._cacheData.sprite = cachedSprite; - this.transform._parentID = -1; - // restore the transform of the cached sprite to avoid the nasty flicker.. - if (!this.parent) { - this.enableTempParent(); - this.updateTransform(); - this.disableTempParent(null); - } - else { - this.updateTransform(); - } - // map the hit test.. - this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); - }; - /** - * Renders a cached version of the sprite with canvas - * @private - * @method _renderCachedCanvas - * @memberof PIXI.DisplayObject# - * @param {PIXI.CanvasRenderer} renderer - The canvas renderer - */ - DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { - if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { - return; - } - this._initCachedDisplayObjectCanvas(renderer); - this._cacheData.sprite.worldAlpha = this.worldAlpha; - this._cacheData.sprite._renderCanvas(renderer); - }; - // TODO this can be the same as the WebGL version.. will need to do a little tweaking first though.. - /** - * Prepares the Canvas renderer to cache the sprite - * @private - * @method _initCachedDisplayObjectCanvas - * @memberof PIXI.DisplayObject# - * @param {PIXI.CanvasRenderer} renderer - The canvas renderer - */ - DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { - if (this._cacheData && this._cacheData.sprite) { - return; - } - // get bounds actually transforms the object for us already! - var bounds = this.getLocalBounds(null, true); - var cacheAlpha = this.alpha; - this.alpha = 1; - var cachedRenderTarget = renderer.context; - var cachedProjectionTransform = renderer._projTransform; - bounds.ceil(settings.RESOLUTION); - var renderTexture = RenderTexture.create({ width: bounds.width, height: bounds.height }); - var textureCacheId = "cacheAsBitmap_" + uid(); - this._cacheData.textureCacheId = textureCacheId; - BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId); - Texture.addToCache(renderTexture, textureCacheId); - // need to set // - var m = _tempMatrix; - this.transform.localTransform.copyTo(m); - m.invert(); - m.tx -= bounds.x; - m.ty -= bounds.y; - // m.append(this.transform.worldTransform.) - // set all properties to there original so we can render to a texture - this.renderCanvas = this._cacheData.originalRenderCanvas; - renderer.render(this, { renderTexture: renderTexture, clear: true, transform: m, skipUpdateTransform: false }); - // now restore the state be setting the new properties - renderer.context = cachedRenderTarget; - renderer._projTransform = cachedProjectionTransform; - this.renderCanvas = this._renderCachedCanvas; - // the rest is the same as for WebGL - this.updateTransform = this.displayObjectUpdateTransform; - this.calculateBounds = this._calculateCachedBounds; - this.getLocalBounds = this._getCachedLocalBounds; - this._mask = null; - this.filterArea = null; - this.alpha = cacheAlpha; - // create our cached sprite - var cachedSprite = new Sprite(renderTexture); - cachedSprite.transform.worldTransform = this.transform.worldTransform; - cachedSprite.anchor.x = -(bounds.x / bounds.width); - cachedSprite.anchor.y = -(bounds.y / bounds.height); - cachedSprite.alpha = cacheAlpha; - cachedSprite._bounds = this._bounds; - this._cacheData.sprite = cachedSprite; - this.transform._parentID = -1; - // restore the transform of the cached sprite to avoid the nasty flicker.. - if (!this.parent) { - this.parent = renderer._tempDisplayObjectParent; - this.updateTransform(); - this.parent = null; - } - else { - this.updateTransform(); - } - // map the hit test.. - this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); - }; - /** - * Calculates the bounds of the cached sprite - * @private - * @method - */ - DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { - this._bounds.clear(); - this._cacheData.sprite.transform._worldID = this.transform._worldID; - this._cacheData.sprite._calculateBounds(); - this._bounds.updateID = this._boundsID; - }; - /** - * Gets the bounds of the cached sprite. - * @private - * @method - * @returns {Rectangle} The local bounds. - */ - DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { - return this._cacheData.sprite.getLocalBounds(null); - }; - /** - * Destroys the cached sprite. - * @private - * @method - */ - DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { - this._cacheData.sprite._texture.destroy(true); - this._cacheData.sprite = null; - BaseTexture.removeFromCache(this._cacheData.textureCacheId); - Texture.removeFromCache(this._cacheData.textureCacheId); - this._cacheData.textureCacheId = null; - }; - /** - * Destroys the cached object. - * @private - * @method - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value. - * Used when destroying containers, see the Container.destroy method. - */ - DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) { - this.cacheAsBitmap = false; - this.destroy(options); - }; - - /*! - * @pixi/mixin-get-child-by-name - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/mixin-get-child-by-name is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * The instance name of the object. - * @memberof PIXI.DisplayObject# - * @member {string} name - */ - DisplayObject.prototype.name = null; - /** - * Returns the display object in the container. - * - * Recursive searches are done in a preorder traversal. - * @method getChildByName - * @memberof PIXI.Container# - * @param {string} name - Instance name. - * @param {boolean}[deep=false] - Whether to search recursively - * @returns {PIXI.DisplayObject} The child with the specified name. - */ - Container.prototype.getChildByName = function getChildByName(name, deep) { - for (var i = 0, j = this.children.length; i < j; i++) { - if (this.children[i].name === name) { - return this.children[i]; - } - } - if (deep) { - for (var i = 0, j = this.children.length; i < j; i++) { - var child = this.children[i]; - if (!child.getChildByName) { - continue; - } - var target = child.getChildByName(name, true); - if (target) { - return target; - } - } - } - return null; - }; - - /*! - * @pixi/mixin-get-global-position - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/mixin-get-global-position is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. - * @method getGlobalPosition - * @memberof PIXI.DisplayObject# - * @param {PIXI.Point} [point=new PIXI.Point()] - The point to write the global value to. - * @param {boolean} [skipUpdate=false] - Setting to true will stop the transforms of the scene graph from - * being updated. This means the calculation returned MAY be out of date BUT will give you a - * nice performance boost. - * @returns {PIXI.Point} The updated point. - */ - DisplayObject.prototype.getGlobalPosition = function getGlobalPosition(point, skipUpdate) { - if (point === void 0) { point = new Point(); } - if (skipUpdate === void 0) { skipUpdate = false; } - if (this.parent) { - this.parent.toGlobal(this.position, point, skipUpdate); - } - else { - point.x = this.position.x; - point.y = this.position.y; - } - return point; - }; - - /*! - * @pixi/app - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/app is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Middleware for for Application's resize functionality - * @private - * @class - */ - var ResizePlugin = /** @class */ (function () { - function ResizePlugin() { - } - /** - * Initialize the plugin with scope of application instance - * @static - * @private - * @param {object} [options] - See application options - */ - ResizePlugin.init = function (options) { - var _this = this; - Object.defineProperty(this, 'resizeTo', - /** - * The HTML element or window to automatically resize the - * renderer's view element to match width and height. - * @member {Window|HTMLElement} - * @name resizeTo - * @memberof PIXI.Application# - */ - { - set: function (dom) { - globalThis.removeEventListener('resize', this.queueResize); - this._resizeTo = dom; - if (dom) { - globalThis.addEventListener('resize', this.queueResize); - this.resize(); - } - }, - get: function () { - return this._resizeTo; - }, - }); - /** - * Resize is throttled, so it's safe to call this multiple times per frame and it'll - * only be called once. - * @memberof PIXI.Application# - * @method queueResize - * @private - */ - this.queueResize = function () { - if (!_this._resizeTo) { - return; - } - _this.cancelResize(); - // // Throttle resize events per raf - _this._resizeId = requestAnimationFrame(function () { return _this.resize(); }); - }; - /** - * Cancel the resize queue. - * @memberof PIXI.Application# - * @method cancelResize - * @private - */ - this.cancelResize = function () { - if (_this._resizeId) { - cancelAnimationFrame(_this._resizeId); - _this._resizeId = null; - } - }; - /** - * Execute an immediate resize on the renderer, this is not - * throttled and can be expensive to call many times in a row. - * Will resize only if `resizeTo` property is set. - * @memberof PIXI.Application# - * @method resize - */ - this.resize = function () { - if (!_this._resizeTo) { - return; - } - // clear queue resize - _this.cancelResize(); - var width; - var height; - // Resize to the window - if (_this._resizeTo === globalThis.window) { - width = globalThis.innerWidth; - height = globalThis.innerHeight; - } - // Resize to other HTML entities - else { - var _a = _this._resizeTo, clientWidth = _a.clientWidth, clientHeight = _a.clientHeight; - width = clientWidth; - height = clientHeight; - } - _this.renderer.resize(width, height); - }; - // On resize - this._resizeId = null; - this._resizeTo = null; - this.resizeTo = options.resizeTo || null; - }; - /** - * Clean up the ticker, scoped to application - * @static - * @private - */ - ResizePlugin.destroy = function () { - globalThis.removeEventListener('resize', this.queueResize); - this.cancelResize(); - this.cancelResize = null; - this.queueResize = null; - this.resizeTo = null; - this.resize = null; - }; - /** @ignore */ - ResizePlugin.extension = exports.ExtensionType.Application; - return ResizePlugin; - }()); - - /** - * Convenience class to create a new PIXI application. - * - * This class automatically creates the renderer, ticker and root container. - * @example - * // Create the application - * const app = new PIXI.Application(); - * - * // Add the view to the DOM - * document.body.appendChild(app.view); - * - * // ex, add display objects - * app.stage.addChild(PIXI.Sprite.from('something.png')); - * @class - * @memberof PIXI - */ - var Application = /** @class */ (function () { - /** - * @param {PIXI.IApplicationOptions} [options] - The optional application and renderer parameters. - * @param {boolean} [options.antialias=false] - - * **WebGL Only.** Whether to enable anti-aliasing. This may affect performance. - * @param {boolean} [options.autoDensity=false] - - * Whether the CSS dimensions of the renderer's view should be resized automatically. - * @param {boolean} [options.autoStart=true] - Automatically starts the rendering after the construction. - * **Note**: Setting this parameter to false does NOT stop the shared ticker even if you set - * `options.sharedTicker` to `true` in case that it is already started. Stop it by your own. - * @param {number} [options.backgroundAlpha=1] - - * Transparency of the background color, value from `0` (fully transparent) to `1` (fully opaque). - * @param {number} [options.backgroundColor=0x000000] - - * The background color used to clear the canvas. It accepts hex numbers (e.g. `0xff0000`). - * @param {boolean} [options.clearBeforeRender=true] - Whether to clear the canvas before new render passes. - * @param {PIXI.IRenderingContext} [options.context] - **WebGL Only.** User-provided WebGL rendering context object. - * @param {boolean} [options.forceCanvas=false] - - * Force using {@link PIXI.CanvasRenderer}, even if WebGL is available. This option only is available when - * using **pixi.js-legacy** or **@pixi/canvas-renderer** packages, otherwise it is ignored. - * @param {number} [options.height=600] - The height of the renderer's view. - * @param {string} [options.powerPreference] - - * **WebGL Only.** A hint indicating what configuration of GPU is suitable for the WebGL context, - * can be `'default'`, `'high-performance'` or `'low-power'`. - * Setting to `'high-performance'` will prioritize rendering performance over power consumption, - * while setting to `'low-power'` will prioritize power saving over rendering performance. - * @param {boolean} [options.premultipliedAlpha=true] - - * **WebGL Only.** Whether the compositor will assume the drawing buffer contains colors with premultiplied alpha. - * @param {boolean} [options.preserveDrawingBuffer=false] - - * **WebGL Only.** Whether to enable drawing buffer preservation. If enabled, the drawing buffer will preserve - * its value until cleared or overwritten. Enable this if you need to call `toDataUrl` on the WebGL context. - * @param {Window|HTMLElement} [options.resizeTo] - Element to automatically resize stage to. - * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - - * The resolution / device pixel ratio of the renderer. - * @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.Loader.shared, `false` to create new Loader. - * @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.Ticker.shared, `false` to create new ticker. - * If set to `false`, you cannot register a handler to occur before anything that runs on the shared ticker. - * The system ticker will always run before both the shared ticker and the app ticker. - * @param {boolean} [options.transparent] - - * **Deprecated since 6.0.0, Use `backgroundAlpha` instead.** \ - * `true` sets `backgroundAlpha` to `0`, `false` sets `backgroundAlpha` to `1`. - * @param {boolean|'notMultiplied'} [options.useContextAlpha=true] - - * Pass-through value for canvas' context attribute `alpha`. This option is for cases where the - * canvas needs to be opaque, possibly for performance reasons on some older devices. - * If you want to set transparency, please use `backgroundAlpha`. \ - * **WebGL Only:** When set to `'notMultiplied'`, the canvas' context attribute `alpha` will be - * set to `true` and `premultipliedAlpha` will be to `false`. - * @param {HTMLCanvasElement} [options.view=null] - - * The canvas to use as the view. If omitted, a new canvas will be created. - * @param {number} [options.width=800] - The width of the renderer's view. - */ - function Application(options) { - var _this = this; - /** - * The root display container that's rendered. - * @member {PIXI.Container} - */ - this.stage = new Container(); - // The default options - options = Object.assign({ - forceCanvas: false, - }, options); - this.renderer = autoDetectRenderer(options); - // install plugins here - Application._plugins.forEach(function (plugin) { - plugin.init.call(_this, options); - }); - } - /** - * Use the {@link PIXI.extensions.add} API to register plugins. - * @deprecated since 6.5.0 - * @static - * @param {PIXI.IApplicationPlugin} plugin - Plugin being installed - */ - Application.registerPlugin = function (plugin) { - deprecation('6.5.0', 'Application.registerPlugin() is deprecated, use extensions.add()'); - extensions.add({ - type: exports.ExtensionType.Application, - ref: plugin, - }); - }; - /** Render the current stage. */ - Application.prototype.render = function () { - this.renderer.render(this.stage); - }; - Object.defineProperty(Application.prototype, "view", { - /** - * Reference to the renderer's canvas element. - * @member {HTMLCanvasElement} - * @readonly - */ - get: function () { - return this.renderer.view; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Application.prototype, "screen", { - /** - * Reference to the renderer's screen rectangle. Its safe to use as `filterArea` or `hitArea` for the whole screen. - * @member {PIXI.Rectangle} - * @readonly - */ - get: function () { - return this.renderer.screen; - }, - enumerable: false, - configurable: true - }); - /** - * Destroy and don't use after this. - * @param {boolean} [removeView=false] - Automatically remove canvas from DOM. - * @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy - * method called as well. 'stageOptions' will be passed on to those calls. - * @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set - * to true. Should it destroy the texture of the child sprite - * @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set - * to true. Should it destroy the base texture of the child sprite - */ - Application.prototype.destroy = function (removeView, stageOptions) { - var _this = this; - // Destroy plugins in the opposite order - // which they were constructed - var plugins = Application._plugins.slice(0); - plugins.reverse(); - plugins.forEach(function (plugin) { - plugin.destroy.call(_this); - }); - this.stage.destroy(stageOptions); - this.stage = null; - this.renderer.destroy(removeView); - this.renderer = null; - }; - /** Collection of installed plugins. */ - Application._plugins = []; - return Application; - }()); - extensions.handleByList(exports.ExtensionType.Application, Application._plugins); - - extensions.add(ResizePlugin); - - /*! - * @pixi/mesh-extras - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/mesh-extras is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$1 = function(d, b) { - extendStatics$1 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$1(d, b); - }; - - function __extends$1(d, b) { - extendStatics$1(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** - * @memberof PIXI - */ - var PlaneGeometry = /** @class */ (function (_super) { - __extends$1(PlaneGeometry, _super); - /** - * @param width - The width of the plane. - * @param height - The height of the plane. - * @param segWidth - Number of horizontal segments. - * @param segHeight - Number of vertical segments. - */ - function PlaneGeometry(width, height, segWidth, segHeight) { - if (width === void 0) { width = 100; } - if (height === void 0) { height = 100; } - if (segWidth === void 0) { segWidth = 10; } - if (segHeight === void 0) { segHeight = 10; } - var _this = _super.call(this) || this; - _this.segWidth = segWidth; - _this.segHeight = segHeight; - _this.width = width; - _this.height = height; - _this.build(); - return _this; - } - /** - * Refreshes plane coordinates - * @private - */ - PlaneGeometry.prototype.build = function () { - var total = this.segWidth * this.segHeight; - var verts = []; - var uvs = []; - var indices = []; - var segmentsX = this.segWidth - 1; - var segmentsY = this.segHeight - 1; - var sizeX = (this.width) / segmentsX; - var sizeY = (this.height) / segmentsY; - for (var i = 0; i < total; i++) { - var x = (i % this.segWidth); - var y = ((i / this.segWidth) | 0); - verts.push(x * sizeX, y * sizeY); - uvs.push(x / segmentsX, y / segmentsY); - } - var totalSub = segmentsX * segmentsY; - for (var i = 0; i < totalSub; i++) { - var xpos = i % segmentsX; - var ypos = (i / segmentsX) | 0; - var value = (ypos * this.segWidth) + xpos; - var value2 = (ypos * this.segWidth) + xpos + 1; - var value3 = ((ypos + 1) * this.segWidth) + xpos; - var value4 = ((ypos + 1) * this.segWidth) + xpos + 1; - indices.push(value, value2, value3, value2, value4, value3); - } - this.buffers[0].data = new Float32Array(verts); - this.buffers[1].data = new Float32Array(uvs); - this.indexBuffer.data = new Uint16Array(indices); - // ensure that the changes are uploaded - this.buffers[0].update(); - this.buffers[1].update(); - this.indexBuffer.update(); - }; - return PlaneGeometry; - }(MeshGeometry)); - - /** - * RopeGeometry allows you to draw a geometry across several points and then manipulate these points. - * - * ```js - * for (let i = 0; i < 20; i++) { - * points.push(new PIXI.Point(i * 50, 0)); - * }; - * const rope = new PIXI.RopeGeometry(100, points); - * ``` - * @memberof PIXI - */ - var RopeGeometry = /** @class */ (function (_super) { - __extends$1(RopeGeometry, _super); - /** - * @param width - The width (i.e., thickness) of the rope. - * @param points - An array of {@link PIXI.Point} objects to construct this rope. - * @param textureScale - By default the rope texture will be stretched to match - * rope length. If textureScale is positive this value will be treated as a scaling - * factor and the texture will preserve its aspect ratio instead. To create a tiling rope - * set baseTexture.wrapMode to {@link PIXI.WRAP_MODES.REPEAT} and use a power of two texture, - * then set textureScale=1 to keep the original texture pixel size. - * In order to reduce alpha channel artifacts provide a larger texture and downsample - - * i.e. set textureScale=0.5 to scale it down twice. - */ - function RopeGeometry(width, points, textureScale) { - if (width === void 0) { width = 200; } - if (textureScale === void 0) { textureScale = 0; } - var _this = _super.call(this, new Float32Array(points.length * 4), new Float32Array(points.length * 4), new Uint16Array((points.length - 1) * 6)) || this; - _this.points = points; - _this._width = width; - _this.textureScale = textureScale; - _this.build(); - return _this; - } - Object.defineProperty(RopeGeometry.prototype, "width", { - /** - * The width (i.e., thickness) of the rope. - * @readonly - */ - get: function () { - return this._width; - }, - enumerable: false, - configurable: true - }); - /** Refreshes Rope indices and uvs */ - RopeGeometry.prototype.build = function () { - var points = this.points; - if (!points) - { return; } - var vertexBuffer = this.getBuffer('aVertexPosition'); - var uvBuffer = this.getBuffer('aTextureCoord'); - var indexBuffer = this.getIndex(); - // if too little points, or texture hasn't got UVs set yet just move on. - if (points.length < 1) { - return; - } - // if the number of points has changed we will need to recreate the arraybuffers - if (vertexBuffer.data.length / 4 !== points.length) { - vertexBuffer.data = new Float32Array(points.length * 4); - uvBuffer.data = new Float32Array(points.length * 4); - indexBuffer.data = new Uint16Array((points.length - 1) * 6); - } - var uvs = uvBuffer.data; - var indices = indexBuffer.data; - uvs[0] = 0; - uvs[1] = 0; - uvs[2] = 0; - uvs[3] = 1; - var amount = 0; - var prev = points[0]; - var textureWidth = this._width * this.textureScale; - var total = points.length; // - 1; - for (var i = 0; i < total; i++) { - // time to do some smart drawing! - var index = i * 4; - if (this.textureScale > 0) { - // calculate pixel distance from previous point - var dx = prev.x - points[i].x; - var dy = prev.y - points[i].y; - var distance = Math.sqrt((dx * dx) + (dy * dy)); - prev = points[i]; - amount += distance / textureWidth; - } - else { - // stretch texture - amount = i / (total - 1); - } - uvs[index] = amount; - uvs[index + 1] = 0; - uvs[index + 2] = amount; - uvs[index + 3] = 1; - } - var indexCount = 0; - for (var i = 0; i < total - 1; i++) { - var index = i * 2; - indices[indexCount++] = index; - indices[indexCount++] = index + 1; - indices[indexCount++] = index + 2; - indices[indexCount++] = index + 2; - indices[indexCount++] = index + 1; - indices[indexCount++] = index + 3; - } - // ensure that the changes are uploaded - uvBuffer.update(); - indexBuffer.update(); - this.updateVertices(); - }; - /** refreshes vertices of Rope mesh */ - RopeGeometry.prototype.updateVertices = function () { - var points = this.points; - if (points.length < 1) { - return; - } - var lastPoint = points[0]; - var nextPoint; - var perpX = 0; - var perpY = 0; - var vertices = this.buffers[0].data; - var total = points.length; - for (var i = 0; i < total; i++) { - var point = points[i]; - var index = i * 4; - if (i < points.length - 1) { - nextPoint = points[i + 1]; - } - else { - nextPoint = point; - } - perpY = -(nextPoint.x - lastPoint.x); - perpX = nextPoint.y - lastPoint.y; - var perpLength = Math.sqrt((perpX * perpX) + (perpY * perpY)); - var num = this.textureScale > 0 ? this.textureScale * this._width / 2 : this._width / 2; - perpX /= perpLength; - perpY /= perpLength; - perpX *= num; - perpY *= num; - vertices[index] = point.x + perpX; - vertices[index + 1] = point.y + perpY; - vertices[index + 2] = point.x - perpX; - vertices[index + 3] = point.y - perpY; - lastPoint = point; - } - this.buffers[0].update(); - }; - RopeGeometry.prototype.update = function () { - if (this.textureScale > 0) { - this.build(); // we need to update UVs - } - else { - this.updateVertices(); - } - }; - return RopeGeometry; - }(MeshGeometry)); - - /** - * The rope allows you to draw a texture across several points and then manipulate these points - * - *```js - * for (let i = 0; i < 20; i++) { - * points.push(new PIXI.Point(i * 50, 0)); - * }; - * let rope = new PIXI.SimpleRope(PIXI.Texture.from("snake.png"), points); - * ``` - * @memberof PIXI - */ - var SimpleRope = /** @class */ (function (_super) { - __extends$1(SimpleRope, _super); - /** - * @param texture - The texture to use on the rope. - * @param points - An array of {@link PIXI.Point} objects to construct this rope. - * @param {number} textureScale - Optional. Positive values scale rope texture - * keeping its aspect ratio. You can reduce alpha channel artifacts by providing a larger texture - * and downsampling here. If set to zero, texture will be stretched instead. - */ - function SimpleRope(texture, points, textureScale) { - if (textureScale === void 0) { textureScale = 0; } - var _this = this; - var ropeGeometry = new RopeGeometry(texture.height, points, textureScale); - var meshMaterial = new MeshMaterial(texture); - if (textureScale > 0) { - // attempt to set UV wrapping, will fail on non-power of two textures - texture.baseTexture.wrapMode = exports.WRAP_MODES.REPEAT; - } - _this = _super.call(this, ropeGeometry, meshMaterial) || this; - /** - * re-calculate vertices by rope points each frame - * @member {boolean} - */ - _this.autoUpdate = true; - return _this; - } - SimpleRope.prototype._render = function (renderer) { - var geometry = this.geometry; - if (this.autoUpdate || geometry._width !== this.shader.texture.height) { - geometry._width = this.shader.texture.height; - geometry.update(); - } - _super.prototype._render.call(this, renderer); - }; - return SimpleRope; - }(Mesh)); - - /** - * The SimplePlane allows you to draw a texture across several points and then manipulate these points - * - *```js - * for (let i = 0; i < 20; i++) { - * points.push(new PIXI.Point(i * 50, 0)); - * }; - * let SimplePlane = new PIXI.SimplePlane(PIXI.Texture.from("snake.png"), points); - * ``` - * @memberof PIXI - */ - var SimplePlane = /** @class */ (function (_super) { - __extends$1(SimplePlane, _super); - /** - * @param texture - The texture to use on the SimplePlane. - * @param verticesX - The number of vertices in the x-axis - * @param verticesY - The number of vertices in the y-axis - */ - function SimplePlane(texture, verticesX, verticesY) { - var _this = this; - var planeGeometry = new PlaneGeometry(texture.width, texture.height, verticesX, verticesY); - var meshMaterial = new MeshMaterial(Texture.WHITE); - _this = _super.call(this, planeGeometry, meshMaterial) || this; - // lets call the setter to ensure all necessary updates are performed - _this.texture = texture; - _this.autoResize = true; - return _this; - } - /** - * Method used for overrides, to do something in case texture frame was changed. - * Meshes based on plane can override it and change more details based on texture. - */ - SimplePlane.prototype.textureUpdated = function () { - this._textureID = this.shader.texture._updateID; - var geometry = this.geometry; - var _a = this.shader.texture, width = _a.width, height = _a.height; - if (this.autoResize && (geometry.width !== width || geometry.height !== height)) { - geometry.width = this.shader.texture.width; - geometry.height = this.shader.texture.height; - geometry.build(); - } - }; - Object.defineProperty(SimplePlane.prototype, "texture", { - get: function () { - return this.shader.texture; - }, - set: function (value) { - // Track texture same way sprite does. - // For generated meshes like NineSlicePlane it can change the geometry. - // Unfortunately, this method might not work if you directly change texture in material. - if (this.shader.texture === value) { - return; - } - this.shader.texture = value; - this._textureID = -1; - if (value.baseTexture.valid) { - this.textureUpdated(); - } - else { - value.once('update', this.textureUpdated, this); - } - }, - enumerable: false, - configurable: true - }); - SimplePlane.prototype._render = function (renderer) { - if (this._textureID !== this.shader.texture._updateID) { - this.textureUpdated(); - } - _super.prototype._render.call(this, renderer); - }; - SimplePlane.prototype.destroy = function (options) { - this.shader.texture.off('update', this.textureUpdated, this); - _super.prototype.destroy.call(this, options); - }; - return SimplePlane; - }(Mesh)); - - /** - * The Simple Mesh class mimics Mesh in PixiJS v4, providing easy-to-use constructor arguments. - * For more robust customization, use {@link PIXI.Mesh}. - * @memberof PIXI - */ - var SimpleMesh = /** @class */ (function (_super) { - __extends$1(SimpleMesh, _super); - /** - * @param texture - The texture to use - * @param {Float32Array} [vertices] - if you want to specify the vertices - * @param {Float32Array} [uvs] - if you want to specify the uvs - * @param {Uint16Array} [indices] - if you want to specify the indices - * @param drawMode - the drawMode, can be any of the Mesh.DRAW_MODES consts - */ - function SimpleMesh(texture, vertices, uvs, indices, drawMode) { - if (texture === void 0) { texture = Texture.EMPTY; } - var _this = this; - var geometry = new MeshGeometry(vertices, uvs, indices); - geometry.getBuffer('aVertexPosition').static = false; - var meshMaterial = new MeshMaterial(texture); - _this = _super.call(this, geometry, meshMaterial, null, drawMode) || this; - _this.autoUpdate = true; - return _this; - } - Object.defineProperty(SimpleMesh.prototype, "vertices", { - /** - * Collection of vertices data. - * @type {Float32Array} - */ - get: function () { - return this.geometry.getBuffer('aVertexPosition').data; - }, - set: function (value) { - this.geometry.getBuffer('aVertexPosition').data = value; - }, - enumerable: false, - configurable: true - }); - SimpleMesh.prototype._render = function (renderer) { - if (this.autoUpdate) { - this.geometry.getBuffer('aVertexPosition').update(); - } - _super.prototype._render.call(this, renderer); - }; - return SimpleMesh; - }(Mesh)); - - var DEFAULT_BORDER_SIZE = 10; - /** - * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful - * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically - * - *```js - * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.from('BoxWithRoundedCorners.png'), 15, 15, 15, 15); - * ``` - *
-   *      A                          B
-   *    +---+----------------------+---+
-   *  C | 1 |          2           | 3 |
-   *    +---+----------------------+---+
-   *    |   |                      |   |
-   *    | 4 |          5           | 6 |
-   *    |   |                      |   |
-   *    +---+----------------------+---+
-   *  D | 7 |          8           | 9 |
-   *    +---+----------------------+---+
-   *  When changing this objects width and/or height:
-   *     areas 1 3 7 and 9 will remain unscaled.
-   *     areas 2 and 8 will be stretched horizontally
-   *     areas 4 and 6 will be stretched vertically
-   *     area 5 will be stretched both horizontally and vertically
-   * 
- * @memberof PIXI - */ - var NineSlicePlane = /** @class */ (function (_super) { - __extends$1(NineSlicePlane, _super); - /** - * @param texture - The texture to use on the NineSlicePlane. - * @param {number} [leftWidth=10] - size of the left vertical bar (A) - * @param {number} [topHeight=10] - size of the top horizontal bar (C) - * @param {number} [rightWidth=10] - size of the right vertical bar (B) - * @param {number} [bottomHeight=10] - size of the bottom horizontal bar (D) - */ - function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { - if (leftWidth === void 0) { leftWidth = DEFAULT_BORDER_SIZE; } - if (topHeight === void 0) { topHeight = DEFAULT_BORDER_SIZE; } - if (rightWidth === void 0) { rightWidth = DEFAULT_BORDER_SIZE; } - if (bottomHeight === void 0) { bottomHeight = DEFAULT_BORDER_SIZE; } - var _this = _super.call(this, Texture.WHITE, 4, 4) || this; - _this._origWidth = texture.orig.width; - _this._origHeight = texture.orig.height; - /** The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */ - _this._width = _this._origWidth; - /** The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */ - _this._height = _this._origHeight; - _this._leftWidth = leftWidth; - _this._rightWidth = rightWidth; - _this._topHeight = topHeight; - _this._bottomHeight = bottomHeight; - // lets call the setter to ensure all necessary updates are performed - _this.texture = texture; - return _this; - } - NineSlicePlane.prototype.textureUpdated = function () { - this._textureID = this.shader.texture._updateID; - this._refresh(); - }; - Object.defineProperty(NineSlicePlane.prototype, "vertices", { - get: function () { - return this.geometry.getBuffer('aVertexPosition').data; - }, - set: function (value) { - this.geometry.getBuffer('aVertexPosition').data = value; - }, - enumerable: false, - configurable: true - }); - /** Updates the horizontal vertices. */ - NineSlicePlane.prototype.updateHorizontalVertices = function () { - var vertices = this.vertices; - var scale = this._getMinScale(); - vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight * scale; - vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - (this._bottomHeight * scale); - vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; - }; - /** Updates the vertical vertices. */ - NineSlicePlane.prototype.updateVerticalVertices = function () { - var vertices = this.vertices; - var scale = this._getMinScale(); - vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth * scale; - vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - (this._rightWidth * scale); - vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; - }; - /** - * Returns the smaller of a set of vertical and horizontal scale of nine slice corners. - * @returns Smaller number of vertical and horizontal scale. - */ - NineSlicePlane.prototype._getMinScale = function () { - var w = this._leftWidth + this._rightWidth; - var scaleW = this._width > w ? 1.0 : this._width / w; - var h = this._topHeight + this._bottomHeight; - var scaleH = this._height > h ? 1.0 : this._height / h; - var scale = Math.min(scaleW, scaleH); - return scale; - }; - Object.defineProperty(NineSlicePlane.prototype, "width", { - /** The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */ - get: function () { - return this._width; - }, - set: function (value) { - this._width = value; - this._refresh(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(NineSlicePlane.prototype, "height", { - /** The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */ - get: function () { - return this._height; - }, - set: function (value) { - this._height = value; - this._refresh(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(NineSlicePlane.prototype, "leftWidth", { - /** The width of the left column. */ - get: function () { - return this._leftWidth; - }, - set: function (value) { - this._leftWidth = value; - this._refresh(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(NineSlicePlane.prototype, "rightWidth", { - /** The width of the right column. */ - get: function () { - return this._rightWidth; - }, - set: function (value) { - this._rightWidth = value; - this._refresh(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(NineSlicePlane.prototype, "topHeight", { - /** The height of the top row. */ - get: function () { - return this._topHeight; - }, - set: function (value) { - this._topHeight = value; - this._refresh(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(NineSlicePlane.prototype, "bottomHeight", { - /** The height of the bottom row. */ - get: function () { - return this._bottomHeight; - }, - set: function (value) { - this._bottomHeight = value; - this._refresh(); - }, - enumerable: false, - configurable: true - }); - /** Refreshes NineSlicePlane coords. All of them. */ - NineSlicePlane.prototype._refresh = function () { - var texture = this.texture; - var uvs = this.geometry.buffers[1].data; - this._origWidth = texture.orig.width; - this._origHeight = texture.orig.height; - var _uvw = 1.0 / this._origWidth; - var _uvh = 1.0 / this._origHeight; - uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0; - uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0; - uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; - uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; - uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth; - uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - (_uvw * this._rightWidth); - uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight; - uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - (_uvh * this._bottomHeight); - this.updateHorizontalVertices(); - this.updateVerticalVertices(); - this.geometry.buffers[0].update(); - this.geometry.buffers[1].update(); - }; - return NineSlicePlane; - }(SimplePlane)); - - /*! - * @pixi/sprite-animated - v6.5.10 - * Compiled Thu, 06 Jul 2023 15:25:11 UTC - * - * @pixi/sprite-animated is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics(d, b); - }; - - function __extends(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** - * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. - * - * ```js - * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; - * let textureArray = []; - * - * for (let i=0; i < 4; i++) - * { - * let texture = PIXI.Texture.from(alienImages[i]); - * textureArray.push(texture); - * }; - * - * let animatedSprite = new PIXI.AnimatedSprite(textureArray); - * ``` - * - * The more efficient and simpler way to create an animated sprite is using a {@link PIXI.Spritesheet} - * containing the animation definitions: - * - * ```js - * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup); - * - * function setup() { - * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet; - * animatedSprite = new PIXI.AnimatedSprite(sheet.animations["image_sequence"]); - * ... - * } - * ``` - * @memberof PIXI - */ - var AnimatedSprite = /** @class */ (function (_super) { - __extends(AnimatedSprite, _super); - /** - * @param textures - An array of {@link PIXI.Texture} or frame - * objects that make up the animation. - * @param {boolean} [autoUpdate=true] - Whether to use PIXI.Ticker.shared to auto update animation time. - */ - function AnimatedSprite(textures, autoUpdate) { - if (autoUpdate === void 0) { autoUpdate = true; } - var _this = _super.call(this, textures[0] instanceof Texture ? textures[0] : textures[0].texture) || this; - _this._textures = null; - _this._durations = null; - _this._autoUpdate = autoUpdate; - _this._isConnectedToTicker = false; - _this.animationSpeed = 1; - _this.loop = true; - _this.updateAnchor = false; - _this.onComplete = null; - _this.onFrameChange = null; - _this.onLoop = null; - _this._currentTime = 0; - _this._playing = false; - _this._previousFrame = null; - _this.textures = textures; - return _this; - } - /** Stops the AnimatedSprite. */ - AnimatedSprite.prototype.stop = function () { - if (!this._playing) { - return; - } - this._playing = false; - if (this._autoUpdate && this._isConnectedToTicker) { - Ticker.shared.remove(this.update, this); - this._isConnectedToTicker = false; - } - }; - /** Plays the AnimatedSprite. */ - AnimatedSprite.prototype.play = function () { - if (this._playing) { - return; - } - this._playing = true; - if (this._autoUpdate && !this._isConnectedToTicker) { - Ticker.shared.add(this.update, this, exports.UPDATE_PRIORITY.HIGH); - this._isConnectedToTicker = true; - } - }; - /** - * Stops the AnimatedSprite and goes to a specific frame. - * @param frameNumber - Frame index to stop at. - */ - AnimatedSprite.prototype.gotoAndStop = function (frameNumber) { - this.stop(); - var previousFrame = this.currentFrame; - this._currentTime = frameNumber; - if (previousFrame !== this.currentFrame) { - this.updateTexture(); - } - }; - /** - * Goes to a specific frame and begins playing the AnimatedSprite. - * @param frameNumber - Frame index to start at. - */ - AnimatedSprite.prototype.gotoAndPlay = function (frameNumber) { - var previousFrame = this.currentFrame; - this._currentTime = frameNumber; - if (previousFrame !== this.currentFrame) { - this.updateTexture(); - } - this.play(); - }; - /** - * Updates the object transform for rendering. - * @param deltaTime - Time since last tick. - */ - AnimatedSprite.prototype.update = function (deltaTime) { - if (!this._playing) { - return; - } - var elapsed = this.animationSpeed * deltaTime; - var previousFrame = this.currentFrame; - if (this._durations !== null) { - var lag = this._currentTime % 1 * this._durations[this.currentFrame]; - lag += elapsed / 60 * 1000; - while (lag < 0) { - this._currentTime--; - lag += this._durations[this.currentFrame]; - } - var sign = Math.sign(this.animationSpeed * deltaTime); - this._currentTime = Math.floor(this._currentTime); - while (lag >= this._durations[this.currentFrame]) { - lag -= this._durations[this.currentFrame] * sign; - this._currentTime += sign; - } - this._currentTime += lag / this._durations[this.currentFrame]; - } - else { - this._currentTime += elapsed; - } - if (this._currentTime < 0 && !this.loop) { - this.gotoAndStop(0); - if (this.onComplete) { - this.onComplete(); - } - } - else if (this._currentTime >= this._textures.length && !this.loop) { - this.gotoAndStop(this._textures.length - 1); - if (this.onComplete) { - this.onComplete(); - } - } - else if (previousFrame !== this.currentFrame) { - if (this.loop && this.onLoop) { - if (this.animationSpeed > 0 && this.currentFrame < previousFrame) { - this.onLoop(); - } - else if (this.animationSpeed < 0 && this.currentFrame > previousFrame) { - this.onLoop(); - } - } - this.updateTexture(); - } - }; - /** Updates the displayed texture to match the current frame index. */ - AnimatedSprite.prototype.updateTexture = function () { - var currentFrame = this.currentFrame; - if (this._previousFrame === currentFrame) { - return; - } - this._previousFrame = currentFrame; - this._texture = this._textures[currentFrame]; - this._textureID = -1; - this._textureTrimmedID = -1; - this._cachedTint = 0xFFFFFF; - this.uvs = this._texture._uvs.uvsFloat32; - if (this.updateAnchor) { - this._anchor.copyFrom(this._texture.defaultAnchor); - } - if (this.onFrameChange) { - this.onFrameChange(this.currentFrame); - } - }; - /** - * Stops the AnimatedSprite and destroys it. - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value. - * @param {boolean} [options.children=false] - If set to true, all the children will have their destroy - * method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well. - * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well. - */ - AnimatedSprite.prototype.destroy = function (options) { - this.stop(); - _super.prototype.destroy.call(this, options); - this.onComplete = null; - this.onFrameChange = null; - this.onLoop = null; - }; - /** - * A short hand way of creating an AnimatedSprite from an array of frame ids. - * @param frames - The array of frames ids the AnimatedSprite will use as its texture frames. - * @returns - The new animated sprite with the specified frames. - */ - AnimatedSprite.fromFrames = function (frames) { - var textures = []; - for (var i = 0; i < frames.length; ++i) { - textures.push(Texture.from(frames[i])); - } - return new AnimatedSprite(textures); - }; - /** - * A short hand way of creating an AnimatedSprite from an array of image ids. - * @param images - The array of image urls the AnimatedSprite will use as its texture frames. - * @returns The new animate sprite with the specified images as frames. - */ - AnimatedSprite.fromImages = function (images) { - var textures = []; - for (var i = 0; i < images.length; ++i) { - textures.push(Texture.from(images[i])); - } - return new AnimatedSprite(textures); - }; - Object.defineProperty(AnimatedSprite.prototype, "totalFrames", { - /** - * The total number of frames in the AnimatedSprite. This is the same as number of textures - * assigned to the AnimatedSprite. - * @readonly - * @default 0 - */ - get: function () { - return this._textures.length; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AnimatedSprite.prototype, "textures", { - /** The array of textures used for this AnimatedSprite. */ - get: function () { - return this._textures; - }, - set: function (value) { - if (value[0] instanceof Texture) { - this._textures = value; - this._durations = null; - } - else { - this._textures = []; - this._durations = []; - for (var i = 0; i < value.length; i++) { - this._textures.push(value[i].texture); - this._durations.push(value[i].time); - } - } - this._previousFrame = null; - this.gotoAndStop(0); - this.updateTexture(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AnimatedSprite.prototype, "currentFrame", { - /** - * The AnimatedSprites current frame index. - * @readonly - */ - get: function () { - var currentFrame = Math.floor(this._currentTime) % this._textures.length; - if (currentFrame < 0) { - currentFrame += this._textures.length; - } - return currentFrame; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AnimatedSprite.prototype, "playing", { - /** - * Indicates if the AnimatedSprite is currently playing. - * @readonly - */ - get: function () { - return this._playing; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AnimatedSprite.prototype, "autoUpdate", { - /** Whether to use PIXI.Ticker.shared to auto update animation time. */ - get: function () { - return this._autoUpdate; - }, - set: function (value) { - if (value !== this._autoUpdate) { - this._autoUpdate = value; - if (!this._autoUpdate && this._isConnectedToTicker) { - Ticker.shared.remove(this.update, this); - this._isConnectedToTicker = false; - } - else if (this._autoUpdate && !this._isConnectedToTicker && this._playing) { - Ticker.shared.add(this.update, this); - this._isConnectedToTicker = true; - } - } - }, - enumerable: false, - configurable: true - }); - return AnimatedSprite; - }(Sprite)); - - extensions.add( - // Install renderer plugins - AccessibilityManager, Extract, InteractionManager, ParticleRenderer, Prepare, BatchRenderer, TilingSpriteRenderer, - // Install loader plugins - BitmapFontLoader, CompressedTextureLoader, DDSLoader, KTXLoader, SpritesheetLoader, - // Install application plugins - TickerPlugin, AppLoaderPlugin); - /** - * This namespace contains WebGL-only display filters that can be applied - * to DisplayObjects using the {@link PIXI.DisplayObject#filters filters} property. - * - * Since PixiJS only had a handful of built-in filters, additional filters - * can be downloaded {@link https://github.com/pixijs/pixi-filters here} from the - * PixiJS Filters repository. - * - * All filters must extend {@link PIXI.Filter}. - * @example - * // Create a new application - * const app = new PIXI.Application(); - * - * // Draw a green rectangle - * const rect = new PIXI.Graphics() - * .beginFill(0x00ff00) - * .drawRect(40, 40, 200, 200); - * - * // Add a blur filter - * rect.filters = [new PIXI.filters.BlurFilter()]; - * - * // Display rectangle - * app.stage.addChild(rect); - * document.body.appendChild(app.view); - * @namespace PIXI.filters - */ - var filters = { - AlphaFilter: AlphaFilter, - BlurFilter: BlurFilter, - BlurFilterPass: BlurFilterPass, - ColorMatrixFilter: ColorMatrixFilter, - DisplacementFilter: DisplacementFilter, - FXAAFilter: FXAAFilter, - NoiseFilter: NoiseFilter, - }; - - exports.AbstractBatchRenderer = AbstractBatchRenderer; - exports.AbstractMultiResource = AbstractMultiResource; - exports.AbstractRenderer = AbstractRenderer; - exports.AccessibilityManager = AccessibilityManager; - exports.AnimatedSprite = AnimatedSprite; - exports.AppLoaderPlugin = AppLoaderPlugin; - exports.Application = Application; - exports.ArrayResource = ArrayResource; - exports.Attribute = Attribute; - exports.BaseImageResource = BaseImageResource; - exports.BasePrepare = BasePrepare; - exports.BaseRenderTexture = BaseRenderTexture; - exports.BaseTexture = BaseTexture; - exports.BatchDrawCall = BatchDrawCall; - exports.BatchGeometry = BatchGeometry; - exports.BatchPluginFactory = BatchPluginFactory; - exports.BatchRenderer = BatchRenderer; - exports.BatchShaderGenerator = BatchShaderGenerator; - exports.BatchSystem = BatchSystem; - exports.BatchTextureArray = BatchTextureArray; - exports.BitmapFont = BitmapFont; - exports.BitmapFontData = BitmapFontData; - exports.BitmapFontLoader = BitmapFontLoader; - exports.BitmapText = BitmapText; - exports.BlobResource = BlobResource; - exports.Bounds = Bounds; - exports.BrowserAdapter = BrowserAdapter; - exports.Buffer = Buffer; - exports.BufferResource = BufferResource; - exports.CanvasResource = CanvasResource; - exports.Circle = Circle; - exports.CompressedTextureLoader = CompressedTextureLoader; - exports.CompressedTextureResource = CompressedTextureResource; - exports.Container = Container; - exports.ContextSystem = ContextSystem; - exports.CountLimiter = CountLimiter; - exports.CubeResource = CubeResource; - exports.DDSLoader = DDSLoader; - exports.DEG_TO_RAD = DEG_TO_RAD; - exports.DisplayObject = DisplayObject; - exports.Ellipse = Ellipse; - exports.Extract = Extract; - exports.FORMATS_TO_COMPONENTS = FORMATS_TO_COMPONENTS; - exports.FillStyle = FillStyle; - exports.Filter = Filter; - exports.FilterState = FilterState; - exports.FilterSystem = FilterSystem; - exports.Framebuffer = Framebuffer; - exports.FramebufferSystem = FramebufferSystem; - exports.GLFramebuffer = GLFramebuffer; - exports.GLProgram = GLProgram; - exports.GLTexture = GLTexture; - exports.GRAPHICS_CURVES = GRAPHICS_CURVES; - exports.Geometry = Geometry; - exports.GeometrySystem = GeometrySystem; - exports.Graphics = Graphics; - exports.GraphicsData = GraphicsData; - exports.GraphicsGeometry = GraphicsGeometry; - exports.IGLUniformData = IGLUniformData; - exports.INSTALLED = INSTALLED; - exports.INTERNAL_FORMAT_TO_BYTES_PER_PIXEL = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL; - exports.ImageBitmapResource = ImageBitmapResource; - exports.ImageResource = ImageResource; - exports.InteractionData = InteractionData; - exports.InteractionEvent = InteractionEvent; - exports.InteractionManager = InteractionManager; - exports.InteractionTrackingData = InteractionTrackingData; - exports.KTXLoader = KTXLoader; - exports.LineStyle = LineStyle; - exports.Loader = Loader; - exports.MaskData = MaskData; - exports.MaskSystem = MaskSystem; - exports.Matrix = Matrix; - exports.Mesh = Mesh; - exports.MeshBatchUvs = MeshBatchUvs; - exports.MeshGeometry = MeshGeometry; - exports.MeshMaterial = MeshMaterial; - exports.NineSlicePlane = NineSlicePlane; - exports.ObjectRenderer = ObjectRenderer; - exports.ObservablePoint = ObservablePoint; - exports.PI_2 = PI_2; - exports.ParticleContainer = ParticleContainer; - exports.ParticleRenderer = ParticleRenderer; - exports.PlaneGeometry = PlaneGeometry; - exports.Point = Point; - exports.Polygon = Polygon; - exports.Prepare = Prepare; - exports.Program = Program; - exports.ProjectionSystem = ProjectionSystem; - exports.Quad = Quad; - exports.QuadUv = QuadUv; - exports.RAD_TO_DEG = RAD_TO_DEG; - exports.Rectangle = Rectangle; - exports.RenderTexture = RenderTexture; - exports.RenderTexturePool = RenderTexturePool; - exports.RenderTextureSystem = RenderTextureSystem; - exports.Renderer = Renderer; - exports.ResizePlugin = ResizePlugin; - exports.Resource = Resource; - exports.RopeGeometry = RopeGeometry; - exports.RoundedRectangle = RoundedRectangle; - exports.Runner = Runner; - exports.SVGResource = SVGResource; - exports.ScissorSystem = ScissorSystem; - exports.Shader = Shader; - exports.ShaderSystem = ShaderSystem; - exports.SimpleMesh = SimpleMesh; - exports.SimplePlane = SimplePlane; - exports.SimpleRope = SimpleRope; - exports.Sprite = Sprite; - exports.SpriteMaskFilter = SpriteMaskFilter; - exports.Spritesheet = Spritesheet; - exports.SpritesheetLoader = SpritesheetLoader; - exports.State = State; - exports.StateSystem = StateSystem; - exports.StencilSystem = StencilSystem; - exports.System = System; - exports.TYPES_TO_BYTES_PER_COMPONENT = TYPES_TO_BYTES_PER_COMPONENT; - exports.TYPES_TO_BYTES_PER_PIXEL = TYPES_TO_BYTES_PER_PIXEL; - exports.TemporaryDisplayObject = TemporaryDisplayObject; - exports.Text = Text; - exports.TextFormat = TextFormat; - exports.TextMetrics = TextMetrics; - exports.TextStyle = TextStyle; - exports.Texture = Texture; - exports.TextureGCSystem = TextureGCSystem; - exports.TextureLoader = TextureLoader; - exports.TextureMatrix = TextureMatrix; - exports.TextureSystem = TextureSystem; - exports.TextureUvs = TextureUvs; - exports.Ticker = Ticker; - exports.TickerPlugin = TickerPlugin; - exports.TilingSprite = TilingSprite; - exports.TilingSpriteRenderer = TilingSpriteRenderer; - exports.TimeLimiter = TimeLimiter; - exports.Transform = Transform; - exports.UniformGroup = UniformGroup; - exports.VERSION = VERSION; - exports.VideoResource = VideoResource; - exports.ViewableBuffer = ViewableBuffer; - exports.XMLFormat = XMLFormat; - exports.XMLStringFormat = XMLStringFormat; - exports.accessibleTarget = accessibleTarget; - exports.autoDetectFormat = autoDetectFormat; - exports.autoDetectRenderer = autoDetectRenderer; - exports.autoDetectResource = autoDetectResource; - exports.checkMaxIfStatementsInShader = checkMaxIfStatementsInShader; - exports.createUBOElements = createUBOElements; - exports.defaultFilterVertex = defaultFilterVertex; - exports.defaultVertex = defaultVertex$1; - exports.extensions = extensions; - exports.filters = filters; - exports.generateProgram = generateProgram; - exports.generateUniformBufferSync = generateUniformBufferSync; - exports.getTestContext = getTestContext; - exports.getUBOData = getUBOData; - exports.graphicsUtils = graphicsUtils; - exports.groupD8 = groupD8; - exports.interactiveTarget = interactiveTarget; - exports.isMobile = isMobile; - exports.parseDDS = parseDDS; - exports.parseKTX = parseKTX; - exports.resources = resources; - exports.settings = settings; - exports.systems = systems; - exports.uniformParsers = uniformParsers; - exports.utils = utils; - - Object.defineProperty(exports, '__esModule', { value: true }); - - return exports; - -})({}); -//# sourceMappingURL=pixi.js.map From dd911d7a2105a39a34cb40a27b583fd7f201f877 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 24 Aug 2023 14:27:30 -0500 Subject: [PATCH 068/188] Scope: added (disabled) benchmark for time spent drawing --- IDE/frontend-dev/scope-src/scope-browser.js | 21 +++++++++++++++++++++ IDE/public/gui/js/GuiHandler.js | 13 +++++++++++++ IDE/public/scope/index.html | 4 +++- IDE/public/scope/js/bundle.js | 21 +++++++++++++++++++++ 4 files changed, 58 insertions(+), 1 deletion(-) diff --git a/IDE/frontend-dev/scope-src/scope-browser.js b/IDE/frontend-dev/scope-src/scope-browser.js index 0a45973eb..c92a74c6d 100644 --- a/IDE/frontend-dev/scope-src/scope-browser.js +++ b/IDE/frontend-dev/scope-src/scope-browser.js @@ -378,9 +378,17 @@ function CPU(data){ } }; + const benchmarkDrawing = false; + const plotRuns = 50; + let plotRunsSum = 0; + let plotRunsStart = 0; + let plotRunsIdx = 0; function plotLoop(){ if (plot){ plot = false; + let start; + if(benchmarkDrawing) + start = performance.now(); ctx.clear(); let minY = 0; let maxY = renderer.height; @@ -418,6 +426,19 @@ function CPU(data){ } renderer.render(stage); triggerStatus(); + if(benchmarkDrawing) { + let stop = performance.now(); + let dur = stop - start; + plotRunsSum += dur; + plotRunsIdx++; + if(plotRunsIdx >= plotRuns) { + let perc = plotRunsSum / (stop - plotRunsStart) * 100; + console.log("sum: " + plotRunsSum.toFixed(2) + ", avg: ", + perc.toFixed(2) + "%, avg fps: ", plotRuns / ((stop - plotRunsStart) / 1000)); + plotRunsSum = 0; + plotRunsIdx = 0; + plotRunsStart = stop; + } + } } /*else { console.log('not plotting'); }*/ diff --git a/IDE/public/gui/js/GuiHandler.js b/IDE/public/gui/js/GuiHandler.js index ed31d9e93..d328ac9bc 100644 --- a/IDE/public/gui/js/GuiHandler.js +++ b/IDE/public/gui/js/GuiHandler.js @@ -1,5 +1,18 @@ import * as utils from './utils.js' import GuiCreator from './GuiCreator.js' +function setup() { + console.log("P5 setup"); +} + +function draw() { + console.log("DRAW") + background(0); // Set the background to black + y = y - 1; + if (y < 0) { + y = height; + } + line(0, y, width, y); +} export default class GuiHandler { constructor(control, parentId='gui') { diff --git a/IDE/public/scope/index.html b/IDE/public/scope/index.html index a081aa1a5..02cc7b4f9 100644 --- a/IDE/public/scope/index.html +++ b/IDE/public/scope/index.html @@ -299,12 +299,14 @@

Channel 1

+
+ - + diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index fe6397e30..eefedde19 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -1684,6 +1684,8 @@ function CPU(data) { var plotLoop = function plotLoop() { if (plot) { plot = false; + var start = void 0; + if (benchmarkDrawing) start = performance.now(); ctx.clear(); var minY = 0; var maxY = renderer.height; @@ -1718,6 +1720,19 @@ function CPU(data) { } renderer.render(stage); triggerStatus(); + if (benchmarkDrawing) { + var stop = performance.now(); + var dur = stop - start; + plotRunsSum += dur; + plotRunsIdx++; + if (plotRunsIdx >= plotRuns) { + var perc = plotRunsSum / (stop - plotRunsStart) * 100; + console.log("sum: " + plotRunsSum.toFixed(2) + ", avg: ", +perc.toFixed(2) + "%, avg fps: ", plotRuns / ((stop - plotRunsStart) / 1000)); + plotRunsSum = 0; + plotRunsIdx = 0; + plotRunsStart = stop; + } + } } /*else { console.log('not plotting'); }*/ @@ -1818,6 +1833,12 @@ function CPU(data) { } }; + var benchmarkDrawing = false; + var plotRuns = 50; + var plotRunsSum = 0; + var plotRunsStart = 0; + var plotRunsIdx = 0; + plotLoop(); // update the status indicator when triggered From 93aea3d1450e9a735852ec8d2edcd8a4379db373 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 24 Aug 2023 14:43:35 -0500 Subject: [PATCH 069/188] Scope: allow to set native line --- IDE/frontend-dev/scope-src/scope-browser.js | 7 ++++++- IDE/public/scope/js/bundle.js | 7 ++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/IDE/frontend-dev/scope-src/scope-browser.js b/IDE/frontend-dev/scope-src/scope-browser.js index c92a74c6d..91ed7fdb9 100644 --- a/IDE/frontend-dev/scope-src/scope-browser.js +++ b/IDE/frontend-dev/scope-src/scope-browser.js @@ -395,7 +395,12 @@ function CPU(data){ for (var i=0; i { if(v < min) diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index eefedde19..14aa9e5ef 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -1691,7 +1691,12 @@ function CPU(data) { var maxY = renderer.height; for (var i = 0; i < numChannels; i++) { if (!channelConfig[i].enabled) continue; - ctx.lineStyle(channelConfig[i].lineWeight, channelConfig[i].color, 1); + ctx.lineStyle({ + width: channelConfig[i].lineWeight, + color: channelConfig[i].color, + alpha: 1, + native: false // setting this to true may reduce CPU usage but only allows width: 1 + }); var iLength = i * length; var constrain = function constrain(v, min, max) { if (v < min) return min; From 3fda4e9cb66249ad697755d615de81d2ab72cd2e Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 24 Aug 2023 16:25:48 -0500 Subject: [PATCH 070/188] NIT: Scope: removed dead branch and reindented --- IDE/frontend-dev/scope-src/scope-browser.js | 117 ++++++++++---------- IDE/public/scope/js/bundle.js | 109 +++++++++--------- 2 files changed, 112 insertions(+), 114 deletions(-) diff --git a/IDE/frontend-dev/scope-src/scope-browser.js b/IDE/frontend-dev/scope-src/scope-browser.js index 91ed7fdb9..6a680eee4 100644 --- a/IDE/frontend-dev/scope-src/scope-browser.js +++ b/IDE/frontend-dev/scope-src/scope-browser.js @@ -384,69 +384,68 @@ function CPU(data){ let plotRunsStart = 0; let plotRunsIdx = 0; function plotLoop(){ - if (plot){ - plot = false; - let start; - if(benchmarkDrawing) - start = performance.now(); - ctx.clear(); - let minY = 0; - let maxY = renderer.height; - for (var i=0; i { - if(v < min) - return min; - if(v > max) - return max; - return v; - } - let curr = constrain(frame[iLength], minY, maxY); - let next = constrain(frame[iLength + 1], minY, maxY); - ctx.moveTo(0, curr + xOff*(next - curr)); - let lastAlpha = 1; - for (var j=1; (j-xOff)= 0) { - let dist = (length + oldDataSeparator - j - 1) % length; - let alpha = dist < length / 2 ? 1 : 1 - (dist - length / 2) / (length / 2); - // throttle lineStyle() calls as they are CPU-heavy - if(Math.abs(alpha - lastAlpha) > 0.1 || (lastAlpha != 1 && alpha == 1)) { - lastAlpha = alpha; - ctx.lineStyle(channelConfig[i].lineWeight, channelConfig[i].color, alpha); - } + if (!plot){ + return + } + plot = false; + let start; + if(benchmarkDrawing) + start = performance.now(); + ctx.clear(); + let minY = 0; + let maxY = renderer.height; + for (var i=0; i { + if(v < min) + return min; + if(v > max) + return max; + return v; + } + let curr = constrain(frame[iLength], minY, maxY); + let next = constrain(frame[iLength + 1], minY, maxY); + ctx.moveTo(0, curr + xOff*(next - curr)); + let lastAlpha = 1; + for (var j=1; (j-xOff)= 0) { + let dist = (length + oldDataSeparator - j - 1) % length; + let alpha = dist < length / 2 ? 1 : 1 - (dist - length / 2) / (length / 2); + // throttle lineStyle() calls as they are CPU-heavy + if(Math.abs(alpha - lastAlpha) > 0.1 || (lastAlpha != 1 && alpha == 1)) { + lastAlpha = alpha; + ctx.lineStyle(channelConfig[i].lineWeight, channelConfig[i].color, alpha); } - ctx.lineTo(j-xOff, curr); } + ctx.lineTo(j-xOff, curr); } - renderer.render(stage); - triggerStatus(); - if(benchmarkDrawing) { - let stop = performance.now(); - let dur = stop - start; - plotRunsSum += dur; - plotRunsIdx++; - if(plotRunsIdx >= plotRuns) { - let perc = plotRunsSum / (stop - plotRunsStart) * 100; - console.log("sum: " + plotRunsSum.toFixed(2) + ", avg: ", + perc.toFixed(2) + "%, avg fps: ", plotRuns / ((stop - plotRunsStart) / 1000)); - plotRunsSum = 0; - plotRunsIdx = 0; - plotRunsStart = stop; - } + } + renderer.render(stage); + triggerStatus(); + if(benchmarkDrawing) { + let stop = performance.now(); + let dur = stop - start; + plotRunsSum += dur; + plotRunsIdx++; + if(plotRunsIdx >= plotRuns) { + let perc = plotRunsSum / (stop - plotRunsStart) * 100; + console.log("sum: " + plotRunsSum.toFixed(2) + ", avg: ", + perc.toFixed(2) + "%, avg fps: ", plotRuns / ((stop - plotRunsStart) / 1000)); + plotRunsSum = 0; + plotRunsIdx = 0; + plotRunsStart = stop; } - } /*else { - console.log('not plotting'); - }*/ + } } plotLoop(); diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index 14aa9e5ef..45fbe5f89 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -1682,65 +1682,64 @@ function CPU(data) { // plotting { var plotLoop = function plotLoop() { - if (plot) { - plot = false; - var start = void 0; - if (benchmarkDrawing) start = performance.now(); - ctx.clear(); - var minY = 0; - var maxY = renderer.height; - for (var i = 0; i < numChannels; i++) { - if (!channelConfig[i].enabled) continue; - ctx.lineStyle({ - width: channelConfig[i].lineWeight, - color: channelConfig[i].color, - alpha: 1, - native: false // setting this to true may reduce CPU usage but only allows width: 1 - }); - var iLength = i * length; - var constrain = function constrain(v, min, max) { - if (v < min) return min; - if (v > max) return max; - return v; - }; - var curr = constrain(frame[iLength], minY, maxY); - var next = constrain(frame[iLength + 1], minY, maxY); - ctx.moveTo(0, curr + xOff * (next - curr)); - var lastAlpha = 1; - for (var j = 1; j - xOff < length; j++) { - var _curr = constrain(frame[j + iLength], minY, maxY); - // when drawing incrementally, alpha will be 1 when close to the most - // recent and then progressively fade out for older values - if (oldDataSeparator >= 0) { - var dist = (length + oldDataSeparator - j - 1) % length; - var alpha = dist < length / 2 ? 1 : 1 - (dist - length / 2) / (length / 2); - // throttle lineStyle() calls as they are CPU-heavy - if (Math.abs(alpha - lastAlpha) > 0.1 || lastAlpha != 1 && alpha == 1) { - lastAlpha = alpha; - ctx.lineStyle(channelConfig[i].lineWeight, channelConfig[i].color, alpha); - } + if (!plot) { + return; + } + plot = false; + var start = void 0; + if (benchmarkDrawing) start = performance.now(); + ctx.clear(); + var minY = 0; + var maxY = renderer.height; + for (var i = 0; i < numChannels; i++) { + if (!channelConfig[i].enabled) continue; + ctx.lineStyle({ + width: channelConfig[i].lineWeight, + color: channelConfig[i].color, + alpha: 1, + native: false // setting this to true may reduce CPU usage but only allows width: 1 + }); + var iLength = i * length; + var constrain = function constrain(v, min, max) { + if (v < min) return min; + if (v > max) return max; + return v; + }; + var curr = constrain(frame[iLength], minY, maxY); + var next = constrain(frame[iLength + 1], minY, maxY); + ctx.moveTo(0, curr + xOff * (next - curr)); + var lastAlpha = 1; + for (var j = 1; j - xOff < length; j++) { + var _curr = constrain(frame[j + iLength], minY, maxY); + // when drawing incrementally, alpha will be 1 when close to the most + // recent and then progressively fade out for older values + if (oldDataSeparator >= 0) { + var dist = (length + oldDataSeparator - j - 1) % length; + var alpha = dist < length / 2 ? 1 : 1 - (dist - length / 2) / (length / 2); + // throttle lineStyle() calls as they are CPU-heavy + if (Math.abs(alpha - lastAlpha) > 0.1 || lastAlpha != 1 && alpha == 1) { + lastAlpha = alpha; + ctx.lineStyle(channelConfig[i].lineWeight, channelConfig[i].color, alpha); } - ctx.lineTo(j - xOff, _curr); } + ctx.lineTo(j - xOff, _curr); } - renderer.render(stage); - triggerStatus(); - if (benchmarkDrawing) { - var stop = performance.now(); - var dur = stop - start; - plotRunsSum += dur; - plotRunsIdx++; - if (plotRunsIdx >= plotRuns) { - var perc = plotRunsSum / (stop - plotRunsStart) * 100; - console.log("sum: " + plotRunsSum.toFixed(2) + ", avg: ", +perc.toFixed(2) + "%, avg fps: ", plotRuns / ((stop - plotRunsStart) / 1000)); - plotRunsSum = 0; - plotRunsIdx = 0; - plotRunsStart = stop; - } + } + renderer.render(stage); + triggerStatus(); + if (benchmarkDrawing) { + var stop = performance.now(); + var dur = stop - start; + plotRunsSum += dur; + plotRunsIdx++; + if (plotRunsIdx >= plotRuns) { + var perc = plotRunsSum / (stop - plotRunsStart) * 100; + console.log("sum: " + plotRunsSum.toFixed(2) + ", avg: ", +perc.toFixed(2) + "%, avg fps: ", plotRuns / ((stop - plotRunsStart) / 1000)); + plotRunsSum = 0; + plotRunsIdx = 0; + plotRunsStart = stop; } - } /*else { - console.log('not plotting'); - }*/ + } }; var triggerStatus = function triggerStatus() { From d2e6239ab3114065a5b82bb94efcfbe3ade6da0c Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 24 Aug 2023 19:54:35 -0500 Subject: [PATCH 071/188] Scope: removed exponential notation from x axis markers --- IDE/frontend-dev/scope-src/BackgroundView.js | 11 +++++++++-- IDE/public/scope/js/bundle.js | 6 ++++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/IDE/frontend-dev/scope-src/BackgroundView.js b/IDE/frontend-dev/scope-src/BackgroundView.js index 8f949a0de..83ca8e6a6 100644 --- a/IDE/frontend-dev/scope-src/BackgroundView.js +++ b/IDE/frontend-dev/scope-src/BackgroundView.js @@ -47,10 +47,17 @@ class BackgroundView extends View{ for (var i=1; i Date: Thu, 24 Aug 2023 20:19:23 -0500 Subject: [PATCH 072/188] Scope: update frontend with backend data for more (all?) parameters --- IDE/frontend-dev/scope-src/ControlView.js | 16 ++++++++++++++++ IDE/public/scope/js/bundle.js | 20 ++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/IDE/frontend-dev/scope-src/ControlView.js b/IDE/frontend-dev/scope-src/ControlView.js index a7c0abde1..143282b14 100644 --- a/IDE/frontend-dev/scope-src/ControlView.js +++ b/IDE/frontend-dev/scope-src/ControlView.js @@ -172,6 +172,22 @@ class ControlView extends View{ _triggerLevel(value){ this.$elements.filterByData('key', 'triggerLevel').val(value); } + + _xAxisBehaviour(value){ + this.$elements.filterByData('key', 'xAxisBehaviour').val(value); + } + + _holdOff(value){ + this.$elements.filterByData('key', 'holdOff').val(value); + } + + _xOffset(value){ + this.$elements.filterByData('key', 'xOffset').val(value); + } + + _interpolation(value){ + this.$elements.filterByData('key', 'interpolation').val(value); + } } module.exports = ControlView; diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index dea0a27b0..ce0456137 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -1027,6 +1027,26 @@ var ControlView = function (_View) { value: function _triggerLevel(value) { this.$elements.filterByData('key', 'triggerLevel').val(value); } + }, { + key: '_xAxisBehaviour', + value: function _xAxisBehaviour(value) { + this.$elements.filterByData('key', 'xAxisBehaviour').val(value); + } + }, { + key: '_holdOff', + value: function _holdOff(value) { + this.$elements.filterByData('key', 'holdOff').val(value); + } + }, { + key: '_xOffset', + value: function _xOffset(value) { + this.$elements.filterByData('key', 'xOffset').val(value); + } + }, { + key: '_interpolation', + value: function _interpolation(value) { + this.$elements.filterByData('key', 'interpolation').val(value); + } }]); return ControlView; From 279a5102b2c21338810cb8d348f09e73c5e7549a Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 24 Aug 2023 20:19:23 -0500 Subject: [PATCH 073/188] Scope: update frontend with backend data for more (all?) parameters --- IDE/frontend-dev/scope-src/ControlView.js | 32 ++++++++++++--------- IDE/public/scope/js/bundle.js | 35 +++++++++++------------ 2 files changed, 35 insertions(+), 32 deletions(-) diff --git a/IDE/frontend-dev/scope-src/ControlView.js b/IDE/frontend-dev/scope-src/ControlView.js index 143282b14..7545fc813 100644 --- a/IDE/frontend-dev/scope-src/ControlView.js +++ b/IDE/frontend-dev/scope-src/ControlView.js @@ -9,6 +9,7 @@ class ControlView extends View{ super(className, models); $('#controlsButton, .overlay').on('click', () => this.toggleControls()); $('body').on('keydown', (e) => this.keyHandler(e)); + this.addGenericHandlers(); } toggleControls(){ @@ -157,20 +158,23 @@ class ControlView extends View{ } } - _triggerMode(value){ - this.$elements.filterByData('key', 'triggerMode').val(value); - } - - _triggerChannel(value){ - this.$elements.filterByData('key', 'triggerChannel').val(value); - } - - _triggerDir(value){ - this.$elements.filterByData('key', 'triggerDir').val(value); - } - - _triggerLevel(value){ - this.$elements.filterByData('key', 'triggerLevel').val(value); + addGenericHandlers() { + let genericHandlers = [ + "triggerMode", + "triggerChannel", + "triggerDir", + "triggerLevel", + "xAxisBehaviour", + "holdOff", + "xOffset", + "interpolation", + ]; + for(let n = 0; n < genericHandlers.length; ++n) { + let h = genericHandlers[n]; + this["_" + h] = (value) => { + this.$elements.filterByData('key', h).val(value); + } + } } _xAxisBehaviour(value){ diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index ce0456137..bd6000a0e 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -819,6 +819,7 @@ var ControlView = function (_View) { $('body').on('keydown', function (e) { return _this.keyHandler(e); }); + _this.addGenericHandlers(); return _this; } @@ -1008,24 +1009,22 @@ var ControlView = function (_View) { } } }, { - key: '_triggerMode', - value: function _triggerMode(value) { - this.$elements.filterByData('key', 'triggerMode').val(value); - } - }, { - key: '_triggerChannel', - value: function _triggerChannel(value) { - this.$elements.filterByData('key', 'triggerChannel').val(value); - } - }, { - key: '_triggerDir', - value: function _triggerDir(value) { - this.$elements.filterByData('key', 'triggerDir').val(value); - } - }, { - key: '_triggerLevel', - value: function _triggerLevel(value) { - this.$elements.filterByData('key', 'triggerLevel').val(value); + key: 'addGenericHandlers', + value: function addGenericHandlers() { + var _this2 = this; + + var genericHandlers = ["triggerMode", "triggerChannel", "triggerDir", "triggerLevel", "xAxisBehaviour", "holdOff", "xOffset", "interpolation"]; + + var _loop = function _loop(n) { + var h = genericHandlers[n]; + _this2["_" + h] = function (value) { + _this2.$elements.filterByData('key', h).val(value); + }; + }; + + for (var n = 0; n < genericHandlers.length; ++n) { + _loop(n); + } } }, { key: '_xAxisBehaviour', From 77f8d15a1d67ee3207059d8d64c0be61c7eeb5e0 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 24 Aug 2023 22:56:27 -0500 Subject: [PATCH 074/188] NIT: Scope: removed stale sliders code --- IDE/frontend-dev/scope-src/SliderView.js | 81 ------------- IDE/frontend-dev/scope-src/scope-browser.js | 18 --- IDE/public/scope/js/bundle.js | 122 ++------------------ 3 files changed, 10 insertions(+), 211 deletions(-) delete mode 100644 IDE/frontend-dev/scope-src/SliderView.js diff --git a/IDE/frontend-dev/scope-src/SliderView.js b/IDE/frontend-dev/scope-src/SliderView.js deleted file mode 100644 index 06bf12a8f..000000000 --- a/IDE/frontend-dev/scope-src/SliderView.js +++ /dev/null @@ -1,81 +0,0 @@ -'use strict'; -var View = require('./View'); - -class SliderView extends View{ - - constructor(className, models){ - super(className, models); - - this.on('set-slider', args => { - $('#scopeSlider'+args.slider) - .find('input[type=range]') - .prop('min', args.min) - .prop('max', args.max) - .prop('step', args.step) - .val(args.value) - .siblings('input[type=number]') - .prop('min', args.min) - .prop('max', args.max) - .prop('step', args.step) - .val(args.value) - .siblings('h1') - .html((args.name == 'Slider') ? 'Slider '+args.slider : args.name); - - var inputs = $('#scopeSlider'+args.slider).find('input[type=number]'); - inputs.filterByData('key', 'min').val(args.min); - inputs.filterByData('key', 'max').val(args.max); - inputs.filterByData('key', 'step').val(args.step); - }); - - } - - inputChanged($element, e){ - - var key = $element.data().key; - var slider = $element.data().slider; - var value = $element.val(); - - if (key === 'value'){ - this.emit('slider-value', parseInt(slider), parseFloat(value)); - } else { - $element.closest('div.sliderView') - .find('input[type=range]').prop(key, value) - .siblings('input[type=number]').prop(key, value); - } - - $element.siblings('input').val(value); - } - - _numSliders(val){ - - var el = $('#scopeSlider0'); - - $('#sliderColumn').empty(); - - if (val == 0){ - el.appendTo($('#sliderColumn')).css('display', 'none'); - } - - for (var i=0; i this.inputChanged($(e.currentTarget), e)); - } - - } - -} - -module.exports = SliderView; - -$.fn.filterByData = function(prop, val) { - return this.filter( - function() { return $(this).data(prop)==val; } - ); -} diff --git a/IDE/frontend-dev/scope-src/scope-browser.js b/IDE/frontend-dev/scope-src/scope-browser.js index 6a680eee4..3e242653d 100644 --- a/IDE/frontend-dev/scope-src/scope-browser.js +++ b/IDE/frontend-dev/scope-src/scope-browser.js @@ -40,7 +40,6 @@ var stage = new PIXI.Container(); var controlView = new (require('./ControlView'))('scope-controls', [settings]); var backgroundView = new (require('./BackgroundView'))('scopeBG', [settings], renderer); var channelView = new (require('./ChannelView'))('channelView', [settings]); -var sliderView = new (require('./SliderView'))('sliderView', [settings]); // main bela socket var belaSocket = io('/IDE'); @@ -89,8 +88,6 @@ var ws_onmessage = function(msg){ return; } if (ws && ws.readyState === 1) ws.send(out); - } else if (data.event == 'set-slider'){ - sliderView.emit('set-slider', data); } else if (data.event == 'set-setting'){ if (settings.getKey(data.setting) !== undefined) { settings.setKey(data.setting, data.value); @@ -190,19 +187,6 @@ channelView.on('channelConfig', (channelConfig) => { legend.update(channelConfig); }); -sliderView.on('slider-value', (slider, value) => { - var obj = {event: "slider", slider, value}; - var out; - try{ - out = JSON.stringify(obj); - } - catch(e){ - console.log('could not stringify slider json:', e); - return; - } - if (ws && ws.readyState === 1) ws.send(out) -}); - belaSocket.on('cpu-usage', CPU); // model events @@ -524,7 +508,6 @@ function CPU(data){ settings.setData({ numChannels : 2, sampleRate : 44100, - numSliders : 0, frameWidth : 1280, plotMode : 0, triggerMode : 0, @@ -539,7 +522,6 @@ settings.setData({ FFTXAxis : 0, FFTYAxis : 0, holdOff : 0, - numSliders : 0, interpolation : 0 }); diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index bd6000a0e..ded63a437 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -542,7 +542,7 @@ var BackgroundView = function (_View) { module.exports = BackgroundView; -},{"./View":7}],3:[function(require,module,exports){ +},{"./View":6}],3:[function(require,module,exports){ 'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); @@ -786,7 +786,7 @@ $.fn.filterByData = function (prop, val) { }); }; -},{"./View":7}],4:[function(require,module,exports){ +},{"./View":6}],4:[function(require,module,exports){ 'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); @@ -1059,7 +1059,7 @@ $.fn.filterByData = function (prop, val) { }); }; -},{"./View":7}],5:[function(require,module,exports){ +},{"./View":6}],5:[function(require,module,exports){ 'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); @@ -1178,89 +1178,6 @@ function _possibleConstructorReturn(self, call) { if (!self) { throw new Referen function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } -var View = require('./View'); - -var SliderView = function (_View) { - _inherits(SliderView, _View); - - function SliderView(className, models) { - _classCallCheck(this, SliderView); - - var _this = _possibleConstructorReturn(this, (SliderView.__proto__ || Object.getPrototypeOf(SliderView)).call(this, className, models)); - - _this.on('set-slider', function (args) { - $('#scopeSlider' + args.slider).find('input[type=range]').prop('min', args.min).prop('max', args.max).prop('step', args.step).val(args.value).siblings('input[type=number]').prop('min', args.min).prop('max', args.max).prop('step', args.step).val(args.value).siblings('h1').html(args.name == 'Slider' ? 'Slider ' + args.slider : args.name); - - var inputs = $('#scopeSlider' + args.slider).find('input[type=number]'); - inputs.filterByData('key', 'min').val(args.min); - inputs.filterByData('key', 'max').val(args.max); - inputs.filterByData('key', 'step').val(args.step); - }); - - return _this; - } - - _createClass(SliderView, [{ - key: 'inputChanged', - value: function inputChanged($element, e) { - - var key = $element.data().key; - var slider = $element.data().slider; - var value = $element.val(); - - if (key === 'value') { - this.emit('slider-value', parseInt(slider), parseFloat(value)); - } else { - $element.closest('div.sliderView').find('input[type=range]').prop(key, value).siblings('input[type=number]').prop(key, value); - } - - $element.siblings('input').val(value); - } - }, { - key: '_numSliders', - value: function _numSliders(val) { - var _this2 = this; - - var el = $('#scopeSlider0'); - - $('#sliderColumn').empty(); - - if (val == 0) { - el.appendTo($('#sliderColumn')).css('display', 'none'); - } - - for (var i = 0; i < val; i++) { - var slider = el.clone(true).prop('id', 'scopeSlider' + i).appendTo($('#sliderColumn')).css('display', 'block'); - - slider.find('input').data('slider', i).on('input', function (e) { - return _this2.inputChanged($(e.currentTarget), e); - }); - } - } - }]); - - return SliderView; -}(View); - -module.exports = SliderView; - -$.fn.filterByData = function (prop, val) { - return this.filter(function () { - return $(this).data(prop) == val; - }); -}; - -},{"./View":7}],7:[function(require,module,exports){ -'use strict'; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - var EventEmitter = require('events').EventEmitter; var View = function (_EventEmitter) { @@ -1379,20 +1296,16 @@ var View = function (_EventEmitter) { module.exports = View; -},{"events":1}],8:[function(require,module,exports){ +},{"events":1}],7:[function(require,module,exports){ 'use strict'; var scope = require('./scope-browser'); -},{"./scope-browser":9}],9:[function(require,module,exports){ +},{"./scope-browser":8}],8:[function(require,module,exports){ 'use strict'; // worker -var _settings$setData; - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - var remoteHost = location.hostname + ":5432"; var qs = new URLSearchParams(location.search); var qsRemoteHost = qs.get("remoteHost"); @@ -1431,7 +1344,6 @@ var stage = new PIXI.Container(); var controlView = new (require('./ControlView'))('scope-controls', [settings]); var backgroundView = new (require('./BackgroundView'))('scopeBG', [settings], renderer); var channelView = new (require('./ChannelView'))('channelView', [settings]); -var sliderView = new (require('./SliderView'))('sliderView', [settings]); // main bela socket var belaSocket = io('/IDE'); @@ -1477,8 +1389,6 @@ var ws_onmessage = function ws_onmessage(msg) { return; } if (ws && ws.readyState === 1) ws.send(out); - } else if (data.event == 'set-slider') { - sliderView.emit('set-slider', data); } else if (data.event == 'set-setting') { if (settings.getKey(data.setting) !== undefined) { settings.setKey(data.setting, data.value); @@ -1577,18 +1487,6 @@ channelView.on('channelConfig', function (channelConfig) { legend.update(channelConfig); }); -sliderView.on('slider-value', function (slider, value) { - var obj = { event: "slider", slider: slider, value: value }; - var out; - try { - out = JSON.stringify(obj); - } catch (e) { - console.log('could not stringify slider json:', e); - return; - } - if (ws && ws.readyState === 1) ws.send(out); -}); - belaSocket.on('cpu-usage', CPU); // model events @@ -1917,10 +1815,9 @@ function CPU(data) { }); } -settings.setData((_settings$setData = { +settings.setData({ numChannels: 2, sampleRate: 44100, - numSliders: 0, frameWidth: 1280, plotMode: 0, triggerMode: 0, @@ -1934,9 +1831,10 @@ settings.setData((_settings$setData = { FFTLength: 1024, FFTXAxis: 0, FFTYAxis: 0, - holdOff: 0 -}, _defineProperty(_settings$setData, "numSliders", 0), _defineProperty(_settings$setData, "interpolation", 0), _settings$setData)); + holdOff: 0, + interpolation: 0 +}); -},{"./BackgroundView":2,"./ChannelView":3,"./ControlView":4,"./Model":5,"./SliderView":6}]},{},[8]) +},{"./BackgroundView":2,"./ChannelView":3,"./ControlView":4,"./Model":5}]},{},[7]) //# sourceMappingURL=bundle.js.map From 72c57988522656cb82d8819403323e573be6efb7 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 25 Aug 2023 15:36:23 -0500 Subject: [PATCH 075/188] Scope: factored out sending to websocket --- IDE/frontend-dev/scope-src/scope-browser.js | 46 ++++++++------------- IDE/public/scope/js/bundle.js | 42 ++++++++----------- 2 files changed, 35 insertions(+), 53 deletions(-) diff --git a/IDE/frontend-dev/scope-src/scope-browser.js b/IDE/frontend-dev/scope-src/scope-browser.js index 3e242653d..b07045f3b 100644 --- a/IDE/frontend-dev/scope-src/scope-browser.js +++ b/IDE/frontend-dev/scope-src/scope-browser.js @@ -38,12 +38,26 @@ var stage = new PIXI.Container(); // views var controlView = new (require('./ControlView'))('scope-controls', [settings]); -var backgroundView = new (require('./BackgroundView'))('scopeBG', [settings], renderer); +var backgroundView = dataDisabled ? {} : new (require('./BackgroundView'))('scopeBG', [settings], renderer); var channelView = new (require('./ChannelView'))('channelView', [settings]); // main bela socket var belaSocket = io('/IDE'); +function sendToWs(obj) { + if (ws && ws.readyState === 1) { + let out; + try { + let out = JSON.stringify(obj); + ws.send(out); + } + catch(e){ + console.log('could not stringify settings:', e); + return; + } + } +} + var ws_onerror = function(e){ setTimeout(() => { ws = new WebSocket(wsUrl); @@ -79,15 +93,7 @@ var ws_onmessage = function(msg){ var obj = settings._getData(); obj.event = "connection-reply"; - var out; - try{ - out = JSON.stringify(obj); - } - catch(e){ - console.log('could not stringify settings:', e); - return; - } - if (ws && ws.readyState === 1) ws.send(out); + sendToWs(obj); } else if (data.event == 'set-setting'){ if (settings.getKey(data.setting) !== undefined) { settings.setKey(data.setting, data.value); @@ -134,15 +140,7 @@ controlView.on('settings-event', (key, value) => { if (value === undefined) return; var obj = {}; obj[key] = value; - var out; - try{ - out = JSON.stringify(obj); - } - catch(e){ - console.log('error creating settings JSON', e); - return; - } - if (ws && ws.readyState === 1) ws.send(out); + sendToWs(obj); settings.setKey(key, value); }); @@ -194,15 +192,7 @@ settings.on('set', (data, changedKeys) => { if (changedKeys.indexOf('frameWidth') !== -1){ var xTimeBase = Math.max(Math.floor(1000*(data.frameWidth/8)/data.sampleRate), 1); settings.setKey('xTimeBase', xTimeBase); - var out; - try{ - out = JSON.stringify({frameWidth: data.frameWidth}); - } - catch(e){ - console.log('unable to stringify framewidth', e); - return; - } - if (ws && ws.readyState === 1) ws.send(out); + sendToWs({frameWidth: data.frameWidth}); } else { worker.postMessage({ event : 'settings', diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index ded63a437..064d42295 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -1342,12 +1342,25 @@ var stage = new PIXI.Container(); // views var controlView = new (require('./ControlView'))('scope-controls', [settings]); -var backgroundView = new (require('./BackgroundView'))('scopeBG', [settings], renderer); +var backgroundView = dataDisabled ? {} : new (require('./BackgroundView'))('scopeBG', [settings], renderer); var channelView = new (require('./ChannelView'))('channelView', [settings]); // main bela socket var belaSocket = io('/IDE'); +function sendToWs(obj) { + if (ws && ws.readyState === 1) { + var out = void 0; + try { + var _out = JSON.stringify(obj); + ws.send(_out); + } catch (e) { + console.log('could not stringify settings:', e); + return; + } + } +} + var ws_onerror = function ws_onerror(e) { setTimeout(function () { ws = new WebSocket(wsUrl); @@ -1381,14 +1394,7 @@ var ws_onmessage = function ws_onmessage(msg) { var obj = settings._getData(); obj.event = "connection-reply"; - var out; - try { - out = JSON.stringify(obj); - } catch (e) { - console.log('could not stringify settings:', e); - return; - } - if (ws && ws.readyState === 1) ws.send(out); + sendToWs(obj); } else if (data.event == 'set-setting') { if (settings.getKey(data.setting) !== undefined) { settings.setKey(data.setting, data.value); @@ -1436,14 +1442,7 @@ controlView.on('settings-event', function (key, value) { if (value === undefined) return; var obj = {}; obj[key] = value; - var out; - try { - out = JSON.stringify(obj); - } catch (e) { - console.log('error creating settings JSON', e); - return; - } - if (ws && ws.readyState === 1) ws.send(out); + sendToWs(obj); settings.setKey(key, value); }); @@ -1494,14 +1493,7 @@ settings.on('set', function (data, changedKeys) { if (changedKeys.indexOf('frameWidth') !== -1) { var xTimeBase = Math.max(Math.floor(1000 * (data.frameWidth / 8) / data.sampleRate), 1); settings.setKey('xTimeBase', xTimeBase); - var out; - try { - out = JSON.stringify({ frameWidth: data.frameWidth }); - } catch (e) { - console.log('unable to stringify framewidth', e); - return; - } - if (ws && ws.readyState === 1) ws.send(out); + sendToWs({ frameWidth: data.frameWidth }); } else { worker.postMessage({ event: 'settings', From 98da8640ac9df8fab5cb378f35fdd8e00e571cbb Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 25 Aug 2023 16:02:14 -0500 Subject: [PATCH 076/188] NIT: Scope: refactored setScopeStatus() --- IDE/frontend-dev/scope-src/scope-browser.js | 48 ++++++++++++++++---- IDE/public/scope/js/bundle.js | 50 +++++++++++++++++---- 2 files changed, 82 insertions(+), 16 deletions(-) diff --git a/IDE/frontend-dev/scope-src/scope-browser.js b/IDE/frontend-dev/scope-src/scope-browser.js index b07045f3b..fab3ec81a 100644 --- a/IDE/frontend-dev/scope-src/scope-browser.js +++ b/IDE/frontend-dev/scope-src/scope-browser.js @@ -45,6 +45,10 @@ var channelView = new (require('./ChannelView'))('channelView', [settings]); var belaSocket = io('/IDE'); function sendToWs(obj) { + // do not send frameWidth if we are not receiving data, + // or the server will get confused + if(dataDisabled) + delete obj.frameWidth; if (ws && ws.readyState === 1) { let out; try { @@ -117,16 +121,44 @@ if(!controlDisabled) { var paused = false, oneShot = false; // view events +const kScopeWaiting = 0, kScopeTriggered = 1, kScopePaused = 2, kScopeWaitingOneShot = 3, kScopeDisabled = 4; +function setScopeStatus(status) { + let d = $('#scopeStatus'); + let trigCls = 'scope-status-triggered'; + let waitCls = 'scope-status-waiting'; + d.removeClass(trigCls).removeClass(waitCls); + switch(status) { + case(kScopeWaiting): + d.addClass(waitCls); + d.html('waiting'); + break; + case(kScopeTriggered): + d.addClass(trigCls); + d.html('triggered'); + break; + case(kScopePaused): + d.addClass(waitCls); + d.html('paused'); + break; + case(kScopeWaitingOneShot): + d.addClass(waitCls); + d.html('waiting (one-shot)'); + break; + case(kScopeDisabled): + d.html('DISABLED'); + break; + } +} controlView.on('settings-event', (key, value) => { if (key === 'scopePause'){ if (paused){ paused = false; $('.pause-button').html('Pause plotting'); - $('#scopeStatus').html('waiting'); + setScopeStatus(kScopeWaiting); } else { paused = true; $('.pause-button').html('Resume plotting'); - $('#scopeStatus').removeClass('scope-status-triggered').addClass('scope-status-waiting').html('paused'); + setScopeStatus(kScopePaused); } return; } else if (key === 'scopeOneShot'){ @@ -135,7 +167,7 @@ controlView.on('settings-event', (key, value) => { paused = false; $('#pauseButton').html('pause'); } - $('#scopeStatus').removeClass('scope-status-triggered').addClass('scope-status-waiting').html('waiting (one-shot)'); + setScopeStatus(kScopeWaitingOneShot); } if (value === undefined) return; var obj = {}; @@ -428,7 +460,6 @@ function CPU(data){ let inactiveTimeout = setTimeout(() => { if (!oneShot && !paused) inactiveOverlay.addClass('inactive-overlay-visible'); }, 5000); - let scopeStatus = $('#scopeStatus'); let inactiveOverlay = $('#inactive-overlay'); function triggerStatus(){ @@ -437,13 +468,14 @@ function CPU(data){ if (oneShot){ oneShot = false; paused = true; - $('.pause-button').html('resume'); - scopeStatus.removeClass('scope-status-triggered').addClass('scope-status-waiting').html('paused'); + $('.pause-button').html('Resume plotting'); + setScopeStatus(kScopePaused); } else { - scopeStatus.removeClass('scope-status-waiting').addClass('scope-status-triggered').html('triggered'); + setScopeStatus(kScopeTriggered); if (triggerTimeout) clearTimeout(triggerTimeout); triggerTimeout = setTimeout(() => { - if (!oneShot && !paused) scopeStatus.removeClass('scope-status-triggered').addClass('scope-status-waiting').html('waiting'); + if (!oneShot && !paused) + setScopeStatus(kScopeWaiting); }, 1000); if (inactiveTimeout) clearTimeout(inactiveTimeout); diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index 064d42295..88f3519a5 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -1349,6 +1349,9 @@ var channelView = new (require('./ChannelView'))('channelView', [settings]); var belaSocket = io('/IDE'); function sendToWs(obj) { + // do not send frameWidth if we are not receiving data, + // or the server will get confused + if (dataDisabled) delete obj.frameWidth; if (ws && ws.readyState === 1) { var out = void 0; try { @@ -1419,16 +1422,48 @@ var paused = false, oneShot = false; // view events +var kScopeWaiting = 0, + kScopeTriggered = 1, + kScopePaused = 2, + kScopeWaitingOneShot = 3, + kScopeDisabled = 4; +function setScopeStatus(status) { + var d = $('#scopeStatus'); + var trigCls = 'scope-status-triggered'; + var waitCls = 'scope-status-waiting'; + d.removeClass(trigCls).removeClass(waitCls); + switch (status) { + case kScopeWaiting: + d.addClass(waitCls); + d.html('waiting'); + break; + case kScopeTriggered: + d.addClass(trigCls); + d.html('triggered'); + break; + case kScopePaused: + d.addClass(waitCls); + d.html('paused'); + break; + case kScopeWaitingOneShot: + d.addClass(waitCls); + d.html('waiting (one-shot)'); + break; + case kScopeDisabled: + d.html('DISABLED'); + break; + } +} controlView.on('settings-event', function (key, value) { if (key === 'scopePause') { if (paused) { paused = false; $('.pause-button').html('Pause plotting'); - $('#scopeStatus').html('waiting'); + setScopeStatus(kScopeWaiting); } else { paused = true; $('.pause-button').html('Resume plotting'); - $('#scopeStatus').removeClass('scope-status-triggered').addClass('scope-status-waiting').html('paused'); + setScopeStatus(kScopePaused); } return; } else if (key === 'scopeOneShot') { @@ -1437,7 +1472,7 @@ controlView.on('settings-event', function (key, value) { paused = false; $('#pauseButton').html('pause'); } - $('#scopeStatus').removeClass('scope-status-triggered').addClass('scope-status-waiting').html('waiting (one-shot)'); + setScopeStatus(kScopeWaitingOneShot); } if (value === undefined) return; var obj = {}; @@ -1660,13 +1695,13 @@ function CPU(data) { if (oneShot) { oneShot = false; paused = true; - $('.pause-button').html('resume'); - scopeStatus.removeClass('scope-status-triggered').addClass('scope-status-waiting').html('paused'); + $('.pause-button').html('Resume plotting'); + setScopeStatus(kScopePaused); } else { - scopeStatus.removeClass('scope-status-waiting').addClass('scope-status-triggered').html('triggered'); + setScopeStatus(kScopeTriggered); if (triggerTimeout) clearTimeout(triggerTimeout); triggerTimeout = setTimeout(function () { - if (!oneShot && !paused) scopeStatus.removeClass('scope-status-triggered').addClass('scope-status-waiting').html('waiting'); + if (!oneShot && !paused) setScopeStatus(kScopeWaiting); }, 1000); if (inactiveTimeout) clearTimeout(inactiveTimeout); @@ -1761,7 +1796,6 @@ function CPU(data) { var inactiveTimeout = setTimeout(function () { if (!oneShot && !paused) inactiveOverlay.addClass('inactive-overlay-visible'); }, 5000); - var scopeStatus = $('#scopeStatus'); var inactiveOverlay = $('#inactive-overlay'); From 1e4fefcc30b623b2268a581baac8d6846a1bce4b Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 25 Aug 2023 16:22:45 -0500 Subject: [PATCH 077/188] NIT: Scope: controlsVisibility() --- IDE/frontend-dev/scope-src/ControlView.js | 16 +++++++++------- IDE/public/scope/js/bundle.js | 20 ++++++++++++-------- 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/IDE/frontend-dev/scope-src/ControlView.js b/IDE/frontend-dev/scope-src/ControlView.js index 7545fc813..021967476 100644 --- a/IDE/frontend-dev/scope-src/ControlView.js +++ b/IDE/frontend-dev/scope-src/ControlView.js @@ -12,17 +12,19 @@ class ControlView extends View{ this.addGenericHandlers(); } - toggleControls(){ - if (controls) { - controls = false; - $('#control-panel').addClass('hidden'); - $('.overlay').removeClass('active'); - } else { - controls = true; + controlsVisibility(show) { + controls = show; + if(show) { $('#control-panel').removeClass('hidden'); $('.overlay').addClass('active'); + } else { + $('#control-panel').addClass('hidden'); + $('.overlay').removeClass('active'); } } + toggleControls(){ + this.controlsVisibility(!controls); + } keyHandler(e){ if (e.key === 'Escape') { diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index 88f3519a5..69f4ab396 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -824,18 +824,22 @@ var ControlView = function (_View) { } _createClass(ControlView, [{ - key: 'toggleControls', - value: function toggleControls() { - if (controls) { - controls = false; - $('#control-panel').addClass('hidden'); - $('.overlay').removeClass('active'); - } else { - controls = true; + key: 'controlsVisibility', + value: function controlsVisibility(show) { + controls = show; + if (show) { $('#control-panel').removeClass('hidden'); $('.overlay').addClass('active'); + } else { + $('#control-panel').addClass('hidden'); + $('.overlay').removeClass('active'); } } + }, { + key: 'toggleControls', + value: function toggleControls() { + this.controlsVisibility(!controls); + } }, { key: 'keyHandler', value: function keyHandler(e) { From 846db389b1f6e4f5dae71b575ca16b4bec0ce095 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Fri, 25 Aug 2023 16:23:59 -0500 Subject: [PATCH 078/188] Scope: if dataDisabled, show controls by default and hide some stuff --- IDE/frontend-dev/scope-src/scope-browser.js | 11 ++++++++++- IDE/public/scope/index.html | 2 +- IDE/public/scope/js/bundle.js | 9 ++++++++- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/IDE/frontend-dev/scope-src/scope-browser.js b/IDE/frontend-dev/scope-src/scope-browser.js index fab3ec81a..f012ddd9f 100644 --- a/IDE/frontend-dev/scope-src/scope-browser.js +++ b/IDE/frontend-dev/scope-src/scope-browser.js @@ -10,7 +10,12 @@ if(qsRemoteHost) remoteHost = qsRemoteHost var wsRemote = "ws://" + remoteHost + "/"; var worker = new Worker("js/scope-worker.js"); -if(!dataDisabled) { +if(dataDisabled) { + $('#ide-cpu').hide(); + $('#bela-cpu').hide(); + $('#scopeMouseX').hide(); + $('#scopeMouseY').hide(); +} else { worker.postMessage({ event: 'wsConnect', remote: wsRemote, @@ -38,6 +43,8 @@ var stage = new PIXI.Container(); // views var controlView = new (require('./ControlView'))('scope-controls', [settings]); +if(dataDisabled) + controlView.controlsVisibility(true); var backgroundView = dataDisabled ? {} : new (require('./BackgroundView'))('scopeBG', [settings], renderer); var channelView = new (require('./ChannelView'))('channelView', [settings]); @@ -123,6 +130,8 @@ var paused = false, oneShot = false; // view events const kScopeWaiting = 0, kScopeTriggered = 1, kScopePaused = 2, kScopeWaitingOneShot = 3, kScopeDisabled = 4; function setScopeStatus(status) { + if(dataDisabled) + status = kScopeDisabled; let d = $('#scopeStatus'); let trigCls = 'scope-status-triggered'; let waitCls = 'scope-status-waiting'; diff --git a/IDE/public/scope/index.html b/IDE/public/scope/index.html index 02cc7b4f9..b9f73a1a7 100644 --- a/IDE/public/scope/index.html +++ b/IDE/public/scope/index.html @@ -29,7 +29,7 @@ Bela CPU: Mouse X position: Mouse Y position: - waiting + DISABLED @@ -286,7 +286,7 @@

Channel 1

- +
diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index adec6a894..8d25069e6 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -563,7 +563,7 @@ function ChannelConfig() { this.enabled = 1; } -var channelConfig = [new ChannelConfig()]; +var channelConfig = []; var colours = ['0xff0000', '0x0000ff', '0x00ff00', '0xff8800', '0xff00ff', '0x00ffff', '0x888800', '0xff8888']; var tdGainVal = 1, @@ -716,14 +716,19 @@ var ChannelView = function (_View) { } } else if (numChannels > channelConfig.length) { while (numChannels > channelConfig.length) { - channelConfig.push(new ChannelConfig()); - channelConfig[channelConfig.length - 1].color = colours[(channelConfig.length - 1) % colours.length]; - var el = $('.channel-view-0').clone(true).prop('class', 'channel-view-' + channelConfig.length).appendTo($('.control-section.channel')); + var cf = new ChannelConfig(); + channelConfig.push(cf); + cf.color = this.colors[(channelConfig.length - 1) % this.colors.length]; + var el = $('.channel-view-template').clone(true).prop('class', 'channel-view-' + channelConfig.length).prop('style', '') // remove display: none + .appendTo($('.control-section.channel')); el.find('[data-channel-name]').html('Channel ' + channelConfig.length); el.find('input').each(function () { $(this).data('channel', channelConfig.length - 1); }); - el.find('input[type=color]').val(colours[(channelConfig.length - 1) % colours.length].replace('0x', '#')); + for (var key in cf) { + var prop = el.find('input[data-key=' + key + ']'); + if ('color' === key) prop.val(cf.color.replace('0x', '#'));else prop.val(cf[key]); + } } } this.emit('channelConfig', channelConfig); From ed5367767bcdf2fd7fa7e0a48b3fd23f2bcc534c Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Mon, 4 Sep 2023 13:31:56 -0500 Subject: [PATCH 084/188] Scope: added dark mode. Also slightly changed the blue color (more may need attention). --- IDE/frontend-dev/scope-src/BackgroundView.js | 17 +++++--- IDE/frontend-dev/scope-src/ChannelView.js | 16 +++++++- IDE/frontend-dev/scope-src/scope-browser.js | 13 ++++-- IDE/public/scope/index.html | 7 ++-- IDE/public/scope/js/bundle.js | 43 +++++++++++++++----- 5 files changed, 74 insertions(+), 22 deletions(-) diff --git a/IDE/frontend-dev/scope-src/BackgroundView.js b/IDE/frontend-dev/scope-src/BackgroundView.js index 83ca8e6a6..cb472097f 100644 --- a/IDE/frontend-dev/scope-src/BackgroundView.js +++ b/IDE/frontend-dev/scope-src/BackgroundView.js @@ -5,6 +5,7 @@ class BackgroundView extends View{ constructor(className, models, renderer){ super(className, models); + this.darkMode = models[1].getKey('darkMode'); var saveCanvas = document.getElementById('saveCanvas'); this.canvas = document.getElementById('scopeBG'); saveCanvas.addEventListener('click', () => { @@ -20,7 +21,7 @@ class BackgroundView extends View{ canvas.height = window.innerHeight; var ctx = canvas.getContext('2d'); ctx.rect(0, 0, canvas.width, canvas.height); - ctx.fillStyle="white"; + ctx.fillStyle = this.darkMode ? "black" : "white"; ctx.fill(); //ctx.clearRect(0, 0, canvas.width, canvas.height); @@ -36,11 +37,11 @@ class BackgroundView extends View{ //console.log(xTime); //faint lines - ctx.strokeStyle = '#000000'; - ctx.fillStyle="grey"; + ctx.strokeStyle = this.darkMode ? '#fff' : '#000'; + ctx.fillStyle= this.darkMode ? '#fff' : '#000'; ctx.font = "14px inconsolata"; ctx.textAlign = "center"; - ctx.lineWidth = 0.2; + ctx.lineWidth = this.darkMode ? 1 : 0.2; ctx.setLineDash([]); ctx.beginPath(); ctx.fillText(0, canvas.width/2, canvas.height/2+11); @@ -102,6 +103,7 @@ class BackgroundView extends View{ //dashed lines ctx.beginPath(); ctx.setLineDash([2, 5]); + ctx.lineWidth = this.darkMode ? 0.5 : 0.2; ctx.moveTo(0, canvas.height*3/4); ctx.lineTo(canvas.width, canvas.height*3/4); @@ -142,7 +144,7 @@ class BackgroundView extends View{ var numVlines = 10; //faint lines - ctx.strokeStyle = '#000000'; + ctx.strokeStyle = this.darkMode ? '#fff' : '#000'; ctx.fillStyle="grey"; ctx.font = "14px inconsolata"; ctx.textAlign = "center"; @@ -187,6 +189,11 @@ class BackgroundView extends View{ ctx.stroke(); } + _darkMode(value, data) { + this.darkMode = value; + this.repaintBG(this.models[0].getKey('xTimeBase'), this.models[0]._getData()); + } + __xTimeBase(value, data){ //console.log(value); this.repaintBG(value, data); diff --git a/IDE/frontend-dev/scope-src/ChannelView.js b/IDE/frontend-dev/scope-src/ChannelView.js index a3aeef6cc..e8c3caaab 100644 --- a/IDE/frontend-dev/scope-src/ChannelView.js +++ b/IDE/frontend-dev/scope-src/ChannelView.js @@ -10,7 +10,6 @@ function ChannelConfig(){ } var channelConfig = []; -var colours = ['0xff0000', '0x0000ff', '0x00ff00', '0xff8800', '0xff00ff', '0x00ffff', '0x888800', '0xff8888']; var tdGainVal = 1, tdOffsetVal = 0, tdGainMin = 0.5, tdGainMax = 2, tdOffsetMin = -5, tdOffsetMax = 5; var FFTNGainVal = 1, FFTNOffsetVal = -0.005, FFTNGainMin = 0.5, FFTNGainMax = 2, FFTNOffsetMin = -1, FFTNOffsetMax = 1; @@ -22,6 +21,17 @@ class ChannelView extends View{ constructor(className, models){ super(className, models); + this.darkMode = this.models[1].getKey('darkMode'); + this.colors = [ + '0xff0000', + '0x94d6ff', + '0x00ff00', + '0xff8800', + '0xff00ff', + '0x00ffff', + '0x888800', + '0xff8888' + ]; } // UI events @@ -82,6 +92,10 @@ class ChannelView extends View{ } } + _darkMode(val){ + this.darkMode = val; + } + _numChannels(val){ var numChannels = val; if (numChannels < channelConfig.length){ diff --git a/IDE/frontend-dev/scope-src/scope-browser.js b/IDE/frontend-dev/scope-src/scope-browser.js index e82c69b9d..e8bd97af5 100644 --- a/IDE/frontend-dev/scope-src/scope-browser.js +++ b/IDE/frontend-dev/scope-src/scope-browser.js @@ -9,6 +9,7 @@ let dataDisabled = parseInt(qs.get("dataDisabled")); let forceWebGl = parseInt(qs.get("forceWebGl")); let antialias = parseInt(qs.get("antialias")); let resolution = qs.get("resolution") ? parseInt(qs.get("resolution")) : 1; +let darkMode = qs.get("darkMode") ? parseInt(qs.get("darkMode")) : 0; if(qsRemoteHost) remoteHost = qsRemoteHost @@ -29,6 +30,9 @@ if(dataDisabled) { // models var Model = require('./Model'); var settings = new Model(); +var tabSettings = new Model(); +tabSettings.setKey('darkMode', darkMode); +var allSettings = [ settings, tabSettings ]; // Pixi.js renderer and stage var renderer = PIXI.autoDetectRenderer({ @@ -48,11 +52,11 @@ $('.scopeWrapper').append(renderer.view); var stage = new PIXI.Container(); // views -var controlView = new (require('./ControlView'))('scope-controls', [settings]); +var controlView = new (require('./ControlView'))('scope-controls', allSettings); if(dataDisabled) controlView.controlsVisibility(true); -var backgroundView = dataDisabled ? {} : new (require('./BackgroundView'))('scopeBG', [settings], renderer); -var channelView = new (require('./ChannelView'))('channelView', [settings]); +var backgroundView = dataDisabled ? {} : new (require('./BackgroundView'))('scopeBG', allSettings, renderer); +var channelView = new (require('./ChannelView'))('channelView', allSettings); // main bela socket var belaSocket = io('/IDE'); @@ -191,6 +195,9 @@ controlView.on('settings-event', (key, value) => { $('#pauseButton').html('pause'); } setScopeStatus(kScopeWaitingOneShot); + } else if (key === 'darkMode') { + tabSettings.setKey('darkMode', !tabSettings.getKey('darkMode')); + return; // do not send via websocket } if (value === undefined) return; var obj = {}; diff --git a/IDE/public/scope/index.html b/IDE/public/scope/index.html index f2ec969ad..a398a0ce1 100644 --- a/IDE/public/scope/index.html +++ b/IDE/public/scope/index.html @@ -225,9 +225,10 @@

FFT

Misc

- - - +
+
+
+
diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index 8d25069e6..7fbd37759 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -323,6 +323,7 @@ var BackgroundView = function (_View) { var _this = _possibleConstructorReturn(this, (BackgroundView.__proto__ || Object.getPrototypeOf(BackgroundView)).call(this, className, models)); + _this.darkMode = models[1].getKey('darkMode'); var saveCanvas = document.getElementById('saveCanvas'); _this.canvas = document.getElementById('scopeBG'); saveCanvas.addEventListener('click', function () { @@ -341,7 +342,7 @@ var BackgroundView = function (_View) { canvas.height = window.innerHeight; var ctx = canvas.getContext('2d'); ctx.rect(0, 0, canvas.width, canvas.height); - ctx.fillStyle = "white"; + ctx.fillStyle = this.darkMode ? "black" : "white"; ctx.fill(); //ctx.clearRect(0, 0, canvas.width, canvas.height); @@ -357,11 +358,11 @@ var BackgroundView = function (_View) { //console.log(xTime); //faint lines - ctx.strokeStyle = '#000000'; - ctx.fillStyle = "grey"; + ctx.strokeStyle = this.darkMode ? '#fff' : '#000'; + ctx.fillStyle = this.darkMode ? '#fff' : '#000'; ctx.font = "14px inconsolata"; ctx.textAlign = "center"; - ctx.lineWidth = 0.2; + ctx.lineWidth = this.darkMode ? 1 : 0.2; ctx.setLineDash([]); ctx.beginPath(); ctx.fillText(0, canvas.width / 2, canvas.height / 2 + 11); @@ -418,6 +419,7 @@ var BackgroundView = function (_View) { //dashed lines ctx.beginPath(); ctx.setLineDash([2, 5]); + ctx.lineWidth = this.darkMode ? 0.5 : 0.2; ctx.moveTo(0, canvas.height * 3 / 4); ctx.lineTo(canvas.width, canvas.height * 3 / 4); @@ -459,7 +461,7 @@ var BackgroundView = function (_View) { var numVlines = 10; //faint lines - ctx.strokeStyle = '#000000'; + ctx.strokeStyle = this.darkMode ? '#fff' : '#000'; ctx.fillStyle = "grey"; ctx.font = "14px inconsolata"; ctx.textAlign = "center"; @@ -504,6 +506,12 @@ var BackgroundView = function (_View) { ctx.stroke(); } + }, { + key: '_darkMode', + value: function _darkMode(value, data) { + this.darkMode = value; + this.repaintBG(this.models[0].getKey('xTimeBase'), this.models[0]._getData()); + } }, { key: '__xTimeBase', value: function __xTimeBase(value, data) { @@ -564,7 +572,6 @@ function ChannelConfig() { } var channelConfig = []; -var colours = ['0xff0000', '0x0000ff', '0x00ff00', '0xff8800', '0xff00ff', '0x00ffff', '0x888800', '0xff8888']; var tdGainVal = 1, tdOffsetVal = 0, @@ -593,7 +600,11 @@ var ChannelView = function (_View) { function ChannelView(className, models) { _classCallCheck(this, ChannelView); - return _possibleConstructorReturn(this, (ChannelView.__proto__ || Object.getPrototypeOf(ChannelView)).call(this, className, models)); + var _this = _possibleConstructorReturn(this, (ChannelView.__proto__ || Object.getPrototypeOf(ChannelView)).call(this, className, models)); + + _this.darkMode = _this.models[1].getKey('darkMode'); + _this.colors = ['0xff0000', '0x94d6ff', '0x00ff00', '0xff8800', '0xff00ff', '0x00ffff', '0x888800', '0xff8888']; + return _this; } // UI events @@ -705,6 +716,11 @@ var ChannelView = function (_View) { this.$elements.filterByData('key', 'yOffset').filterByData('channel', i).val(channelConfig[i].yOffset); } } + }, { + key: '_darkMode', + value: function _darkMode(val) { + this.darkMode = val; + } }, { key: '_numChannels', value: function _numChannels(val) { @@ -1323,6 +1339,7 @@ var dataDisabled = parseInt(qs.get("dataDisabled")); var forceWebGl = parseInt(qs.get("forceWebGl")); var antialias = parseInt(qs.get("antialias")); var resolution = qs.get("resolution") ? parseInt(qs.get("resolution")) : 1; +var darkMode = qs.get("darkMode") ? parseInt(qs.get("darkMode")) : 0; if (qsRemoteHost) remoteHost = qsRemoteHost; var wsRemote = "ws://" + remoteHost + "/"; @@ -1342,6 +1359,9 @@ if (dataDisabled) { // models var Model = require('./Model'); var settings = new Model(); +var tabSettings = new Model(); +tabSettings.setKey('darkMode', darkMode); +var allSettings = [settings, tabSettings]; // Pixi.js renderer and stage var renderer = PIXI.autoDetectRenderer({ @@ -1361,10 +1381,10 @@ $('.scopeWrapper').append(renderer.view); var stage = new PIXI.Container(); // views -var controlView = new (require('./ControlView'))('scope-controls', [settings]); +var controlView = new (require('./ControlView'))('scope-controls', allSettings); if (dataDisabled) controlView.controlsVisibility(true); -var backgroundView = dataDisabled ? {} : new (require('./BackgroundView'))('scopeBG', [settings], renderer); -var channelView = new (require('./ChannelView'))('channelView', [settings]); +var backgroundView = dataDisabled ? {} : new (require('./BackgroundView'))('scopeBG', allSettings, renderer); +var channelView = new (require('./ChannelView'))('channelView', allSettings); // main bela socket var belaSocket = io('/IDE'); @@ -1503,6 +1523,9 @@ controlView.on('settings-event', function (key, value) { $('#pauseButton').html('pause'); } setScopeStatus(kScopeWaitingOneShot); + } else if (key === 'darkMode') { + tabSettings.setKey('darkMode', !tabSettings.getKey('darkMode')); + return; // do not send via websocket } if (value === undefined) return; var obj = {}; From ed718ac6070c223b04ca45fe6c0b34addd52df99 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Mon, 4 Sep 2023 13:56:13 -0500 Subject: [PATCH 085/188] Scope: added showLabels --- IDE/frontend-dev/scope-src/BackgroundView.js | 18 ++++++++++++++---- IDE/frontend-dev/scope-src/scope-browser.js | 5 +++++ IDE/public/scope/index.html | 1 + IDE/public/scope/js/bundle.js | 20 ++++++++++++++++---- 4 files changed, 36 insertions(+), 8 deletions(-) diff --git a/IDE/frontend-dev/scope-src/BackgroundView.js b/IDE/frontend-dev/scope-src/BackgroundView.js index cb472097f..d2812e1c4 100644 --- a/IDE/frontend-dev/scope-src/BackgroundView.js +++ b/IDE/frontend-dev/scope-src/BackgroundView.js @@ -6,6 +6,7 @@ class BackgroundView extends View{ constructor(className, models, renderer){ super(className, models); this.darkMode = models[1].getKey('darkMode'); + this.showLabels = models[1].getKey('showLabels'); var saveCanvas = document.getElementById('saveCanvas'); this.canvas = document.getElementById('scopeBG'); saveCanvas.addEventListener('click', () => { @@ -44,7 +45,8 @@ class BackgroundView extends View{ ctx.lineWidth = this.darkMode ? 1 : 0.2; ctx.setLineDash([]); ctx.beginPath(); - ctx.fillText(0, canvas.width/2, canvas.height/2+11); + if(this.showLabels) + ctx.fillText(0, canvas.width/2, canvas.height/2+11); for (var i=1; i { } else if (key === 'darkMode') { tabSettings.setKey('darkMode', !tabSettings.getKey('darkMode')); return; // do not send via websocket + } else if (key === 'showLabels') { + tabSettings.setKey('showLabels', !tabSettings.getKey('showLabels')); + return; // do not send via websocket } if (value === undefined) return; var obj = {}; diff --git a/IDE/public/scope/index.html b/IDE/public/scope/index.html index a398a0ce1..698924de9 100644 --- a/IDE/public/scope/index.html +++ b/IDE/public/scope/index.html @@ -226,6 +226,7 @@

FFT

Misc


+



diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index 7fbd37759..cb9661112 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -324,6 +324,7 @@ var BackgroundView = function (_View) { var _this = _possibleConstructorReturn(this, (BackgroundView.__proto__ || Object.getPrototypeOf(BackgroundView)).call(this, className, models)); _this.darkMode = models[1].getKey('darkMode'); + _this.showLabels = models[1].getKey('showLabels'); var saveCanvas = document.getElementById('saveCanvas'); _this.canvas = document.getElementById('scopeBG'); saveCanvas.addEventListener('click', function () { @@ -365,16 +366,16 @@ var BackgroundView = function (_View) { ctx.lineWidth = this.darkMode ? 1 : 0.2; ctx.setLineDash([]); ctx.beginPath(); - ctx.fillText(0, canvas.width / 2, canvas.height / 2 + 11); + if (this.showLabels) ctx.fillText(0, canvas.width / 2, canvas.height / 2 + 11); for (var i = 1; i < numVLines; i++) { ctx.moveTo(canvas.width / 2 + i * xPixels, 0); ctx.lineTo(canvas.width / 2 + i * xPixels, canvas.height); var val = i * mspersample; if (val < 10) val = val.toFixed(2);else if (val < 100) val = val.toFixed(1);else val = val.toFixed(0); - ctx.fillText(val, canvas.width / 2 + i * xPixels, canvas.height / 2 + 11); + if (this.showLabels) ctx.fillText(val, canvas.width / 2 + i * xPixels, canvas.height / 2 + 11); ctx.moveTo(canvas.width / 2 - i * xPixels, 0); ctx.lineTo(canvas.width / 2 - i * xPixels, canvas.height); - ctx.fillText("-" + val, canvas.width / 2 - i * xPixels, canvas.height / 2 + 11); + if (this.showLabels) ctx.fillText("-" + val, canvas.width / 2 - i * xPixels, canvas.height / 2 + 11); } var numHLines = 6; @@ -482,7 +483,7 @@ var BackgroundView = function (_View) { val = (Math.pow(Math.E, -Math.log(1 / window.innerWidth) * i / numVlines) * (this.models[0].getKey('sampleRate') / (2 * window.innerWidth)) * (data.upSampling / data.downSampling)).toFixed(0); } - ctx.fillText(val, i * window.innerWidth / numVlines, canvas.height - 2); + if (this.showLabels) ctx.fillText(val, i * window.innerWidth / numVlines, canvas.height - 2); } } @@ -506,6 +507,12 @@ var BackgroundView = function (_View) { ctx.stroke(); } + }, { + key: '_showLabels', + value: function _showLabels(value, data) { + this.showLabels = value; + this.repaintBG(this.models[0].getKey('xTimeBase'), this.models[0]._getData()); + } }, { key: '_darkMode', value: function _darkMode(value, data) { @@ -1340,6 +1347,7 @@ var forceWebGl = parseInt(qs.get("forceWebGl")); var antialias = parseInt(qs.get("antialias")); var resolution = qs.get("resolution") ? parseInt(qs.get("resolution")) : 1; var darkMode = qs.get("darkMode") ? parseInt(qs.get("darkMode")) : 0; +var showLabels = qs.get("showLabels") ? parseInt(qs.get("showLabels")) : 0; if (qsRemoteHost) remoteHost = qsRemoteHost; var wsRemote = "ws://" + remoteHost + "/"; @@ -1361,6 +1369,7 @@ var Model = require('./Model'); var settings = new Model(); var tabSettings = new Model(); tabSettings.setKey('darkMode', darkMode); +tabSettings.setKey('showLabels', showLabels); var allSettings = [settings, tabSettings]; // Pixi.js renderer and stage @@ -1526,6 +1535,9 @@ controlView.on('settings-event', function (key, value) { } else if (key === 'darkMode') { tabSettings.setKey('darkMode', !tabSettings.getKey('darkMode')); return; // do not send via websocket + } else if (key === 'showLabels') { + tabSettings.setKey('showLabels', !tabSettings.getKey('showLabels')); + return; // do not send via websocket } if (value === undefined) return; var obj = {}; From 291d2353150057df09e650089b6f5de4f0a74a8f Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Mon, 4 Sep 2023 13:57:12 -0500 Subject: [PATCH 086/188] Scope: changed default lineWidth --- IDE/frontend-dev/scope-src/ChannelView.js | 2 +- IDE/public/scope/js/bundle.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/IDE/frontend-dev/scope-src/ChannelView.js b/IDE/frontend-dev/scope-src/ChannelView.js index e8c3caaab..9aed8829b 100644 --- a/IDE/frontend-dev/scope-src/ChannelView.js +++ b/IDE/frontend-dev/scope-src/ChannelView.js @@ -5,7 +5,7 @@ function ChannelConfig(){ this.yAmplitude = 1; this.yOffset = 0; this.color = '0xff0000'; - this.lineWeight = 1.5; + this.lineWeight = 5; this.enabled = 1; } diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index cb9661112..d03bdf71b 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -574,7 +574,7 @@ function ChannelConfig() { this.yAmplitude = 1; this.yOffset = 0; this.color = '0xff0000'; - this.lineWeight = 1.5; + this.lineWeight = 5; this.enabled = 1; } From 28a28733615982de1bd1734534f5bb5640fab799 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Mon, 4 Sep 2023 14:32:36 -0500 Subject: [PATCH 087/188] Scope: default to showLabels --- IDE/frontend-dev/scope-src/scope-browser.js | 2 +- IDE/public/scope/js/bundle.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/IDE/frontend-dev/scope-src/scope-browser.js b/IDE/frontend-dev/scope-src/scope-browser.js index 055b45b30..f715a8797 100644 --- a/IDE/frontend-dev/scope-src/scope-browser.js +++ b/IDE/frontend-dev/scope-src/scope-browser.js @@ -10,7 +10,7 @@ let forceWebGl = parseInt(qs.get("forceWebGl")); let antialias = parseInt(qs.get("antialias")); let resolution = qs.get("resolution") ? parseInt(qs.get("resolution")) : 1; let darkMode = qs.get("darkMode") ? parseInt(qs.get("darkMode")) : 0; -let showLabels = qs.get("showLabels") ? parseInt(qs.get("showLabels")) : 0; +let showLabels = qs.get("showLabels") ? parseInt(qs.get("showLabels")) : 1; if(qsRemoteHost) remoteHost = qsRemoteHost diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index d03bdf71b..720fd659a 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -1347,7 +1347,7 @@ var forceWebGl = parseInt(qs.get("forceWebGl")); var antialias = parseInt(qs.get("antialias")); var resolution = qs.get("resolution") ? parseInt(qs.get("resolution")) : 1; var darkMode = qs.get("darkMode") ? parseInt(qs.get("darkMode")) : 0; -var showLabels = qs.get("showLabels") ? parseInt(qs.get("showLabels")) : 0; +var showLabels = qs.get("showLabels") ? parseInt(qs.get("showLabels")) : 1; if (qsRemoteHost) remoteHost = qsRemoteHost; var wsRemote = "ws://" + remoteHost + "/"; From 42ecd8963c7d730c0919a7055b98a32c2c7b8180 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Mon, 4 Sep 2023 15:18:33 -0500 Subject: [PATCH 088/188] Scope: darkMode toggles a class in which in turns affects some text colors --- IDE/frontend-dev/scope-src/scope-browser.js | 18 +++++++++++++++--- IDE/frontend-dev/scss/_scope.scss | 7 +++++++ IDE/public/css/style.css | 5 +++++ IDE/public/scope/js/bundle.js | 15 ++++++++++++--- 4 files changed, 39 insertions(+), 6 deletions(-) diff --git a/IDE/frontend-dev/scope-src/scope-browser.js b/IDE/frontend-dev/scope-src/scope-browser.js index f715a8797..e3469b6ed 100644 --- a/IDE/frontend-dev/scope-src/scope-browser.js +++ b/IDE/frontend-dev/scope-src/scope-browser.js @@ -32,10 +32,22 @@ if(dataDisabled) { var Model = require('./Model'); var settings = new Model(); var tabSettings = new Model(); -tabSettings.setKey('darkMode', darkMode); -tabSettings.setKey('showLabels', showLabels); var allSettings = [ settings, tabSettings ]; +let toggleDarkMode = () => { + let newState = !tabSettings.getKey('darkMode'); + setDarkMode(newState); +} +let setDarkMode = (newState) => { + tabSettings.setKey('darkMode', newState); + if(newState) + $('body').addClass('darkMode'); + else + $('body').removeClass('darkMode'); +} +setDarkMode(darkMode); +tabSettings.setKey('showLabels', showLabels); + // Pixi.js renderer and stage var renderer = PIXI.autoDetectRenderer({ width: window.innerWidth, @@ -198,7 +210,7 @@ controlView.on('settings-event', (key, value) => { } setScopeStatus(kScopeWaitingOneShot); } else if (key === 'darkMode') { - tabSettings.setKey('darkMode', !tabSettings.getKey('darkMode')); + toggleDarkMode(); return; // do not send via websocket } else if (key === 'showLabels') { tabSettings.setKey('showLabels', !tabSettings.getKey('showLabels')); diff --git a/IDE/frontend-dev/scss/_scope.scss b/IDE/frontend-dev/scss/_scope.scss index 39316d492..173e912b7 100644 --- a/IDE/frontend-dev/scss/_scope.scss +++ b/IDE/frontend-dev/scss/_scope.scss @@ -116,6 +116,10 @@ button.scope-controls { } } +body.darkMode .mini-dropdown select[data-key=plotMode] { + color: white; +} + .number-box[type=number] { border: 0; font-family: inconsolata; @@ -305,6 +309,9 @@ input[type="range"].scope-range-slider { display: inline-block; text-align: right; padding-right: 3px; + body.darkMode & { + color:white; + } } [data-legend-color-box] { diff --git a/IDE/public/css/style.css b/IDE/public/css/style.css index 5427e2eb2..674045dff 100644 --- a/IDE/public/css/style.css +++ b/IDE/public/css/style.css @@ -1995,6 +1995,9 @@ button.scope-controls { display: inline; margin-left: 165px; } +body.darkMode .mini-dropdown select[data-key=plotMode] { + color: white; } + .number-box[type=number] { border: 0; font-family: inconsolata; @@ -2143,6 +2146,8 @@ input[type="range"].scope-range-slider { display: inline-block; text-align: right; padding-right: 3px; } + body.darkMode [data-legend-color-label] { + color: white; } [data-legend-color-box] { width: 12px; diff --git a/IDE/public/scope/js/bundle.js b/IDE/public/scope/js/bundle.js index 720fd659a..2196a069b 100644 --- a/IDE/public/scope/js/bundle.js +++ b/IDE/public/scope/js/bundle.js @@ -1368,10 +1368,19 @@ if (dataDisabled) { var Model = require('./Model'); var settings = new Model(); var tabSettings = new Model(); -tabSettings.setKey('darkMode', darkMode); -tabSettings.setKey('showLabels', showLabels); var allSettings = [settings, tabSettings]; +var toggleDarkMode = function toggleDarkMode() { + var newState = !tabSettings.getKey('darkMode'); + setDarkMode(newState); +}; +var setDarkMode = function setDarkMode(newState) { + tabSettings.setKey('darkMode', newState); + if (newState) $('body').addClass('darkMode');else $('body').removeClass('darkMode'); +}; +setDarkMode(darkMode); +tabSettings.setKey('showLabels', showLabels); + // Pixi.js renderer and stage var renderer = PIXI.autoDetectRenderer({ width: window.innerWidth, @@ -1533,7 +1542,7 @@ controlView.on('settings-event', function (key, value) { } setScopeStatus(kScopeWaitingOneShot); } else if (key === 'darkMode') { - tabSettings.setKey('darkMode', !tabSettings.getKey('darkMode')); + toggleDarkMode(); return; // do not send via websocket } else if (key === 'showLabels') { tabSettings.setKey('showLabels', !tabSettings.getKey('showLabels')); From 78111a88c0bec305034859dbddf15b5318455491 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Mon, 4 Sep 2023 15:35:50 -0500 Subject: [PATCH 089/188] Scope: added apple-specific stuff so it can be visualised full screen on iPad. See https://forum.bela.io/d/2275-bela-gui-as-fullscreen-app-on-ios --- IDE/public/scope/index.html | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/IDE/public/scope/index.html b/IDE/public/scope/index.html index 698924de9..76ddb5ec0 100644 --- a/IDE/public/scope/index.html +++ b/IDE/public/scope/index.html @@ -4,6 +4,11 @@ Bela Oscilloscope + + + + + From bd96fdb61f445ed2a078527aaaf552b994569658 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 5 Sep 2023 18:02:14 +0000 Subject: [PATCH 090/188] default_libpd_render: handle lists/msgs sent to bela_system and execute them with system() --- core/default_libpd_render.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/core/default_libpd_render.cpp b/core/default_libpd_render.cpp index b330091ba..7db191081 100644 --- a/core/default_libpd_render.cpp +++ b/core/default_libpd_render.cpp @@ -573,6 +573,30 @@ void setTrillPrintError() } #endif // BELA_LIBPD_TRILL +static void belaSystem(const char* first, int argc, t_atom* argv) +{ + printf("belaSystem %s, %d\n", first, argc); + std::string cmd = first ? first : ""; + for(size_t n = 0; n < argc; ++n) + { + cmd += " "; + if(libpd_is_float(argv + n)) { + float arg = libpd_get_float(argv + n); + if(arg == (int)arg) + cmd += std::to_string((int)arg); + else + cmd += std::to_string(arg); + } else if(libpd_is_symbol(argv + n)) { + cmd += libpd_get_symbol(argv + n); + } else { + fprintf(stderr, "Error: argument %d of bela_system is not a float or symbol. Command so far: '%s', this will be discarded\n", n, cmd.c_str()); + return; + } + } + printf("system(\"%s\");\n", cmd.c_str()); + system(cmd.c_str()); +} + void Bela_listHook(const char *source, int argc, t_atom *argv) { #ifdef BELA_LIBPD_GUI @@ -615,6 +639,12 @@ void Bela_listHook(const char *source, int argc, t_atom *argv) return; } #endif // BELA_LIBPD_GUI + if(0 == strcmp(source, "bela_system")) + { + printf("list: %d\n", argc); + belaSystem(nullptr, argc, argv); + return; + } } void Bela_messageHook(const char *source, const char *symbol, int argc, t_atom *argv){ #ifdef BELA_LIBPD_MIDI @@ -691,6 +721,10 @@ void Bela_messageHook(const char *source, const char *symbol, int argc, t_atom * dcm.manage(channel, direction, isMessageRate); return; } + if(strcmp(source, "bela_system") == 0){ + printf("msg: %s %d\n", symbol, argc); + belaSystem(symbol, argc, argv); + } if(strcmp(source, "bela_control") == 0){ if(strcmp("stop", symbol) == 0){ rt_printf("bela_control: stop\n"); @@ -1134,6 +1168,7 @@ bool setup(BelaContext *context, void *userData) libpd_bind(gReceiverOutputNames[i].c_str()); libpd_bind("bela_setDigital"); libpd_bind("bela_control"); + libpd_bind("bela_system"); #ifdef BELA_LIBPD_MIDI libpd_bind("bela_setMidi"); #endif // BELA_LIBPD_MIDI From 97b86de0e83b32358016df6220d3c7d35d4923fe Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 7 Sep 2023 12:39:41 -0500 Subject: [PATCH 091/188] Gui: use location.hostname instead of location.host so it works even with non-80 ports --- IDE/public/gui/js/Bela.js | 2 +- IDE/public/gui/js/BelaControl.js | 2 +- IDE/public/gui/js/BelaData.js | 2 +- IDE/public/gui/js/BelaWebSocket.js | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/IDE/public/gui/js/Bela.js b/IDE/public/gui/js/Bela.js index bca86700e..bba75bd8f 100644 --- a/IDE/public/gui/js/Bela.js +++ b/IDE/public/gui/js/Bela.js @@ -2,7 +2,7 @@ import BelaData from './BelaData.js' import BelaControl from './BelaControl.js' export default class Bela { - constructor(ip=location.host) { + constructor(ip=location.hostname) { this.port = 5555 this.addresses = { data: 'gui_data', diff --git a/IDE/public/gui/js/BelaControl.js b/IDE/public/gui/js/BelaControl.js index c4051154e..d6da67cab 100644 --- a/IDE/public/gui/js/BelaControl.js +++ b/IDE/public/gui/js/BelaControl.js @@ -3,7 +3,7 @@ import GuiHandler from './GuiHandler.js' import * as utils from './utils.js' export default class BelaControl extends BelaWebSocket { - constructor(port=5555, address='gui_control', ip=location.host) { + constructor(port=5555, address='gui_control', ip=location.hostname) { super(port, address, ip) this.projectName = null; diff --git a/IDE/public/gui/js/BelaData.js b/IDE/public/gui/js/BelaData.js index 888a80366..6cb4eb0cc 100644 --- a/IDE/public/gui/js/BelaData.js +++ b/IDE/public/gui/js/BelaData.js @@ -1,7 +1,7 @@ import BelaWebSocket from './BelaWebSocket.js' export default class BelaData extends BelaWebSocket { - constructor(port=5555, address='gui_data', ip=location.host) { + constructor(port=5555, address='gui_data', ip=location.hostname) { super(port, address, ip) this.buffers = new Array(); diff --git a/IDE/public/gui/js/BelaWebSocket.js b/IDE/public/gui/js/BelaWebSocket.js index eca2ae44f..7863e4372 100644 --- a/IDE/public/gui/js/BelaWebSocket.js +++ b/IDE/public/gui/js/BelaWebSocket.js @@ -1,5 +1,5 @@ export default class BelaWebSocket { - constructor(port, address, ip = location.host) { + constructor(port, address, ip = location.hostname) { this.port = port; this.address = address; this.ip = ip; From 3aa80f1af2bc6e12055fdea9c64051f53798ae6b Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Sun, 10 Sep 2023 12:30:03 -0500 Subject: [PATCH 092/188] PureData/samples-record: have the behaviour match the comment --- examples/PureData/samples-record/_main.pd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/PureData/samples-record/_main.pd b/examples/PureData/samples-record/_main.pd index e600b1029..6ca499c8c 100644 --- a/examples/PureData/samples-record/_main.pd +++ b/examples/PureData/samples-record/_main.pd @@ -47,7 +47,7 @@ #X obj 790 369 tabwrite~ sample-1; #X obj 945 417 s sampleLength1; #X obj 22 418 phasor~ 1; -#X obj 864 230 delay 200; +#X obj 864 230 delay 3; #X obj 170 387 expr 44100/$f1; #X obj 22 395 *~; #X msg 19 228 read -resize greek-rumba.wav sample-1; From be0500c80bfe95fed49388494717d0e3b288be93 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Wed, 13 Sep 2023 23:54:34 +0000 Subject: [PATCH 093/188] Bela_initRtBackend() --- core/RTAudio.cpp | 46 ++++++++++++++++++++++------------------- include/xenomai_wraps.h | 3 +++ 2 files changed, 28 insertions(+), 21 deletions(-) diff --git a/core/RTAudio.cpp b/core/RTAudio.cpp index b14bb8aab..75683d35f 100644 --- a/core/RTAudio.cpp +++ b/core/RTAudio.cpp @@ -375,27 +375,8 @@ static int setChannelGains(BelaChannelGainArray& cga, int (*cb)(int, float)) return ret; } -int Bela_initAudio(BelaInitSettings *settings, void *userData) +extern "C" void Bela_initRtBackend() { - if(!settings) - return -1; - Bela_setVerboseLevel(settings->verbose); - // Before we go ahead, let's check if Bela is alreadt running: - // check if another real-time thread of the same name is already running. - char command[200]; -#if (XENOMAI_MAJOR == 2) - char pathToXenomaiStat[] = "/proc/xenomai/stat"; -#endif -#if (XENOMAI_MAJOR == 3) - char pathToXenomaiStat[] = "/proc/xenomai/sched/stat"; -#endif - snprintf(command, 199, "grep %s %s", gRTAudioThreadName, pathToXenomaiStat); - int ret = system(command); - if(ret == 0) - { - fprintf(stderr, "Error: Bela is already running in another process. Cannot start.\n"); - return -1; - } #if (XENOMAI_MAJOR == 3) // initialize Xenomai with manual bootstrapping if needed // we cannot trust gXenomaiInited exclusively, in case the caller @@ -408,7 +389,7 @@ int Bela_initAudio(BelaInitSettings *settings, void *userData) // object (a mutex). If it fails with EPERM, Xenomai needs to be initialized // See https://www.xenomai.org/pipermail/xenomai/2019-January/040203.html pthread_mutex_t dummyMutex; - ret = __wrap_pthread_mutex_init(&dummyMutex, NULL); + int ret = __wrap_pthread_mutex_init(&dummyMutex, NULL); if(0 == ret) { if(gRTAudioVerbose) printf("Xenomai was inited by someone else\n"); @@ -431,6 +412,29 @@ int Bela_initAudio(BelaInitSettings *settings, void *userData) } gXenomaiInited = 1; #endif +} +int Bela_initAudio(BelaInitSettings *settings, void *userData) +{ + if(!settings) + return -1; + Bela_setVerboseLevel(settings->verbose); + // Before we go ahead, let's check if Bela is alreadt running: + // check if another real-time thread of the same name is already running. + char command[200]; +#if (XENOMAI_MAJOR == 2) + char pathToXenomaiStat[] = "/proc/xenomai/stat"; +#endif +#if (XENOMAI_MAJOR == 3) + char pathToXenomaiStat[] = "/proc/xenomai/sched/stat"; +#endif + snprintf(command, 199, "grep %s %s", gRTAudioThreadName, pathToXenomaiStat); + int ret = system(command); + if(ret == 0) + { + fprintf(stderr, "Error: Bela is already running in another process. Cannot start.\n"); + return -1; + } + Bela_initRtBackend(); #ifdef XENOMAI_CATCH_MSW struct sigaction sa; sigemptyset(&sa.sa_mask); diff --git a/include/xenomai_wraps.h b/include/xenomai_wraps.h index a9985d87d..1b48a38a0 100644 --- a/include/xenomai_wraps.h +++ b/include/xenomai_wraps.h @@ -51,6 +51,7 @@ ssize_t __wrap_mq_receive(mqd_t mqdes, char *msg_ptr, size_t msg_len, unsigned * int __wrap_mq_send(mqd_t mqdes, const char *msg_ptr, size_t msg_len, unsigned msg_prio); int __wrap_mq_unlink(const char *name); +extern "C" void Bela_initRtBackend(); // Handle difference between posix API of Xenomai 2.6 and Xenomai 3 // Some functions are not wrapped by Xenomai 2.6, so we redefine the __wrap // to the actual POSIX service for Xenomai 2.6 while we simply forward declare @@ -175,9 +176,11 @@ inline int create_and_start_thread(pthread_t* task, const char* taskName, int pr pthread_attr_destroy(&attr); return 0; } + // from xenomai-3/demo/posix/cobalt/xddp-echo.c inline int createXenomaiPipe(const char* portName, size_t poolsz) { + Bela_initRtBackend(); /* * Get a datagram socket to bind to the RT endpoint. Each * endpoint is represented by a port number within the XDDP From a6cbc7e7b3ece30cdb4704b105197b0b7c033984 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 14 Sep 2023 00:03:10 +0000 Subject: [PATCH 094/188] Bela_initRtBackend() using call_once() for thread safety --- core/AuxiliaryTasks.cpp | 14 +------------- core/RTAudio.cpp | 28 ++++++++++++++++------------ 2 files changed, 17 insertions(+), 25 deletions(-) diff --git a/core/AuxiliaryTasks.cpp b/core/AuxiliaryTasks.cpp index fd8c8ca8f..1b16a06e2 100644 --- a/core/AuxiliaryTasks.cpp +++ b/core/AuxiliaryTasks.cpp @@ -8,11 +8,6 @@ #include #endif -#ifdef XENOMAI_SKIN_posix -#include -extern int gXenomaiInited; -#endif - #include "../include/xenomai_wraps.h" using namespace std; @@ -49,14 +44,7 @@ void auxiliaryTaskLoop(void *taskStruct); extern unsigned int gAuxiliaryTaskStackSize; AuxiliaryTask Bela_createAuxiliaryTask(void (*functionToCall)(void* args), int priority, const char *name, void* args) { -#if XENOMAI_MAJOR == 3 - // if a program calls this before xenomai is inited, let's init it here with empty arguments. - if(!gXenomaiInited) - { - fprintf(stderr, "Error: You should call Bela_initAudio() before calling Bela_createAuxiliaryTask()\n"); - return 0; - } -#endif + Bela_initRtBackend() InternalAuxiliaryTask *newTask = (InternalAuxiliaryTask*)malloc(sizeof(InternalAuxiliaryTask)); // Populate the rest of the data structure diff --git a/core/RTAudio.cpp b/core/RTAudio.cpp index 75683d35f..b2fca179b 100644 --- a/core/RTAudio.cpp +++ b/core/RTAudio.cpp @@ -375,14 +375,17 @@ static int setChannelGains(BelaChannelGainArray& cga, int (*cb)(int, float)) return ret; } +#include extern "C" void Bela_initRtBackend() { #if (XENOMAI_MAJOR == 3) - // initialize Xenomai with manual bootstrapping if needed - // we cannot trust gXenomaiInited exclusively, in case the caller - // already initialised Xenomai. - bool xenomaiNeedsInit = false; - if(!gXenomaiInited) { + static std::once_flag flag; + std::call_once(flag, [](){ + // initialize Xenomai with manual bootstrapping if needed + // we cannot trust gXenomaiInited exclusively, in case the caller + // already initialised Xenomai, so first we check if it is + // actually working. + bool xenomaiNeedsInit = false; if(gRTAudioVerbose) printf("Xenomai not explicitly inited\n"); // To figure out if we need to intialize it, attempt to create a Cobalt @@ -404,13 +407,14 @@ extern "C" void Bela_initRtBackend() if(gRTAudioVerbose) printf("Xenomai is in unknown state\n"); } - } - if(xenomaiNeedsInit) { - int argc = 0; - char *const *argv; - xenomai_init(&argc, &argv); - } - gXenomaiInited = 1; + if(xenomaiNeedsInit) { + int argc = 0; + char *const *argv; + xenomai_init(&argc, &argv); + } + // this is no longer requi, but we keep it for backward + gXenomaiInited = 1; + }); #endif } int Bela_initAudio(BelaInitSettings *settings, void *userData) From 03f6fd4adedb4a91fc0f456d8094ff21a1f44697 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 14 Sep 2023 00:04:46 +0000 Subject: [PATCH 095/188] Pipe: start with an actually invalid fd --- core/AuxiliaryTasks.cpp | 2 +- libraries/Pipe/Pipe.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/AuxiliaryTasks.cpp b/core/AuxiliaryTasks.cpp index 1b16a06e2..d7a2f2459 100644 --- a/core/AuxiliaryTasks.cpp +++ b/core/AuxiliaryTasks.cpp @@ -44,7 +44,7 @@ void auxiliaryTaskLoop(void *taskStruct); extern unsigned int gAuxiliaryTaskStackSize; AuxiliaryTask Bela_createAuxiliaryTask(void (*functionToCall)(void* args), int priority, const char *name, void* args) { - Bela_initRtBackend() + Bela_initRtBackend(); InternalAuxiliaryTask *newTask = (InternalAuxiliaryTask*)malloc(sizeof(InternalAuxiliaryTask)); // Populate the rest of the data structure diff --git a/libraries/Pipe/Pipe.cpp b/libraries/Pipe/Pipe.cpp index be8666fe3..0e9f4dd5d 100644 --- a/libraries/Pipe/Pipe.cpp +++ b/libraries/Pipe/Pipe.cpp @@ -14,7 +14,7 @@ bool Pipe::setup(const std::string& pipeName, size_t size, bool newBlockingRt, b { if(fd) cleanup(); - fd = 0; + fd = -1; pipeSize = size; name = "p_" + pipeName; From 02e7dc0e1ed0a46ef5f55ce057d561525f413f0d Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 14 Sep 2023 00:06:15 +0000 Subject: [PATCH 096/188] default_libpd_render: system: avoid unnecessary leading space --- core/default_libpd_render.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/default_libpd_render.cpp b/core/default_libpd_render.cpp index 7db191081..6a0e1c975 100644 --- a/core/default_libpd_render.cpp +++ b/core/default_libpd_render.cpp @@ -579,7 +579,8 @@ static void belaSystem(const char* first, int argc, t_atom* argv) std::string cmd = first ? first : ""; for(size_t n = 0; n < argc; ++n) { - cmd += " "; + if(0 != n || first) + cmd += " "; if(libpd_is_float(argv + n)) { float arg = libpd_get_float(argv + n); if(arg == (int)arg) From f9246f4ef9a99b50e2c8a0f5d2abd455067940fb Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Mon, 9 Oct 2023 13:47:03 -0500 Subject: [PATCH 097/188] IDE: open scope and GUI in a given target, so if it was already opened there it will be there again --- IDE/frontend-dev/src/Views/ToolbarView.js | 22 +++++++++++++++++----- IDE/public/js/bundle.js | 21 ++++++++++++++++----- 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/IDE/frontend-dev/src/Views/ToolbarView.js b/IDE/frontend-dev/src/Views/ToolbarView.js index 507b7f549..7f53ee094 100644 --- a/IDE/frontend-dev/src/Views/ToolbarView.js +++ b/IDE/frontend-dev/src/Views/ToolbarView.js @@ -80,9 +80,22 @@ class ToolbarView extends View { $('[data-toolbar-controltext2]').html(''); }); + let openUrl = (url, evt) => { + // set a target name so that the same tab is used if it was + // previously opened + let target = location.host + "/url"; + if(evt) { + // if a modifier is pressed, then just "open" it and the + // browser will figure out what the modifier means (e.g.: new + // tab vs new window) + if(evt.altKey || evt.ctrlKey || evt.shiftKey || evt.metaKey) + target = undefined; + } + window.open(url, target); + }; $('[data-toolbar-scope]') - .on('click', function(){ - window.open('scope'); + .on('click', function(evt){ + openUrl('scope', evt) }); $('[data-toolbar-gui]') @@ -94,9 +107,8 @@ class ToolbarView extends View { }); $('[data-toolbar-gui]') - .on('click', function(){ - // window.open('gui'); - window.open('gui'); + .on('click', function(evt){ + openUrl('gui', evt); }); } diff --git a/IDE/public/js/bundle.js b/IDE/public/js/bundle.js index a5665675e..25b0c80fe 100644 --- a/IDE/public/js/bundle.js +++ b/IDE/public/js/bundle.js @@ -5111,8 +5111,20 @@ var ToolbarView = function (_View) { $('[data-toolbar-controltext2]').html(''); }); - $('[data-toolbar-scope]').on('click', function () { - window.open('scope'); + var openUrl = function openUrl(url, evt) { + // set a target name so that the same tab is used if it was + // previously opened + var target = location.host + "/url"; + if (evt) { + // if a modifier is pressed, then just "open" it and the + // browser will figure out what the modifier means (e.g.: new + // tab vs new window) + if (evt.altKey || evt.ctrlKey || evt.shiftKey || evt.metaKey) target = undefined; + } + window.open(url, target); + }; + $('[data-toolbar-scope]').on('click', function (evt) { + openUrl('scope', evt); }); $('[data-toolbar-gui]').mouseover(function () { @@ -5121,9 +5133,8 @@ var ToolbarView = function (_View) { $('[data-toolbar-controltext2]').html(''); }); - $('[data-toolbar-gui]').on('click', function () { - // window.open('gui'); - window.open('gui'); + $('[data-toolbar-gui]').on('click', function (evt) { + openUrl('gui', evt); }); return _this; } From 3de8124d296deb6ff21ca4c6487edb01b5f450e0 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Mon, 9 Oct 2023 19:21:26 +0000 Subject: [PATCH 098/188] RTAudio: fixed channel and frame count for Batch --- core/RTAudio.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/RTAudio.cpp b/core/RTAudio.cpp index b2fca179b..6d496cc9d 100644 --- a/core/RTAudio.cpp +++ b/core/RTAudio.cpp @@ -241,12 +241,12 @@ static int initBatch(BelaInitSettings *settings, InternalBelaContext* ctx, const { gBatchParams = codecMode; ctx->audioFrames = settings->periodSize; - ctx->audioInChannels = 12; - ctx->audioOutChannels = 12; + ctx->audioInChannels = 2; + ctx->audioOutChannels = 2; ctx->digitalChannels = 16; ctx->analogInChannels = settings->numAnalogInChannels; ctx->analogOutChannels = settings->numAnalogOutChannels; - ctx->analogFrames = ctx->audioFrames / 2; + ctx->analogFrames = settings->uniformSampleRate ? ctx->audioFrames : ctx->audioFrames / 2; ctx->digitalFrames = ctx->audioFrames; ctx->audioSampleRate = 44100; ctx->digitalSampleRate = ctx->audioSampleRate; From 8014f37d95a692d52106525c72c44fbedffd1fda Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Mon, 9 Oct 2023 23:38:51 +0000 Subject: [PATCH 099/188] Gui: a connection can set itself as active/inactive and the Gui keeps tabs on that. It doesn't do anything with the information yet, but a client can --- libraries/Gui/Gui.cpp | 8 ++++++++ libraries/Gui/Gui.h | 2 ++ 2 files changed, 10 insertions(+) diff --git a/libraries/Gui/Gui.cpp b/libraries/Gui/Gui.cpp index 72b3d9bd7..696dc12e4 100644 --- a/libraries/Gui/Gui.cpp +++ b/libraries/Gui/Gui.cpp @@ -105,6 +105,14 @@ void Gui::ws_onControlData(const std::string& address, const WSServerDetails* id if (event.compare(L"connection-reply") == 0){ if(!wsConnections.count(id)) wsConnections.insert(id); + // by default also set connection as active + if(!wsActiveConnections.count(id)) + wsActiveConnections.insert(id); + } else if(event.compare(L"active") == 0){ + if(!wsActiveConnections.count(id)) + wsActiveConnections.insert(id); + } else if(event.compare(L"inactive") == 0){ + wsActiveConnections.erase(id); } } delete value; diff --git a/libraries/Gui/Gui.h b/libraries/Gui/Gui.h index 31f6455e9..81749e7a2 100644 --- a/libraries/Gui/Gui.h +++ b/libraries/Gui/Gui.h @@ -19,6 +19,7 @@ class Gui std::vector _buffers; std::unique_ptr ws_server; std::set wsConnections; + std::set wsActiveConnections; void ws_connect(const std::string& address, const WSServerDetails* id); void ws_disconnect(const std::string& address, const WSServerDetails* id); @@ -56,6 +57,7 @@ class Gui void cleanup(); size_t numConnections(){ return wsConnections.size(); }; + size_t numActiveConnections(){ return wsActiveConnections.size(); }; // BUFFERS /** From 2ed047a973d4dcd246d576fc37ad68ba9472a959 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 10 Oct 2023 21:17:15 +0000 Subject: [PATCH 100/188] Gui: add a count and ts to incoming data buffers so the user can know whether they have been updated --- IDE/public/gui/js/BelaData.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/IDE/public/gui/js/BelaData.js b/IDE/public/gui/js/BelaData.js index 6cb4eb0cc..5898f845f 100644 --- a/IDE/public/gui/js/BelaData.js +++ b/IDE/public/gui/js/BelaData.js @@ -109,8 +109,11 @@ export default class BelaData extends BelaWebSocket { if(err) return; let idx = this.newBuffer['id']; + let count = this.buffers[idx] && "undefined" !== typeof(this.buffers[idx].count) ? this.buffers[idx].count + 1 : 0; this.buffers[idx] = this.newBuffer['data']; this.buffers[idx].type = type; + this.buffers[idx].count = count; + this.buffers[idx].ts = performance.now(); this.bufferReady = true; this.target.dispatchEvent( new CustomEvent('buffer-ready', { detail: this.newBuffer['id'] }) ); From c374cbcf168c8634522c62b5b0ecef3c3fc28c8c Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 12 Oct 2023 19:39:39 +0000 Subject: [PATCH 101/188] PureData/serial example --- examples/PureData/serial/_main.pd | 41 +++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 examples/PureData/serial/_main.pd diff --git a/examples/PureData/serial/_main.pd b/examples/PureData/serial/_main.pd new file mode 100644 index 000000000..cd57801df --- /dev/null +++ b/examples/PureData/serial/_main.pd @@ -0,0 +1,41 @@ +#N canvas 190 75 1090 589 12; +#X obj 31 350 loadbang; +#X obj 31 398 s bela_setSerial; +#X obj 29 462 route myserial; +#X msg 31 374 new myserial /dev/ttyS4 9600 none bytes; +#X obj 355 486 s bela_serialOut; +#X obj 355 385 metro 1000; +#X obj 355 361 loadbang; +#X obj 403 413 + 1; +#X obj 355 412 f; +#X msg 355 455 myserial \$1 2 3 4 5 6; +#X obj 29 438 r bela_serialIn; +#X obj 29 486 print serialIn; +#X text 73 20 Send a `new` message to bela_setSerial to initialise UART communication. Arguments are:; +#X text 69 50 [new ; +#X text 72 65 Where:; +#X text 82 78 serialId: symbol to use in future communications pertaining this object; +#X text 85 133 bps: a valid baudrate supported by the device; +#X text 85 111 device: path to the serial device; +#X text 85 154 EOM: End Of Message byte \, used to identify boundaries; +#X text 102 168 in incoming messages. Possible values are:; +#X text 101 183 `none` (no message splitting) \, `newline` \, or a float; +#X text 103 198 representing the character code; +#X text 82 216 type: how the data is output from bela_serialIn. Possible; +#X text 101 231 values are:; +#X text 99 263 symbol: convert incoming message string to a symbol; +#X text 100 246 floats: convert incoming message string to a float; +#X text 99 279 symbols: convert incoming data to a symbol ignoring EOM; +#X text 98 294 bytes: convert each incoming byte to a float \, output them; +#X text 98 307 one byte at a time if EOM is none \, or as one list per message; +#X text 442 413 Output raw bytes (that's the only output mode supported right now); +#X connect 0 0 3 0; +#X connect 2 0 11 0; +#X connect 3 0 1 0; +#X connect 5 0 8 0; +#X connect 6 0 5 0; +#X connect 7 0 8 1; +#X connect 8 0 7 0; +#X connect 8 0 9 0; +#X connect 9 0 4 0; +#X connect 10 0 2 0; From ab3c50a427d9968b6d7d8c623600d2c463ae7f88 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 12 Oct 2023 17:55:17 -0500 Subject: [PATCH 102/188] IDE: remove readonly stuff on opening a file --- IDE/frontend-dev/src/IDE-browser.js | 3 ++- IDE/public/js/bundle.js | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/IDE/frontend-dev/src/IDE-browser.js b/IDE/frontend-dev/src/IDE-browser.js index 4bc9170d8..89207b344 100644 --- a/IDE/frontend-dev/src/IDE-browser.js +++ b/IDE/frontend-dev/src/IDE-browser.js @@ -354,7 +354,8 @@ function fileOpenedOrChanged(data, changed) { fileChangedPopup(fileName); else enterReadonlyPopup(fileName); - } + } else + setReadOnlyStatus(false); } // run-on-boot diff --git a/IDE/public/js/bundle.js b/IDE/public/js/bundle.js index 25b0c80fe..8b09f395b 100644 --- a/IDE/public/js/bundle.js +++ b/IDE/public/js/bundle.js @@ -763,7 +763,7 @@ function fileOpenedOrChanged(data, changed) { // and we arenot ignoring it if (project === models.project.getKey('currentProject') && fileName === models.project.getKey('fileName') && clientId != socket.id && !models.project.getKey('openElsewhere') && !models.project.getKey('readOnly')) { if (changed) fileChangedPopup(fileName);else enterReadonlyPopup(fileName); - } + } else setReadOnlyStatus(false); } // run-on-boot From fad556978272d76f08a0c59ebcdfacd7cccf1994 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 12 Oct 2023 17:56:12 -0500 Subject: [PATCH 103/188] IDE: do not refresh the page when reloading the file from the file open in other tab popup Fixes the issue introduced between a4f5bbebc and 361a30cd4d --- IDE/frontend-dev/src/IDE-browser.js | 21 +++++++++++++-------- IDE/public/js/bundle.js | 21 +++++++++++++-------- 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/IDE/frontend-dev/src/IDE-browser.js b/IDE/frontend-dev/src/IDE-browser.js index 89207b344..29ce38ab9 100644 --- a/IDE/frontend-dev/src/IDE-browser.js +++ b/IDE/frontend-dev/src/IDE-browser.js @@ -402,6 +402,16 @@ function setModifiedTimeInterval(mtime){ }, 5000); } +function reopenFile() { + // Not sure how to get the name of the current file without passing it in + // So we actually reopen the project instead. + var data = { + func : 'openProject', + currentProject : models.project.getKey('currentProject'), + timestamp : performance.now() + }; + socket.emit('project-event', data); +} // current file changed var fileChangedPopupVisible = false; function fileChangedPopup(fileName){ @@ -413,13 +423,7 @@ function fileChangedPopup(fileName){ e => { fileChangedPopupVisible = false; e.preventDefault(); - var data = { - func : 'openProject', - currentProject : models.project.getKey('currentProject'), - timestamp : performance.now() - }; - socket.emit('project-event', data); - consoleView.emit('openNotification', data); + reopenFile(); }, () => { fileChangedPopupVisible = false; @@ -466,7 +470,8 @@ function exitReadonlyPopup() { // on Submit: e => { setReadOnlyStatus(false); - window.location.reload(); + e.preventDefault(); + reopenFile(); }, // on Cancel: () => { diff --git a/IDE/public/js/bundle.js b/IDE/public/js/bundle.js index 8b09f395b..d2e0ae943 100644 --- a/IDE/public/js/bundle.js +++ b/IDE/public/js/bundle.js @@ -823,6 +823,16 @@ function setModifiedTimeInterval(mtime) { }, 5000); } +function reopenFile() { + // Not sure how to get the name of the current file without passing it in + // So we actually reopen the project instead. + var data = { + func: 'openProject', + currentProject: models.project.getKey('currentProject'), + timestamp: performance.now() + }; + socket.emit('project-event', data); +} // current file changed var fileChangedPopupVisible = false; function fileChangedPopup(fileName) { @@ -833,13 +843,7 @@ function fileChangedPopup(fileName) { popup.twoButtons(strings, function (e) { fileChangedPopupVisible = false; e.preventDefault(); - var data = { - func: 'openProject', - currentProject: models.project.getKey('currentProject'), - timestamp: performance.now() - }; - socket.emit('project-event', data); - consoleView.emit('openNotification', data); + reopenFile(); }, function () { fileChangedPopupVisible = false; editorView.emit('upload', editorView.getData()); @@ -883,7 +887,8 @@ function exitReadonlyPopup() { // on Submit: function (e) { setReadOnlyStatus(false); - window.location.reload(); + e.preventDefault(); + reopenFile(); }, // on Cancel: function () { From 6ca640f67cae1d7d640399899aa2637dbf0c6b18 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 19 Oct 2023 16:20:35 +0000 Subject: [PATCH 104/188] Gui: erase active connection on disconnect --- libraries/Gui/Gui.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/libraries/Gui/Gui.cpp b/libraries/Gui/Gui.cpp index 696dc12e4..463ec1fd4 100644 --- a/libraries/Gui/Gui.cpp +++ b/libraries/Gui/Gui.cpp @@ -77,8 +77,9 @@ void Gui::ws_connect(const std::string& address, const WSServerDetails* id) */ void Gui::ws_disconnect(const std::string& address, const WSServerDetails* id) { - if(wsConnections.count(id)) - wsConnections.erase(id); + for(auto& wsc : {&wsConnections, &wsActiveConnections}) + if(wsc->count(id)) + wsc->erase(id); } /* From bcf6e57b98e709b5ac289455d3e0787300222583 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Sun, 10 Jul 2022 16:15:04 +0000 Subject: [PATCH 105/188] Makefile: removed wheezy support --- Makefile | 25 ------------------------- 1 file changed, 25 deletions(-) diff --git a/Makefile b/Makefile index 081f31dac..5d8058c75 100644 --- a/Makefile +++ b/Makefile @@ -255,7 +255,6 @@ XENOMAI_STAT_PATH=/proc/xenomai/sched/stat endif # This is used to run Bela projects from the terminal in the background -# On wheezy, it is also used for running Bela at startup SCREEN_NAME?=Bela # These are parsed by the IDE to understand if a program is active at startup @@ -263,21 +262,6 @@ BELA_STARTUP_ENV?=/opt/Bela/startup_env BELA_POST_ENABLE_STARTUP_COMMAND=mkdir -p /opt/Bela && printf "ACTIVE=1\nPROJECT=$(PROJECT)\nARGS=$(COMMAND_LINE_OPTIONS)" > $(BELA_STARTUP_ENV) BELA_PRE_DISABLE_STARTUP_COMMAND=mkdir -p /opt/Bela && printf "ACTIVE=0\n" > $(BELA_STARTUP_ENV) -ifeq ($(DEBIAN_VERSION), wheezy) -# this section contains some hardcoded and/or obsolete variables. It is currently unsupported and deprecated and we'll remove it "soon" (GM said on 2021.06.09) -BELA_IDE_HOME?=$(BELA_DIR)/IDE -BELA_IDE_SCREEN_NAME?=IDE-Bela -BELA_IDE_STARTUP_SCRIPT?=/root/Bela_node.sh -BELA_STARTUP_SCRIPT?=/root/Bela_startup.sh -BELA_ENABLE_STARTUP_COMMAND=printf "\#!/bin/sh\n\#\n\# This file is autogenerated by Bela. Do not edit!\n\necho Running Bela...\nexport PATH=\"$$PATH:/usr/local/bin\"\n cd $(RUN_FROM) && screen -S $(SCREEN_NAME) -d -m bash -c \"while sleep 0.6 ; do echo Running Bela...; $(RUN_COMMAND); done\"\n" > $(BELA_STARTUP_SCRIPT) && chmod +x $(BELA_STARTUP_SCRIPT) && $(BELA_POST_ENABLE_STARTUP_COMMAND) - -BELA_DISABLE_STARTUP_COMMAND=$(BELA_PRE_DISABLE_STARTUP_COMMAND); printf "\#!/bin/sh\n\#\n\n\# This file is autogenerated by Bela. Do not edit!\n\n\# Run on startup disabled -- nothing to do here\n" > $(BELA_STARTUP_SCRIPT) -BELA_IDE_START_COMMAND?=cd $(BELA_IDE_HOME) && export USER=root && export HOME=/root && export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin && screen -S $(BELA_IDE_SCREEN_NAME) -d -m bash -c "while true; do /usr/local/bin/node index.js; sleep 0.5; done" -BELA_IDE_STOP_COMMAND?=screen -X -S $(BELA_IDE_SCREEN_NAME) quit > /dev/null || true -BELA_IDE_ENABLE_STARTUP_COMMAND?=printf '\#!/bin/sh\n\#\n\# This file is autogenerated by Bela. Do not edit!\n\necho Running the Bela IDE...\n$(BELA_IDE_START_COMMAND)\n' > $(BELA_IDE_STARTUP_SCRIPT) -BELA_IDE_DISABLE_STARTUP_COMMAND?=printf "#!/bin/sh\n#\n\n# This file is autogenerated by Bela. Do not edit!\n\n# The Bela IDE is disabled on startup.\n" > $(BELA_IDE_STARTUP_SCRIPT) -BELA_IDE_CONNECT_COMMAND=screen -r -S $(BELA_IDE_SCREEN_NAME) -else BELA_ENABLE_STARTUP_COMMAND=systemctl enable bela_startup && $(BELA_POST_ENABLE_STARTUP_COMMAND) BELA_DISABLE_STARTUP_COMMAND=$(BELA_PRE_DISABLE_STARTUP_COMMAND); systemctl disable bela_startup BELA_IDE_START_COMMAND=systemctl restart bela_ide @@ -285,7 +269,6 @@ BELA_IDE_STOP_COMMAND=systemctl stop bela_ide BELA_IDE_ENABLE_STARTUP_COMMAND=systemctl enable bela_ide BELA_IDE_DISABLE_STARTUP_COMMAND=systemctl disable bela_ide BELA_IDE_CONNECT_COMMAND=journalctl -fu bela_ide -n 50 -endif SC_CL?=-u 57110 -z 16 -J 8 -K 8 -G 16 -i 2 -o 2 -B 0.0.0.0 ifneq (,$(filter $(QUIET_TARGETS),$(MAKECMDGOALS))) @@ -636,9 +619,7 @@ startup: ## Same as startuploop startup: startuploop # compatibility only stopstartup: ## stop the system service that ran Bela at startup -ifneq ($(DEBIAN_VERSION),wheezy) $(AT) systemctl stop bela_startup || true -endif stoprunning: ## Stops a Bela program that is currently running $(AT) PID=`grep $(BELA_AUDIO_THREAD_NAME) $(XENOMAI_STAT_PATH) | cut -d " " -f 5 | sed s/\s//g`; if [ -z $$PID ]; then [ $(QUIET) = true ] || echo "No process to kill"; else [ $(QUIET) = true ] || echo "Killing old Bela process $$PID"; kill -2 $$PID; sleep 0.2; kill -9 $$PID 2> /dev/null; fi; screen -X -S $(SCREEN_NAME) quit > /dev/null; exit 0; @@ -655,19 +636,13 @@ endif stop: ## Stops any system service and Bela program that is currently running stop: stopstartup stoprunning -ifneq ($(DEBIAN_VERSION),wheezy) connect_startup: ## Connects to Bela program running at startup $(AT) journalctl -fu bela_startup -n 30 -endif connect: ## Connects to the running Bela program (if any), can detach with ctrl-a ctrl-d. $(AT) screen -r -S $(SCREEN_NAME) idestart: ## Starts the on-board IDE -ifeq ($(DEBIAN_VERSION),wheezy) -# when using systemctl, idestart does not require idestop. -idestart: idestop -endif $(AT) printf "Starting IDE..." $(AT) $(BELA_IDE_START_COMMAND) $(AT) printf "done\n" From 2e98557b79c6acd61dc2df2abc137189d08c3cd4 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Sun, 10 Jul 2022 16:15:57 +0000 Subject: [PATCH 106/188] resources: removed wheezy support --- .../deb/libmathneon-dev_1.0.2-1_armhf.deb | 1 - .../deb/libne10-dev_20181116-1_armhf.deb | 1 - ...xenomai-2.6-dev_0.10.1-xenomai-1_armhf.deb | Bin 313018 -> 0 bytes .../deb/libseasocks-dev_20171012-1_armhf.deb | Bin 456352 -> 0 bytes .../wheezy/dtb/BB-BONE-BAREAUDI-00A0.dtbo | Bin 1371 -> 0 bytes .../wheezy/dtb/BB-BONE-BAREAUDI-02-00A0.dts | 76 - .../wheezy/dtb/BB-BONE-PRU-BELA-00A0.dts | 59 - resources/wheezy/dtb/am335x-boneblack.dtb | Bin 23787 -> 0 bytes resources/wheezy/dtb/am335x-boneblack.dts | 1251 ----------------- resources/wheezy/dtb/am335x-bonegreen.dtb | Bin 23787 -> 0 bytes resources/wheezy/dtb/am335x-bonegreen.dts | 1251 ----------------- resources/wheezy/include/prussdrv.h | 203 --- resources/wheezy/sh/Bela_capeButtonHold.sh | 5 - resources/wheezy/sh/initd-bela | 28 - .../wheezy/sh/initd-bela_shutdown_switch | 65 - resources/wheezy/sh/shutdown_switch.sh | 79 -- 16 files changed, 3019 deletions(-) delete mode 120000 resources/wheezy/deb/libmathneon-dev_1.0.2-1_armhf.deb delete mode 120000 resources/wheezy/deb/libne10-dev_20181116-1_armhf.deb delete mode 100644 resources/wheezy/deb/libpd-xenomai-2.6-dev_0.10.1-xenomai-1_armhf.deb delete mode 100644 resources/wheezy/deb/libseasocks-dev_20171012-1_armhf.deb delete mode 100644 resources/wheezy/dtb/BB-BONE-BAREAUDI-00A0.dtbo delete mode 100644 resources/wheezy/dtb/BB-BONE-BAREAUDI-02-00A0.dts delete mode 100644 resources/wheezy/dtb/BB-BONE-PRU-BELA-00A0.dts delete mode 100755 resources/wheezy/dtb/am335x-boneblack.dtb delete mode 100755 resources/wheezy/dtb/am335x-boneblack.dts delete mode 100644 resources/wheezy/dtb/am335x-bonegreen.dtb delete mode 100644 resources/wheezy/dtb/am335x-bonegreen.dts delete mode 100644 resources/wheezy/include/prussdrv.h delete mode 100755 resources/wheezy/sh/Bela_capeButtonHold.sh delete mode 100755 resources/wheezy/sh/initd-bela delete mode 100755 resources/wheezy/sh/initd-bela_shutdown_switch delete mode 100755 resources/wheezy/sh/shutdown_switch.sh diff --git a/resources/wheezy/deb/libmathneon-dev_1.0.2-1_armhf.deb b/resources/wheezy/deb/libmathneon-dev_1.0.2-1_armhf.deb deleted file mode 120000 index 422e564b2..000000000 --- a/resources/wheezy/deb/libmathneon-dev_1.0.2-1_armhf.deb +++ /dev/null @@ -1 +0,0 @@ -../../stretch/deb/libmathneon-dev_1.0.2-1_armhf.deb \ No newline at end of file diff --git a/resources/wheezy/deb/libne10-dev_20181116-1_armhf.deb b/resources/wheezy/deb/libne10-dev_20181116-1_armhf.deb deleted file mode 120000 index 085ddab6f..000000000 --- a/resources/wheezy/deb/libne10-dev_20181116-1_armhf.deb +++ /dev/null @@ -1 +0,0 @@ -../../stretch/deb/libne10-dev_20181116-1_armhf.deb \ No newline at end of file diff --git a/resources/wheezy/deb/libpd-xenomai-2.6-dev_0.10.1-xenomai-1_armhf.deb b/resources/wheezy/deb/libpd-xenomai-2.6-dev_0.10.1-xenomai-1_armhf.deb deleted file mode 100644 index 27af26cadeb25a70fa11011f5d5e3eea4c0fdff1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 313018 zcmagEQ?Muu%p`bh+qP}n_PNKlZQHhO+qP}n_I&@;>^yDlcBN8DRr1vR)CnPvfuoT* zAC$3)p@o4ht)Ydjfujcj0RbZ`BQrY_6FVy-0Rh8*{r{6085r1DSO^IIi~j?CC?+}v zC?h*tXGc40I%fk%Iy2Az|9xgo=Ks5o9|ZyMKL7!~S=zA-Vn6}6uk(p~0@7OgR5Xr; z1>2&73K_g@!mui5B`q!4S)$j{YSnF4AJq60jKJdI{Ea2Y@d%0=kD-z5wsk#nyv=Kv zNH0MiO{8(U(i~-qOB`T!!nW3)f=w`MZe4rrYVp0<;qOL^4YsXbc=6|S1(iE`Z@ex0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1j^WPEQ zX^@Og3)Tm@=X5`|VH>kI|3dJmlz>@!wfY#U!)^h_+hr=hyfBgnfv>dw$Q76R$j{C{ z42eshHFncN$Cb~wtm6rVsq0Y&MtQ;}p9w=!tF(vOv~zg559P_Ap6!%cumDcC>i3@T zL}By<(YV_{tBGu$0hVb>)wWe5YqfSz_4}?HiC@-vw+Z;PFg4Io1w!IU$uJdS%|+8|1fx6 zfpYRMR$*UlF;t0$YJ~?CB^`?}~ow6VqZ)Ge$Tw>tEDJaRtJxJf(UMn@M|wP}F+&sKIyZ%}}YOcYTZdE6lj+ z`Kvl$wT&@My@ZEI{eFs@8$s(ldX~dSUP5Qp&gP0f2KU(6-XafbeGno{N63uin<~|Q zkKHmDpL6;36IXx2cL<*>_f_mDDS|~kE%l&rkWlK@P!t`4mgV=PT+rma+0E)~`$^v2 zYVSMhcZ{%f^`9!*pp&3!oQz$?W0e%P;HJ-jv$6W*KdSADW=*N)IJxN;poP{T zy-hTs{aQ@h>Vj+5#`CuZjY=^Du&~l+jF$aOi>y)Rocd}D5`^ClNOwyhQ|`;s9e?|I zF4=7f3Vt8eULSHQQ9P6&<{iBh-z0++}|AIUFt07L+g zMYEw^YsFyG;nZ2Wt~*+ML%!LMN~dy%hkMjHdS> zKj(3@&^p%VP&|7JSb#g!FI~&%+x(kpi$#fjA;pM?S})c0*Rpv%KrA@79Gq4QKT&tO z#aGUBaUe(Ui3DiV6=}CEUswMWF;bTpfZhMld&&dEHkh)drX#li0Ax5ntN;Pbh!cRI UDK$35Yd$ayivj=u00045S_&70ZU6uP diff --git a/resources/wheezy/deb/libseasocks-dev_20171012-1_armhf.deb b/resources/wheezy/deb/libseasocks-dev_20171012-1_armhf.deb deleted file mode 100644 index 0628cfc0884cef4545a2473412d8192521592190..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 456352 zcmagFQ>-vd(51U=+qP}ndbe%cwr$(CZQHhO<9ugk{<)o%PN(aluAZcNrBX%6W8i3H z&Ie^|VrX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dzE+E_3qaF zC#7rjVusK;S_f=YCax**+SODov=nTj_8*XxAE#a3wJd3?{eZZPgf?Mbf6#l(= zq={@CjbQ&O-4R^l12+pN75}kaNY(4^2{36ej!k&Hh#sq$aLbDd7y2$p5%3ETjIPo9 zXSQs=3--W8qNNnO2z?buS^{}D*~bjdaoUY4U=b^>j7H$Hw{%Y^>)LZLoL zO4W{`R-lv$nJd|BNd(qdp)p7(%rJOfo!Lat#8XW)p?8TRt%j8%4!u|u$lFaQ^)2Wm zS75&aLec^VSTzxq2`k!R4Nr`mf?`!&(FO8RG{KA4KBp5~5788NX9m`hbO8M&V?$+n z9BbSWm-*PjhPw`8$kc>?7m44K-Tg)a13QKG8vDq#es6t~$h@rxDj4i{-9W4f_CS>~ zI_4Da+K-WGB5?geuFmJ5y3{s|>#IdcKxC3^KOTlUvq+0bcwdlOL7X{9*Syz?(!_~0 zq1_HpHYAArHzr_~;7%^^{}j`Fbc%Q%H}x4xHv?d{#7e3>MWRO5Oy%l(FDhF9OFLNX zFXr9NM9^U>J;kRdtg!&<9?>iMDwh59kG%c~s$sutjuO28 zD}#00Ua$Xx9Rx4%kOKmjPd1RtH*{1n(z}3Vmk9K|1K~it6iS|f7IMSP8+z%W&tOrn zpq;~6)>$APoZ{J0Bw~p;8EY(Sa=1UZ@-HkR65T?FLHQ29ZumajySf#PE-YEZVcT$2 zo8P!NycyPULZpIvF2u>suz`*$XaQ5g&I?4-yJvo6$$3lUd-@nJBqk&U-^(%zy{>(>>wH`bmUs%dMO9D`eiyk>

From 69bd93ecc9e2093138881b4220596b05a6d33651 Mon Sep 17 00:00:00 2001 From: Laimonade Date: Tue, 30 Jan 2024 23:37:38 +0000 Subject: [PATCH 168/188] implemented callback to switch code editor theme --- IDE/public/js/bundle.js | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/IDE/public/js/bundle.js b/IDE/public/js/bundle.js index d2e0ae943..acda4b13a 100644 --- a/IDE/public/js/bundle.js +++ b/IDE/public/js/bundle.js @@ -417,7 +417,7 @@ settingsView.on('project-settings', function (data) { settingsView.on('IDE-settings', function (data) { data.currentProject = models.project.getKey('currentProject'); - //console.log('IDE-settings', data); + // console.log('IDE-settings', data); socket.emit('IDE-settings', data); }); settingsView.on('run-on-boot', function (project) { @@ -2179,9 +2179,20 @@ var EditorView = function (_View) { this.__focus(opts.focus); } } - // editor focus has changed + // editor theme has changed }, { + key: '_darkTheme', + value: function _darkTheme(value) { + if (parseInt(value)) { + this.editor.setTheme("ace/theme/xcode_dark"); + } else { + this.editor.setTheme("ace/theme/chrome"); + } + } + // editor focus has changed + + }, { key: '__focus', value: function __focus(data) { From 33d3ecf1777d1a527a9154f89321fe1ea104ee44 Mon Sep 17 00:00:00 2001 From: Laimonade Date: Tue, 30 Jan 2024 23:53:57 +0000 Subject: [PATCH 169/188] implemented callback to switch code editor theme --- IDE/public/js/bundle.js | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/IDE/public/js/bundle.js b/IDE/public/js/bundle.js index acda4b13a..b22568c27 100644 --- a/IDE/public/js/bundle.js +++ b/IDE/public/js/bundle.js @@ -2185,7 +2185,8 @@ var EditorView = function (_View) { key: '_darkTheme', value: function _darkTheme(value) { if (parseInt(value)) { - this.editor.setTheme("ace/theme/xcode_dark"); + // this.editor.setTheme("ace/theme/xcode_dark"); + this.editor.setTheme("ace/theme/monokai"); } else { this.editor.setTheme("ace/theme/chrome"); } @@ -4595,6 +4596,20 @@ var SettingsView = function (_View) { } }); } + // }, { + // key: '_darkTheme', + // value: function _darkTheme(func, key, value) { + // console.log("in _darkTheme") + // var app = document.querySelector(".app"); + // // editor theme has changed + // if (parseInt(func)) { + // app.classList.remove('light'); + // app.classList.add('dark'); + // } else { + // app.classList.remove('dark'); + // app.classList.add('light'); + // } + // } }, { key: '_boardString', value: function _boardString(data) { From 6d14b7c3d754330db3b9332db647ed56ab4980f0 Mon Sep 17 00:00:00 2001 From: Laimonade Date: Wed, 31 Jan 2024 00:00:53 +0000 Subject: [PATCH 170/188] added switchable dark theme to default IDE settings --- IDE/dist/IDESettings.js | 3 ++- IDE/src/IDESettings.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/IDE/dist/IDESettings.js b/IDE/dist/IDESettings.js index 008ab7b2e..1260051ac 100644 --- a/IDE/dist/IDESettings.js +++ b/IDE/dist/IDESettings.js @@ -168,6 +168,7 @@ function default_IDE_settings() { 'cpuMonitoring': 1, 'cpuMonitoringVerbose': 0, 'consoleDelete': 0, - 'viewHiddenFiles': 0 + 'viewHiddenFiles': 0, + 'darkTheme': 0 }; } diff --git a/IDE/src/IDESettings.ts b/IDE/src/IDESettings.ts index cda2a67b9..c6fe04a05 100644 --- a/IDE/src/IDESettings.ts +++ b/IDE/src/IDESettings.ts @@ -71,6 +71,7 @@ function default_IDE_settings(){ 'cpuMonitoring' : 1, 'cpuMonitoringVerbose' : 0, 'consoleDelete' : 0, - 'viewHiddenFiles' : 0 + 'viewHiddenFiles' : 0, + 'darkTheme' : 0 }; } From b66b12c2c8be58bdef0c8d6bb58658a9c03f7d83 Mon Sep 17 00:00:00 2001 From: Laimonade Date: Fri, 2 Feb 2024 02:00:24 +0000 Subject: [PATCH 171/188] implemented css class switch --- IDE/public/js/bundle.js | 31 ++++++++++++------------------- 1 file changed, 12 insertions(+), 19 deletions(-) diff --git a/IDE/public/js/bundle.js b/IDE/public/js/bundle.js index b22568c27..3324b3a1a 100644 --- a/IDE/public/js/bundle.js +++ b/IDE/public/js/bundle.js @@ -417,7 +417,7 @@ settingsView.on('project-settings', function (data) { settingsView.on('IDE-settings', function (data) { data.currentProject = models.project.getKey('currentProject'); - // console.log('IDE-settings', data); + //console.log('IDE-settings', data); socket.emit('IDE-settings', data); }); settingsView.on('run-on-boot', function (project) { @@ -2184,16 +2184,23 @@ var EditorView = function (_View) { }, { key: '_darkTheme', value: function _darkTheme(value) { - if (parseInt(value)) { - // this.editor.setTheme("ace/theme/xcode_dark"); - this.editor.setTheme("ace/theme/monokai"); + var isDarkTheme = parseInt(value) + var body = $('body'); + + if (isDarkTheme) { + this.editor.setTheme("ace/theme/xcode_dark"); + // this.editor.setTheme("ace/theme/monokai"); + body.toggleClass('light-theme', Boolean(false)); + body.toggleClass('dark-theme', Boolean(true)); } else { this.editor.setTheme("ace/theme/chrome"); + body.toggleClass('dark-theme', Boolean(false)); + body.toggleClass('light-theme', Boolean(true)); } } // editor focus has changed - }, { + }, { key: '__focus', value: function __focus(data) { @@ -4596,20 +4603,6 @@ var SettingsView = function (_View) { } }); } - // }, { - // key: '_darkTheme', - // value: function _darkTheme(func, key, value) { - // console.log("in _darkTheme") - // var app = document.querySelector(".app"); - // // editor theme has changed - // if (parseInt(func)) { - // app.classList.remove('light'); - // app.classList.add('dark'); - // } else { - // app.classList.remove('dark'); - // app.classList.add('light'); - // } - // } }, { key: '_boardString', value: function _boardString(data) { From 1ad3467423707e9c937e6a333326cf60a1768046 Mon Sep 17 00:00:00 2001 From: Laimonade Date: Fri, 2 Feb 2024 02:04:38 +0000 Subject: [PATCH 172/188] added css variables --- IDE/public/css/theme-variables.css | 62 ++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 IDE/public/css/theme-variables.css diff --git a/IDE/public/css/theme-variables.css b/IDE/public/css/theme-variables.css new file mode 100644 index 000000000..741b2c21f --- /dev/null +++ b/IDE/public/css/theme-variables.css @@ -0,0 +1,62 @@ +:root { + --main-background-color: #ffffff; + --tabs-color: #c9c9c9; + --selected-tab-color: #ffffff; + --top-file-status-color: #e1e1e1; + --accordion-background-color: #f1f1f1; + --hovered-accordion-color: #bdbdbd; + --accordion-font-color: rgba(0, 0, 0, 0.6); + --accordion-font-color-accent: rgba(0, 0, 0, 0.8); + --main-font-color: #000000; + --hovered-accordion-color-two: #f9f9f9; + --main-font-color-accent: #000000; + --cursor-color: #f1f1f1; +} + +/* Light Theme */ +.light-theme { + --main-background-color: #ffffff; + --tabs-color: #c9c9c9; + --selected-tab-color: #ffffff; + --top-file-status-color: #e1e1e1; + --accordion-background-color: #f1f1f1; + --hovered-accordion-color: #bdbdbd; + --accordion-font-color: rgba(0, 0, 0, 0.6); + --accordion-font-color-accent: rgba(0, 0, 0, 0.8); + --main-font-color: #000000; + --hovered-accordion-color-two: #f9f9f9; + --main-font-color-accent: #000000; + --cursor-color: #f1f1f1; +} + +/* Dark Theme */ +.dark-theme { + --main-background-color: #292a2f; + --tab-color: #252729; + --selected-tab-color: #252729; + --top-file-status-color: #252729; + --accordion-background-color: #3f4045; + --hovered-accordion-color: #3e4d5c; + --accordion-font-color: #dfdfe0; + --accordion-font-color-accent: #ededf2; + --main-font-color: #dfdfe0; + --hovered-accordion-color-two: #3f4045; + --main-font-color-accent: #ededf2; + --cursor-color: rgb(44,44,44); +} + + +/*$theme: (*/ +/* "white-to-dark-bg-color": map-get($shades, "shade-0"),*/ +/* "grey-to-dark-toolbar-color": map-get($shades, "shade-1"),*/ +/* "white-to-dark-toolbar-color": map-get($shades, "shade-2"),*/ +/* "grey-to-dark-top-bar-color": map-get($shades, "shade-3"),*/ +/* "grey-light-to-dark-accordion-color": map-get($shades, "shade-4"),*/ +/* "grey-mid-to-dark-hov-accordion-color": map-get($shades, "shade-5"),*/ +/* "accordion-font-color": map-get($shades, "shade-6"),*/ +/* "accordion-highlight-font-color": map-get($shades, "shade-7"),*/ +/* "black-to-light-text-color": map-get($shades, "shade-8"),*/ +/* "light-to-dark-dropdown-color": map-get($shades, "shade-9"),*/ +/* "black-to-highlight-text-color": map-get($shades, "shade-10"),*/ +/* "cursor-highlight-color": map-get($shades, "shade-11"),*/ +/* );*/ \ No newline at end of file From 92782c8d1e5d9019a73c4382add2e60d58314b25 Mon Sep 17 00:00:00 2001 From: Laimonade Date: Fri, 2 Feb 2024 02:05:51 +0000 Subject: [PATCH 173/188] implemented custom ACE xcode dark theme --- IDE/public/js/ace/theme-xcode_dark.js | 154 ++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 IDE/public/js/ace/theme-xcode_dark.js diff --git a/IDE/public/js/ace/theme-xcode_dark.js b/IDE/public/js/ace/theme-xcode_dark.js new file mode 100644 index 000000000..55ad74580 --- /dev/null +++ b/IDE/public/js/ace/theme-xcode_dark.js @@ -0,0 +1,154 @@ +ace.define("ace/theme/xcode_dark",["require","exports","module","ace/lib/dom"], function(require, exports, module) { + +exports.isDark = true; +exports.cssClass = "ace-xcode-dark"; +exports.cssText = "\ +.ace-xcode-dark .ace_gutter {\ +background: #292A2F;\ +color: #8F908A;\ +overflow : hidden;\ +}\ +.ace-xcode-dark .ace_print-margin {\ +width: 1px;\ +background: #292A2F;\ +}\ +.ace-xcode-dark {\ +display: block;\ +overflow-x: auto;\ +padding: .5em;\ +color: #DFDFE0;\ +background-color: #292A2F;\ +}\ +.ace-xcode-dark .ace_invisible {\ +color: #656f81;\ +}\ +.ace-xcode-dark .ace_constant.ace_buildin {\ +color: #EF81B0;\ +}\ +.ace-xcode-dark .ace_constant.ace_language {\ +color: #AB83E4;\ +}\ +.ace-xcode-dark .ace_constant.ace_library {\ +color: #E57668;\ +}\ +.ace-xcode-dark .ace_invalid {\ +color: #F8F8F0;\ +background-color: #F92672;\ +}\ +.ace-xcode-dark .ace_fold {\ +background-color: #A6E22E;\ +border-color: #F8F8F2;\ +}\ +.ace-xcode-dark .ace_support.ace_function {\ +color: #4EB0CC;\ +}\ +.ace-xcode-dark .ace_support.ace_constant {\ +color: #4EB0CC;\ +}\ +.ace-xcode-dark .ace_support.ace_other,\ +.ace-xcode-dark .ace_storage.ace_type,\ +.ace-xcode-dark .ace_support.ace_class,\ +.ace-xcode-dark .ace_support.ace_type {\ +font-style: italic;\ +color: #66D9EF;\ +}\ +.ace-xcode-dark .ace_variable.ace_parameter {\ +font-style:italic;\ +color: #FD971F;\ +}\ +.ace-xcode-dark .ace_keyword.ace_operator {\ +color: #DFDFE0;\ +}\ +.ace-xcode-dark .ace_comment {\ +color: #A5B0BD;\ +}\ +.ace-xcode-dark .ace_comment.ace_doc {\ +color: #75715E;\ +}\ +.ace-xcode-dark .ace_comment.ace_doc.ace_tag {\ +color: #EF81B0;\ +}\ +.ace-xcode-dark .ace_constant.ace_numeric {\ +color: #D5CA86;\ +}\ +.ace-xcode-dark .ace_variable {\ +color: #BBF0E4;\ +}\ +.ace-xcode-dark .ace_xml-pe {\ +color: rgb(104, 104, 91);\ +}\ +.ace-xcode-dark .ace_entity.ace_name.ace_function {\ +color: #4Eb0CC;\ +}\ +.ace-xcode-dark .ace_heading {\ +color: #DFDFE0;\ +}\ +.ace-xcode-dark .ace_list {\ +color: #4EB0CC;\ +}\ +.ace-xcode-dark .ace_marker-layer .ace_selection {\ +background: #49483E;\ +}\ +.ace-xcode-dark .ace_marker-layer .ace_step {\ +background: rgb(102, 82, 0);\ +}\ +.ace-xcode-dark .ace_marker-layer .ace_stack {\ +background: rgb(164, 229, 101);\ +}\ +.ace-xcode-dark .ace_marker-layer .ace_bracket {\ +margin: -1px 0 0 -1px;\ +border: 1px solid #828C97;\ +}\ +.ace-xcode-dark .ace_marker-layer .ace_active-line {\ +background: #202020;\ +}\ +.ace-xcode-dark .ace_gutter-active-line {\ +background-color: #2F113239;\ +}\ +.ace-xcode-dark .ace_marker-layer .ace_selected-word {\ +border: 1px solid #656F81;\ +}\ +.ace-xcode-dark .ace_storage,\ +.ace-xcode-dark .ace_keyword,\ +.ace-xcode-dark .ace_meta.ace_tag {\ +color: #EF81B0;\ +}\ +.ace-xcode-dark .ace_string.ace_regex {\ +color: #F08875;\ +}\ +.ace-xcode-dark .ace_string {\ +color: #F08875;\ +}\ +.ace-xcode-dark .ace_entity.ace_other.ace_attribute-name {\ +color: #F08875;\ +}\ +.ace-xcode-dark .ace_indent-guide {\ +background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWPQ0FD0ZXBzd/wPAAjVAoxeSgNeAAAAAElFTkSuQmCC) right repeat-y;\ +}\ +.ace-xcode-dark .ace_entity.ace_other{\ +color: #DFDFE0;\ +}\ +.ace-xcode-dark.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px #646F83;\ +}\ +.ace-content{\ + border-top:1px solid #43464a;\ +}\ +"; + +var dom = require("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); (function() { + ace.require(["ace/theme/xcode_dark"], function(m) { + if (typeof module == "object" && typeof exports == "object" && module) { + module.exports = m; + } + }); + })(); + + + + + + + From fe60e74f27439986456bda8691e53dd30dbab93d Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 1 Feb 2024 21:08:43 +0000 Subject: [PATCH 174/188] Trill: do not print errors when probing --- libraries/Trill/Trill.cpp | 11 ++++++++--- libraries/Trill/Trill.h | 1 + 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/libraries/Trill/Trill.cpp b/libraries/Trill/Trill.cpp index 62182fca1..5b208f0e3 100644 --- a/libraries/Trill/Trill.cpp +++ b/libraries/Trill/Trill.cpp @@ -224,6 +224,7 @@ int Trill::setup(unsigned int i2c_bus, Device device, uint8_t i2c_address) Trill::Device Trill::probe(unsigned int i2c_bus, uint8_t i2c_address) { Trill t; + t.quiet = true; if(t.initI2C_RW(i2c_bus, i2c_address, -1)) { return Trill::NONE; } @@ -329,7 +330,8 @@ int Trill::writeCommandAndHandle(const i2c_char_t* data, size_t size, const char int ret = writeBytes(buf, bytesToWrite); if(ret != bytesToWrite) { - fprintf(stderr, "Trill: failed to write command \"%s\"; ret: %d, errno: %d, %s.\n", name, ret, errno, strerror(errno)); + if(!quiet) + fprintf(stderr, "Trill: failed to write command \"%s\"; ret: %d, errno: %d, %s.\n", name, ret, errno, strerror(errno)); return 1; } currentReadOffset = buf[0]; @@ -351,8 +353,11 @@ int Trill::readBytesFrom(const uint8_t offset, i2c_char_t* data, size_t size, co int ret = writeBytes(&offset, sizeof(offset)); if(ret != sizeof(offset)) { - fprintf(stderr, "%s: error while setting read offset\n", name); - printErrno(ret); + if(!quiet) + { + fprintf(stderr, "%s: error while setting read offset\n", name); + printErrno(ret); + } return 1; } currentReadOffset = offset; diff --git a/libraries/Trill/Trill.h b/libraries/Trill/Trill.h index c7115985c..5fc68d6f2 100644 --- a/libraries/Trill/Trill.h +++ b/libraries/Trill/Trill.h @@ -70,6 +70,7 @@ class Trill : public I2c uint8_t firmware_version_ = 0; // Firmware version running on the device uint8_t num_touches_; // Number of touches on last read bool dataBufferIncludesStatusByte = false; + bool quiet = false; std::vector dataBuffer; uint16_t commandSleepTime = 1000; size_t currentReadOffset = -1; From 78b9fd724adf059229bab32e7730dc244b67f10f Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Mon, 5 Feb 2024 22:57:34 +0000 Subject: [PATCH 175/188] Trill: re-enable kScanTriggerI2c for rev 3 sensors. This issue has been around since 28e2c3fcb9f3e4f9042565734c9b326ef7d05de3 --- libraries/Trill/Trill.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/Trill/Trill.cpp b/libraries/Trill/Trill.cpp index 5b208f0e3..b46a65d68 100644 --- a/libraries/Trill/Trill.cpp +++ b/libraries/Trill/Trill.cpp @@ -213,7 +213,7 @@ int Trill::setup(unsigned int i2c_bus, Device device, uint8_t i2c_address) address = i2c_address; readErrorOccurred = false; - if(firmware_version_ > 3) + if(firmware_version_ >= 3) { if(setScanTrigger(kScanTriggerI2c)) return 1; From f98d815526b4a5ed1ac7c83705f5e7f2f9aa3cc0 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 6 Feb 2024 00:14:19 +0000 Subject: [PATCH 176/188] Trill: added probeRange() and allow to pass Trill::UNKNOWN to setup() to automatically probe the whole range if needed --- libraries/Trill/Trill.cpp | 26 ++++++++++++++++++++++++++ libraries/Trill/Trill.h | 36 ++++++++++++++++++++++++++++-------- 2 files changed, 54 insertions(+), 8 deletions(-) diff --git a/libraries/Trill/Trill.cpp b/libraries/Trill/Trill.cpp index b46a65d68..f8e761225 100644 --- a/libraries/Trill/Trill.cpp +++ b/libraries/Trill/Trill.cpp @@ -2,6 +2,7 @@ #include #include #include +#include constexpr uint8_t Trill::speedValues[4]; #define MAX_TOUCH_1D_OR_2D (((device_type_ == SQUARE || device_type_ == HEX) ? kMaxTouchNum2D : kMaxTouchNum1D)) @@ -130,6 +131,17 @@ int Trill::setup(unsigned int i2c_bus, Device device, uint8_t i2c_address) frameId = 0; device_type_ = NONE; TrillDefaults defaults = trillDefaults.at(device); + if(UNKNOWN == device && 255 == i2c_address) { + auto devs = probeRange(i2c_bus, 1); + if(devs.size()) { + const auto& d = devs[0]; + device = d.first; + i2c_address = d.second; + } else { + fprintf(stderr, "No Trill device found on I2C bus %d\n", i2c_bus); + return 2; + } + } if(128 <= i2c_address) i2c_address = defaults.address; @@ -234,6 +246,20 @@ Trill::Device Trill::probe(unsigned int i2c_bus, uint8_t i2c_address) return t.device_type_; } +std::vector > Trill::probeRange(unsigned int i2c_bus, size_t maxCount) +{ + std::vector< std::pair > devs; + if(0 == maxCount) + maxCount = std::numeric_limits::max(); + // probe the valid address range on the bus to find a valid device + for(uint8_t n = 0x20; n <= 0x50 && devs.size() <= maxCount; ++n) { + Device device = probe(i2c_bus, n); + if(device != NONE) + devs.push_back({device, n}); + } + return devs; +} + Trill::~Trill() { closeI2C(); } diff --git a/libraries/Trill/Trill.h b/libraries/Trill/Trill.h index 5fc68d6f2..563e4dbc8 100644 --- a/libraries/Trill/Trill.h +++ b/libraries/Trill/Trill.h @@ -154,15 +154,21 @@ class Trill : public I2c * Initialise the device. * * @param i2c_bus the bus that the device is connected to. - * @param device the device type. If #UNKNOWN is passed, then - * the \p i2c_address parameter has to be a valid address, and - * any detected device type will be accepted. If something else - * than #UNKNOWN is passed, and the detected device type is - * different from the requested one, the function will fail and - * the object will be left uninitialised. + * @param device the device type. + * * @param i2c_address the address at which the device can be - * found. If `255` or no value is passed, the default address - * for the specified device type will be used. + * found. + * + * If @p device is #UNKNOWN then: + * - if \p i2c_address is a valid address, then + * any device detected at that addres will be accepted + * - if \p i2c_address is `255` or unspecified, then the range of + * valid addresses will be scanned, stopping at the first + * valid device encountered. Use this with caution as it may + * affect the behaviour of non-Trill devices on the I2C bus. + * + * Otherwise, if @p i2c_address is `255` or unspecified, + * the default address for the specified device type will be used. */ Trill(unsigned int i2c_bus, Device device, uint8_t i2c_address = 255); /** @@ -180,6 +186,20 @@ class Trill : public I2c */ static Device probe(unsigned int i2c_bus, uint8_t i2c_address); + /** + * Probe the bus for a device at any valid address. + * \warning Use with caution as it may affect the behaviour of + * non-Trill devices on the I2C bus. + * + * @param i2c_bus the I2C bus to scan + * @param maxCount stop discovering new devices after this many + * have been discovered. Use 0 to find all possible devices. + * + * @return A vector containing the #Device and address pairs + * identified. + */ + static std::vector > probeRange(unsigned int i2c_bus, size_t maxCount = 0); + /** * Update the baseline value on the device. */ From 77e3f02792655a007d99c876f92f6d5aa5ca6691 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 6 Feb 2024 00:31:04 +0000 Subject: [PATCH 177/188] Trill: use ANY instead of UNKNOWN --- libraries/Trill/Trill.cpp | 12 ++++++------ libraries/Trill/Trill.h | 5 +++-- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/libraries/Trill/Trill.cpp b/libraries/Trill/Trill.cpp index f8e761225..24be4a6dc 100644 --- a/libraries/Trill/Trill.cpp +++ b/libraries/Trill/Trill.cpp @@ -67,7 +67,7 @@ struct TrillDefaults const float defaultThreshold = 0x28 / 4096.f; static const std::map trillDefaults = { {Trill::NONE, TrillDefaults("No device", Trill::AUTO, 0, 0xFF, -1)}, - {Trill::UNKNOWN, TrillDefaults("Unknown device", Trill::AUTO, 0, 0xFF, -1)}, + {Trill::ANY, TrillDefaults("Unknown device", Trill::AUTO, 0, 0xFF, -1)}, {Trill::BAR, TrillDefaults("Bar", Trill::CENTROID, defaultThreshold, 0x20, 2)}, {Trill::SQUARE, TrillDefaults("Square", Trill::CENTROID, defaultThreshold, 0x28, 1)}, {Trill::CRAFT, TrillDefaults("Craft", Trill::DIFF, defaultThreshold, 0x30, 1)}, @@ -91,7 +91,7 @@ struct trillRescaleFactors_t { }; static const std::vector trillRescaleFactors ={ - {.pos = 1, .posH = 0, .size = 1}, // UNKNOWN = 0, + {.pos = 1, .posH = 0, .size = 1}, // ANY = 0, {.pos = 3200, .posH = 0, .size = 4566}, // BAR = 1, {.pos = 1792, .posH = 1792, .size = 3780}, // SQUARE = 2, {.pos = 4096, .posH = 0, .size = 1}, // CRAFT = 3, @@ -131,7 +131,7 @@ int Trill::setup(unsigned int i2c_bus, Device device, uint8_t i2c_address) frameId = 0; device_type_ = NONE; TrillDefaults defaults = trillDefaults.at(device); - if(UNKNOWN == device && 255 == i2c_address) { + if(ANY == device && 255 == i2c_address) { auto devs = probeRange(i2c_bus, 1); if(devs.size()) { const auto& d = devs[0]; @@ -168,7 +168,7 @@ int Trill::setup(unsigned int i2c_bus, Device device, uint8_t i2c_address) fprintf(stderr, "Unable to identify device\n"); return 2; } - if(UNKNOWN != device && device_type_ != device) { + if(ANY != device && device_type_ != device) { fprintf(stderr, "Wrong device type detected. `%s` was requested " "but `%s` was detected on bus %d at address %#x(%d).\n", defaults.name.c_str(), @@ -269,7 +269,7 @@ const std::string& Trill::getNameFromDevice(Device device) __try { return trillDefaults.at(device).name; } __catch (std::exception e) { - return trillDefaults.at(Device::UNKNOWN).name; + return trillDefaults.at(Device::ANY).name; } } @@ -297,7 +297,7 @@ Trill::Device Trill::getDeviceFromName(const std::string& name) if(strCmpIns(name, str2)) return Device(device); } - return Trill::UNKNOWN; + return Trill::ANY; } const std::string& Trill::getNameFromMode(Mode mode) diff --git a/libraries/Trill/Trill.h b/libraries/Trill/Trill.h index 563e4dbc8..a6ab57f6a 100644 --- a/libraries/Trill/Trill.h +++ b/libraries/Trill/Trill.h @@ -30,13 +30,14 @@ class Trill : public I2c */ typedef enum { NONE = -1, ///< No device - UNKNOWN = 0, ///< A valid device of unknown type + ANY = 0, ///< A valid device of unknown type BAR = 1, ///< %Trill Bar SQUARE = 2, ///< %Trill Square CRAFT = 3, ///< %Trill Craft RING = 4, ///< %Trill Ring HEX = 5, ///< %Trill Hex FLEX = 6, ///< %Trill Flex + UNKNOWN = ANY, ///< same as ANY, for backwards compatibility } Device; /** * Controls when the EVT pin will be set when a new frame is @@ -159,7 +160,7 @@ class Trill : public I2c * @param i2c_address the address at which the device can be * found. * - * If @p device is #UNKNOWN then: + * If @p device is #ANY then: * - if \p i2c_address is a valid address, then * any device detected at that addres will be accepted * - if \p i2c_address is `255` or unspecified, then the range of From 08bef7783fb9e5640f8420d26153c0f4f51cab36 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 6 Feb 2024 22:22:32 +0000 Subject: [PATCH 178/188] NIT: typo --- examples/Sensors/DHT11-temperature-humidity/render.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/Sensors/DHT11-temperature-humidity/render.cpp b/examples/Sensors/DHT11-temperature-humidity/render.cpp index bc392de5f..244fd1aa2 100644 --- a/examples/Sensors/DHT11-temperature-humidity/render.cpp +++ b/examples/Sensors/DHT11-temperature-humidity/render.cpp @@ -32,7 +32,7 @@ Datasheet: https://www.mouser.com/datasheet/2/758/DHT11-Technical-Data-Sheet-Tra const unsigned digitalPin = 0; -DHT dht(digitialPin, DHT11); +DHT dht(digitalPin, DHT11); bool setup(BelaContext *context, void *userData) { return true; From ab8cecdf4dd93cf09b11a06f2ddcbbffb84e4925 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 6 Feb 2024 23:05:58 +0000 Subject: [PATCH 179/188] Trill: default to ANY in setup() --- libraries/Trill/Trill.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/Trill/Trill.h b/libraries/Trill/Trill.h index a6ab57f6a..39cccdb96 100644 --- a/libraries/Trill/Trill.h +++ b/libraries/Trill/Trill.h @@ -177,7 +177,7 @@ class Trill : public I2c * * \copydoc TAGS_canonical_return */ - int setup(unsigned int i2c_bus, Device device, uint8_t i2c_address = 255); + int setup(unsigned int i2c_bus, Device device = ANY, uint8_t i2c_address = 255); /** * Probe the bus for a device at the specified address. From cdda35b4bffb45bd65433e134d765b5caff37452 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 6 Feb 2024 23:06:51 +0000 Subject: [PATCH 180/188] Trill/{detect-all-devices,general-*}: take advantage of new API --- examples/Trill/detect-all-devices/render.cpp | 14 ++++++-------- examples/Trill/general-print/render.cpp | 6 ++---- examples/Trill/general-settings/render.cpp | 5 ++--- examples/Trill/general-visual/render.cpp | 5 ++--- 4 files changed, 12 insertions(+), 18 deletions(-) diff --git a/examples/Trill/detect-all-devices/render.cpp b/examples/Trill/detect-all-devices/render.cpp index 3043745a9..f8faaf380 100644 --- a/examples/Trill/detect-all-devices/render.cpp +++ b/examples/Trill/detect-all-devices/render.cpp @@ -34,15 +34,13 @@ bool setup(BelaContext *context, void *userData) unsigned int i2cBus = 1; printf("Trill devices detected on bus %d\n", i2cBus); printf("Address | Type\n"); - unsigned int total = 0; - for(uint8_t n = 0x20; n <= 0x50; ++n) { - Trill::Device device = Trill::probe(i2cBus, n); - if(device != Trill::NONE) { - printf("%#4x (%3d) | %s\n", n, n, Trill::getNameFromDevice(device).c_str()); - ++total; - } + auto devices = Trill::probeRange(i2cBus); + for(auto& d : devices) { + const std::string& device = Trill::getNameFromDevice(d.first); + int addr = d.second; + printf("%#4x (%2d) | %s\n", addr, addr, device.c_str()); } - printf("Total: %d devices\n", total); + printf("Total: %d devices\n", devices.size()); return true; } diff --git a/examples/Trill/general-print/render.cpp b/examples/Trill/general-print/render.cpp index 206d14d54..47c181a13 100644 --- a/examples/Trill/general-print/render.cpp +++ b/examples/Trill/general-print/render.cpp @@ -49,10 +49,8 @@ void loop(void*) bool setup(BelaContext *context, void *userData) { - // Setup a Trill Craft on i2c bus 1, using the default address. - // Set it to differential mode for bargraph display - if(touchSensor.setup(1, Trill::CRAFT) != 0) { - fprintf(stderr, "Unable to initialise Trill Craft\n"); + // Look for a connected Trill on I2C bus 1 + if(touchSensor.setup(1) != 0) { return false; } // ensure the device is in DIFF mode for printing raw values diff --git a/examples/Trill/general-settings/render.cpp b/examples/Trill/general-settings/render.cpp index 4c88bf8a0..ce449cbaf 100644 --- a/examples/Trill/general-settings/render.cpp +++ b/examples/Trill/general-settings/render.cpp @@ -287,9 +287,8 @@ void loop(void*) bool setup(BelaContext *context, void *userData) { - // Setup a Trill Craft on i2c bus 1, using the default address. - if(touchSensor.setup(1, Trill::CRAFT) != 0) { - fprintf(stderr, "Unable to initialise Trill Craft\n"); + // Look for a connected Trill on I2C bus 1 + if(touchSensor.setup(1) != 0) { return false; } touchSensor.printDetails(); diff --git a/examples/Trill/general-visual/render.cpp b/examples/Trill/general-visual/render.cpp index 582082009..7460a6174 100644 --- a/examples/Trill/general-visual/render.cpp +++ b/examples/Trill/general-visual/render.cpp @@ -55,9 +55,8 @@ void loop(void*) bool setup(BelaContext *context, void *userData) { - // Setup a Trill Craft on i2c bus 1, using the default address. - if(touchSensor.setup(1, Trill::CRAFT) != 0) { - fprintf(stderr, "Unable to initialise Trill Craft\n"); + // Look for a connected Trill on I2C bus 1 + if(touchSensor.setup(1) != 0) { return false; } // ensure the device is in DIFF mode for printing raw values From c954b747fe1daf3ab731f4dc6231370d5d98b0f3 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 8 Feb 2024 21:15:31 +0000 Subject: [PATCH 181/188] Midi: add more information on port, retrievabble --- libraries/Midi/Midi.cpp | 115 ++++++++++++++++++++++++++++++++-------- libraries/Midi/Midi.h | 28 +++++++++- 2 files changed, 118 insertions(+), 25 deletions(-) diff --git a/libraries/Midi/Midi.cpp b/libraries/Midi/Midi.cpp index 77475d63e..bdaa64fdd 100644 --- a/libraries/Midi/Midi.cpp +++ b/libraries/Midi/Midi.cpp @@ -263,6 +263,47 @@ void Midi::doWriteOutput(const void* data, int size) { #include +static Midi::Port getPort(snd_rawmidi_info_t* info) +{ +#if 0 + printf("==========\n"); + printf("device: %d\n", snd_rawmidi_info_get_device(info)); + printf("subdevice: %d\n", snd_rawmidi_info_get_subdevice(info)); + printf("stream: %d\n", snd_rawmidi_info_get_stream(info)); + printf("card: %d\n", snd_rawmidi_info_get_card(info)); + printf("flags: %d\n", snd_rawmidi_info_get_flags(info)); + printf("id: %s\n", snd_rawmidi_info_get_id(info)); + printf("name: %s\n", snd_rawmidi_info_get_name(info)); + printf("subdevice_name: %s\n", snd_rawmidi_info_get_subdevice_name(info)); + printf("subdevices_count: %d\n", snd_rawmidi_info_get_subdevices_count(info)); + printf("subdevices_avail: %d\n", snd_rawmidi_info_get_subdevices_avail(info)); +#endif + int card = snd_rawmidi_info_get_card(info); + int sub = snd_rawmidi_info_get_subdevice(info); + int device = snd_rawmidi_info_get_device(info); + std::string name = "hw:" + std::to_string(card) + "," + std::to_string(device) + "," + std::to_string(sub); + std::string desc = std::string(snd_rawmidi_info_get_id(info)) + " " + snd_rawmidi_info_get_name(info) + " [ " + snd_rawmidi_info_get_subdevice_name(info) + " ]"; + return { + .name = name, + .desc = desc, + .card = card, + .device = device, + .sub = (int)sub, + .hasInput = false, // TODO: fill these in, see is_input()/is_output() + .hasOutput = false, + }; +} + +static int getPort(snd_rawmidi_t* rmidi, Midi::Port& port) { + snd_rawmidi_info_t *info; + snd_rawmidi_info_alloca(&info); + int ret = snd_rawmidi_info(rmidi, info); + if(ret) + return ret; + port = getPort(info); + return 0; +} + int Midi::readFrom(const char* port){ if(port == NULL){ port = defaultPort.c_str(); @@ -274,7 +315,13 @@ int Midi::readFrom(const char* port){ if (err) { return err; } - int ret = create_and_start_thread(&midiInputThread, inId.c_str(), 50, 0, NULL, Midi::readInputLoopStatic, (void*)this); + int ret = getPort(alsaIn, inPortFull); + inPortFull.hasInput = true; + if(ret) { + fprintf(stderr, "Unable to retrieve input port information for %s\n", port); + return 0; + } + ret = create_and_start_thread(&midiInputThread, inId.c_str(), 50, 0, NULL, Midi::readInputLoopStatic, (void*)this); if(ret) return 0; inputEnabled = true; @@ -292,6 +339,12 @@ int Midi::writeTo(const char* port){ if (err) { return err; } + int ret = getPort(alsaOut, outPortFull); + inPortFull.hasOutput = true; + if(ret) { + fprintf(stderr, "Unable to retrieve output port information for %s\n", port); + return 0; + } midiOutputTask = new AuxTaskNonRT(); midiOutputTask->create(outId, [this](void* buf, int size) { this->doWriteOutput(buf, size); @@ -300,7 +353,8 @@ int Midi::writeTo(const char* port){ return 1; } -void Midi::createAllPorts(std::vector& ports, bool useParser){ +std::vector Midi::listAllPorts(){ + std::vector ports; int card = -1; int status; while((status = snd_card_next(&card)) == 0){ @@ -314,7 +368,7 @@ void Midi::createAllPorts(std::vector& ports, bool useParser){ sprintf(name, "hw:%d", card); if ((status = snd_ctl_open(&ctl, name, 0)) < 0) { error("cannot open control for card %d: %s\n", card, snd_strerror(status)); - return; + return ports; } do { status = snd_ctl_rawmidi_next_device(ctl, &device); @@ -342,7 +396,7 @@ void Midi::createAllPorts(std::vector& ports, bool useParser){ if ((status = is_output(ctl, card, device, sub)) < 0) { error("cannot get rawmidi information %d:%d: %s", card, device, snd_strerror(status)); - return; + return ports; } else if (status){ out = true; // writeTo @@ -352,7 +406,7 @@ void Midi::createAllPorts(std::vector& ports, bool useParser){ if ((status = is_input(ctl, card, device, sub)) < 0) { error("cannot get rawmidi information %d:%d: %s", card, device, snd_strerror(status)); - return; + return ports; } } else if (status) { in = true; @@ -360,27 +414,43 @@ void Midi::createAllPorts(std::vector& ports, bool useParser){ } if(in || out){ - ports.resize(ports.size() + 1); - unsigned int index = ports.size() - 1; - ports[index] = new Midi(); - const char* myName = snd_rawmidi_info_get_name(info); - const char* mySubName = snd_rawmidi_info_get_subdevice_name(info); - sprintf(name, "hw:%d,%d,%d", card, device, sub); - if(in){ - printf("Port %d, Reading from: %s, %s %s\n", index, name, myName, mySubName); - ports[index]->readFrom(name); - ports[index]->enableParser(useParser); - } - if(out){ - printf("Port %d, Writing to: %s %s %s\n", index, name, myName, mySubName); - ports[index]->writeTo(name); - } + Port port = getPort(info); + port.hasInput = in; + port.hasOutput = out; + ports.push_back(port); } } } } while (device >= 0); snd_ctl_close(ctl); } + return ports; +} + +void Midi::createAllPorts(std::vector& ports, bool useParser){ + auto list = listAllPorts(); + ports.reserve(list.size()); + for(size_t n = 0; n < list.size(); ++n) { + auto& l = list[n]; + if(!(l.hasInput || l.hasOutput)) + continue; + Midi* m = new Midi(); + if(l.hasInput) { + std::string str = "reading from " + l.name + ": " + l.desc; + if(1 == m->readFrom(l.name.c_str())) + printf("Port %d, %s\n", n, str.c_str()); + else + fprintf(stderr, "Port %d, ERROR %s\n", n, str.c_str()); + } + if(l.hasOutput) { + std::string str = "writing to " + l.name + ": " + l.desc; + if(1 == m->writeTo(l.name.c_str())) + printf("Port %d, %s\n", n, str.c_str()); + else + fprintf(stderr, "Port %d, ERROR %s\n", n, str.c_str()); + } + ports.push_back(m); + } } int Midi::_getInput(){ @@ -437,12 +507,12 @@ int Midi::writeOutput(midi_byte_t* bytes, unsigned int length){ return 1; } -bool Midi::isInputEnabled() +bool Midi::isInputEnabled() const { return inputEnabled; } -bool Midi::isOutputEnabled() +bool Midi::isOutputEnabled() const { return outputEnabled; } @@ -761,7 +831,6 @@ static int is_input(snd_ctl_t *ctl, int card, int device, int sub) { } - ////////////////////////////// // // is_output -- returns true if specified card/device/sub can output MIDI data. diff --git a/libraries/Midi/Midi.h b/libraries/Midi/Midi.h index 4f567bc99..d4ae89def 100644 --- a/libraries/Midi/Midi.h +++ b/libraries/Midi/Midi.h @@ -2,6 +2,7 @@ #include #include #include +#include typedef unsigned char midi_byte_t; @@ -370,10 +371,31 @@ class Midi { MidiParser* getMidiParser(); virtual ~Midi(); - bool isInputEnabled(); + bool isInputEnabled() const; - bool isOutputEnabled(); + bool isOutputEnabled() const; + struct Port { + std::string name; + std::string desc; + int card; + int device; + int sub; + bool hasInput; + bool hasOutput; + bool operator== (const Port& o) const { + return name == o.name && + desc == o.desc && + card == o.card && + device == o.device && + sub == o.sub && + hasInput == o.hasInput && + hasOutput == o.hasOutput; + } + }; + const Port& getInputPort() const { return inPortFull; } + const Port& getOutputPort() const { return outPortFull; } + static std::vector listAllPorts(); /** * Opens all the existing MIDI ports, in the same order returned by the filesystem or Alsa. * Ports open with this method should be closed with destroyPorts() @@ -387,6 +409,8 @@ class Midi { private: std::string inPort; std::string outPort; + Port inPortFull; + Port outPortFull; int _getInput(); int attemptRecoveryRead(); static void* readInputLoopStatic(void* obj); From 0434fd7e654308527dc53cbc0c14f079c76220af Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Thu, 8 Feb 2024 21:13:50 +0000 Subject: [PATCH 182/188] default_libpd_render: overhauled MIDI initialisation, using dedicated thread. Send 'auto' to automatically discover new MIDI devices. --- core/default_libpd_render.cpp | 196 +++++++++++++++++++++++++++++----- 1 file changed, 169 insertions(+), 27 deletions(-) diff --git a/core/default_libpd_render.cpp b/core/default_libpd_render.cpp index e3a356819..ef27abc78 100644 --- a/core/default_libpd_render.cpp +++ b/core/default_libpd_render.cpp @@ -32,13 +32,15 @@ #undef BELA_LIBPD_SYSTEM_THREADED #endif // BELA_LIBPD_DISABLE_SYSTEM_THREADD -#define PD_THREADED_IO +//#define PD_THREADED_IO #include #include #include #ifdef BELA_LIBPD_MIDI +#include #include +#include #endif // BELA_LIBPD_MIDI #ifdef BELA_LIBPD_SCOPE #include @@ -429,10 +431,125 @@ float* gInBuf; float* gOutBuf; #ifdef BELA_LIBPD_MIDI #define PARSE_MIDI -static std::vector midi; -std::vector gMidiPortNames; int gMidiVerbose = 1; const int kMidiVerbosePrintLevel = 1; +#include + +static Midi* openMidiDevice(const std::string& name, bool verboseSuccess = false, bool verboseError = false); +static const std::string& midiName(const Midi* m) +{ + // assumes input and output are the same subdevice + if(m) { + if(m->isInputEnabled()) + return m->getInputPort().name; + else if(m->isOutputEnabled()) + return m->getOutputPort().name; + } + static const std::string none("NONE"); + return none; +} + +static std::thread gMidiDiscoveryThread; +static volatile bool gMidiDiscoveryThreadShouldStop; +static volatile bool gMidiDiscoveryThreadAuto; +Pipe gMidiDiscoveryPipe("midiDiscoveryPipe"); +enum MidiDiscoveryCmd { + kMidiAdd, + kMidiAck, +}; +struct MidiDiscoveryMsgFromNonRt { + MidiDiscoveryCmd cmd; + Midi* ptr; +}; +struct MidiDiscoveryMsgFromRt { + MidiDiscoveryCmd cmd; + Midi* ptr; + char name[32]; +}; + +static void midiDiscovery() +{ + gMidiDiscoveryPipe.setBlockingNonRt(true); + gMidiDiscoveryPipe.setTimeoutMsNonRt(100); + // it's hard to use inotify meaningfully, so we poll instead + auto shouldStop = []() { + return Bela_stopRequested() || gMidiDiscoveryThreadShouldStop; + }; + + std::vector toOpen; + std::vector localMidi; + std::vector msgs; + int count = 1; + unsigned int numDevices = 0; + bool doDiscovery = false; + while(!shouldStop()) + { + msgs.resize(0); + if(numDevices == localMidi.size()) + { + //printf("We are equal: %d\n", numDevices); + // when we are fully synced up: + if(doDiscovery && !toOpen.size() && gMidiDiscoveryThreadAuto) + { + doDiscovery = false; + // do discovery + auto list = Midi::listAllPorts(); + for(auto& l : list) + { + // Check if there are new devices that are not open yet. + toOpen.push_back(l.name); + // NOTE: devices that are unplugged and plugged back in + // that were previously initialised will be automatically reopened, + // so we are only concerned with new devices here. + } + count = 0; + } + while(toOpen.size()) + { + std::string name = toOpen[0]; + toOpen.erase(toOpen.begin()); + bool found = false; + for(const auto m : localMidi) + { + if(midiName(m) == name) + { + found = true; + break; + } + } + if(!found) + { + printf("New device %s, opening it\n", name.c_str()); + Midi* midi = openMidiDevice(name); + if(midi) { + MidiDiscoveryMsgFromNonRt msg = { + .cmd = kMidiAdd, + .ptr = midi, + }; + msgs.push_back(msg); + numDevices++; + break; + } + } + } + } + if(count++ > 20) + doDiscovery = true; + for(auto& msg : msgs) + gMidiDiscoveryPipe.writeNonRt(msg); + MidiDiscoveryMsgFromRt msg; + // potentially blocking read + int ret = gMidiDiscoveryPipe.readNonRt(msg); + if(1 == ret) + { + if(kMidiAck == msg.cmd) + localMidi.push_back(msg.ptr); + if(kMidiAdd == msg.cmd) + toOpen.push_back(msg.name); + } + } +} +static std::vector midi; void dumpMidi() { @@ -453,7 +570,7 @@ void dumpMidi() { printf("[%2d]%20s %3s %3s (%d-%d)\n", n, - gMidiPortNames[n].c_str(), + midiName(midi[n]).c_str(), midi[n]->isInputEnabled() ? "x" : "_", midi[n]->isOutputEnabled() ? "x" : "_", n * 16 + 1, @@ -462,7 +579,7 @@ void dumpMidi() } } -Midi* openMidiDevice(std::string name, bool verboseSuccess = false, bool verboseError = false) +static Midi* openMidiDevice(const std::string& name, bool verboseSuccess, bool verboseError) { Midi* newMidi; newMidi = new Midi(); @@ -684,6 +801,14 @@ void Bela_messageHook(const char *source, const char *symbol, int argc, t_atom * } return; } + if(0 == strcmp("auto", symbol)) + { + rt_printf("Automatically discover new MIDI devices\n"); + if(!gMidiDiscoveryThread.joinable()) + gMidiDiscoveryThread = std::thread(midiDiscovery); + gMidiDiscoveryThreadAuto = true; + return; + } int num[3] = {0, 0, 0}; for(int n = 0; n < argc && n < 3; ++n) { @@ -694,16 +819,19 @@ void Bela_messageHook(const char *source, const char *symbol, int argc, t_atom * } num[n] = libpd_get_float(&argv[n]); } + // TODO: this string/stream business is not actually realtime-safe. std::ostringstream deviceName; deviceName << symbol << ":" << num[0] << "," << num[1] << "," << num[2]; - printf("Adding Midi device: %s\n", deviceName.str().c_str()); - Midi* newMidi = openMidiDevice(deviceName.str(), false, true); - if(newMidi) - { - midi.push_back(newMidi); - gMidiPortNames.push_back(deviceName.str()); + MidiDiscoveryMsgFromRt msg = { + .cmd = kMidiAdd, + }; + std::string name = deviceName.str(); + if(name.size() + 1 > sizeof(msg.name)) { + fprintf(stderr, "MIDI name too long: %s\n", name.c_str()); + return; } - dumpMidi(); + strncpy(msg.name, deviceName.str().c_str(), sizeof(msg.name)); + gMidiDiscoveryPipe.writeRt(msg); return; } #endif // BELA_LIBPD_MIDI @@ -1082,9 +1210,9 @@ bool setup(BelaContext *context, void *userData) #ifdef BELA_LIBPD_MIDI // add here other devices you need - gMidiPortNames.push_back("hw:1,0,0"); - //gMidiPortNames.push_back("hw:0,0,0"); - //gMidiPortNames.push_back("hw:1,0,1"); + std::vector midiPortNames; + midiPortNames.push_back("hw:1,0,0"); + //midiPortNames.push_back("hw:0,0,0"); #endif // BELA_LIBPD_MIDI #ifdef BELA_LIBPD_SCOPE scope.setup(gScopeChannelsInUse, context->audioSampleRate); @@ -1133,19 +1261,15 @@ bool setup(BelaContext *context, void *userData) } #ifdef BELA_LIBPD_MIDI - unsigned int n = 0; - while(n < gMidiPortNames.size()) + gMidiDiscoveryThread = std::thread(midiDiscovery); + for(const auto & name : midiPortNames) { - Midi* newMidi = openMidiDevice(gMidiPortNames[n], false, false); - if(newMidi) - { - midi.push_back(newMidi); - ++n; - } else { - gMidiPortNames.erase(gMidiPortNames.begin() + n); - } + MidiDiscoveryMsgFromRt msg; + msg.cmd = kMidiAdd; + strncpy(msg.name, name.c_str(), sizeof(msg.name)); + gMidiDiscoveryPipe.writeRt(msg); } - dumpMidi(); + midi.reserve(midiPortNames.size() + 10); // hope we can avoid reallocation for a while #endif // BELA_LIBPD_MIDI // check that we are not running with a blocksize smaller than gLibPdBlockSize @@ -1400,6 +1524,22 @@ void render(BelaContext *context, void *userData) } #endif // BELA_LIBPD_TRILL #ifdef BELA_LIBPD_MIDI + if(gMidiDiscoveryThread.joinable()) + { + MidiDiscoveryMsgFromNonRt msg; + while(1 == gMidiDiscoveryPipe.readRt(msg)) + { + if(kMidiAdd == msg.cmd) + { + rt_printf("Midi pointer created %p\n", msg.ptr); + midi.push_back(msg.ptr); + MidiDiscoveryMsgFromRt res; + res.cmd = kMidiAck; + res.ptr = msg.ptr; + gMidiDiscoveryPipe.writeRt(res); + } + } + } #ifdef PARSE_MIDI int num; for(unsigned int port = 0; port < midi.size(); ++port){ @@ -1408,7 +1548,7 @@ void render(BelaContext *context, void *userData) message = midi[port]->getParser()->getNextChannelMessage(); if(gMidiVerbose >= kMidiVerbosePrintLevel) { - rt_printf("On port %d (%s): ", port, gMidiPortNames[port].c_str()); + rt_printf("On port %d (%s): ", port, midiName(midi[port]).c_str()); message.prettyPrint(); // use this to print beautified message (channel, data bytes) } switch(message.getType()){ @@ -1609,6 +1749,8 @@ void render(BelaContext *context, void *userData) void cleanup(BelaContext *context, void *userData) { #ifdef BELA_LIBPD_MIDI + if(gMidiDiscoveryThread.joinable()) + gMidiDiscoveryThread.join(); for(auto a : midi) { delete a; From dbbcd3fa88d1644c01ad742d3b3494a1e19331b5 Mon Sep 17 00:00:00 2001 From: Laimonade Date: Wed, 14 Feb 2024 23:20:00 +0000 Subject: [PATCH 183/188] implemented theme switching for color-themed elements --- IDE/frontend-dev/scss/_accordion-menu.scss | 64 ++++++++++++++------ IDE/frontend-dev/scss/_buttons.scss | 17 +++++- IDE/frontend-dev/scss/_console.scss | 9 ++- IDE/frontend-dev/scss/_dropdown-mini.scss | 7 +++ IDE/frontend-dev/scss/_dropdown.scss | 33 ++++++++--- IDE/frontend-dev/scss/_editor.scss | 6 +- IDE/frontend-dev/scss/_library-list.scss | 12 +++- IDE/frontend-dev/scss/_popup.scss | 13 ++++- IDE/frontend-dev/scss/_tab-content.scss | 28 ++++++++- IDE/frontend-dev/scss/_tab-menu.scss | 68 +++++++++++++++------- IDE/frontend-dev/scss/_tabs.scss | 26 +++++++-- IDE/frontend-dev/scss/_text-input.scss | 10 +++- IDE/frontend-dev/scss/_toolbar.scss | 14 ++++- IDE/frontend-dev/scss/_upper.scss | 11 +++- 14 files changed, 252 insertions(+), 66 deletions(-) diff --git a/IDE/frontend-dev/scss/_accordion-menu.scss b/IDE/frontend-dev/scss/_accordion-menu.scss index 06fdc51ef..1499ff5ca 100644 --- a/IDE/frontend-dev/scss/_accordion-menu.scss +++ b/IDE/frontend-dev/scss/_accordion-menu.scss @@ -1,8 +1,50 @@ +// color-themed accordion menu elements +@include themify($themes) { + button.accordion { + background-color: themed('accordion-background-color'); + border-bottom: 2px solid themed('main-background-color'); + color: themed('accordion-font-color'); + + &:hover { + background: themed('hovered-accordion-color'); + } + + &.active { + background-color: themed('accordion-background-color'); + color: themed('accordion-font-color-accent'); + + &:hover { + color: themed('accordion-font-color-accent'); + } + } + &:after { + color: themed('accordion-font-color'); + } + } + button.accordion-sub { + border-bottom: 1px solid themed('tabs-color'); + color: themed('accordion-font-color-accent'); + &:hover { + color: themed('accordion-font-color-accent'); + } + &.active { + color: themed('accordion-font-color-accent'); + &:hover { + color: themed('accordion-font-color-accent'); + } + } + } + .docs-content { + color: themed('main-font-color'); + } + .panel.show { + color: themed('main-font-color'); + } +} + + button.accordion { - background-color: $grey-light; border: none; - border-bottom: 2px solid #fff; - color: rgba(0, 0, 0, 0.6); cursor: pointer; font-family: poppins_regular; font-size: 16px; @@ -13,23 +55,16 @@ button.accordion { transition: 0.25s ease-in-out; width: 100%; &:hover { - background: $grey-mid; border-bottom: 2px solid $teal-main; } &.active { - background-color: $grey-light; border-bottom: 2px solid $teal-main; - color: $grey-dark; padding: 8px 14px; - &:hover { - color: $grey-dark; - } &:after { content: "\2796"; /* Unicode character for "minus" sign (-) */ } } &:after { - color: rgba(0, 0, 0, 0.6); content: '\02795'; /* Unicode character for "plus" sign (+) */ float: right; font-size: 14px; @@ -39,12 +74,10 @@ button.accordion { button.accordion-sub { background: transparent; - border-bottom: 1px solid $grey-toolbar; border-top: 0; border-left: 0; border-right: 0; border-radius: 0; - color: $grey-dark; font-size: 1em; font-family: 'poppins_regular'; padding: .4em .8em .25em; @@ -52,17 +85,12 @@ button.accordion-sub { width: 100%; &:hover { background: rgba($grey-toolbar,0.2); - color: $grey-dark; } &.active { background: transparent; border-bottom: 2px solid $teal-01; - color: $grey-dark; padding-bottom: .2em; margin-top: .2em; - &:hover { - color: $grey-dark; - } &:after { content: "\2796"; /* Unicode character for "minus" sign (-) */ font-size: .75em; @@ -101,4 +129,4 @@ button.accordion-sub { .panel.show { max-height: 100000px; /* Whatever you like, as long as its more than the height of the content (on all screen sizes) */ opacity: 1; -} +} \ No newline at end of file diff --git a/IDE/frontend-dev/scss/_buttons.scss b/IDE/frontend-dev/scss/_buttons.scss index 76334cbc1..fa0b7c316 100644 --- a/IDE/frontend-dev/scss/_buttons.scss +++ b/IDE/frontend-dev/scss/_buttons.scss @@ -1,3 +1,17 @@ +// color-themed button elements +@include themify($themes) { + button, + .button { + background-color: themed('main-background-color'); + color: themed('main-font-color'); + &.create-project { + &:before { + color: themed('accordion-font-color-accent'); + } + } + } +} + a.button { color: black; font-size: 11px; @@ -10,9 +24,7 @@ a.button { button, .button { border: 1px solid $teal-main; - background-color: $white; border-radius: 3px; - color: $black; font-size: .8em; cursor: pointer; font-family: poppins_light; @@ -36,7 +48,6 @@ button, color: $white; } &:before { - color: $grey-dark; content: '+'; /* Unicode character for "plus" sign (+) */ font-family: space_bold; font-size: 36px; diff --git a/IDE/frontend-dev/scss/_console.scss b/IDE/frontend-dev/scss/_console.scss index 5f2ebdb13..5ec33daa2 100644 --- a/IDE/frontend-dev/scss/_console.scss +++ b/IDE/frontend-dev/scss/_console.scss @@ -1,5 +1,12 @@ +// color-themed console elements +@include themify($themes) { + #beaglert-console { + background-color: themed('main-background-color'); + color: themed('main-font-color'); + } +} + #beaglert-console { - background-color: white; box-sizing: border-box; font-family: inconsolata, monospace; font-size: 12px; diff --git a/IDE/frontend-dev/scss/_dropdown-mini.scss b/IDE/frontend-dev/scss/_dropdown-mini.scss index 2dd776bdc..edd34fae4 100644 --- a/IDE/frontend-dev/scss/_dropdown-mini.scss +++ b/IDE/frontend-dev/scss/_dropdown-mini.scss @@ -1,3 +1,10 @@ +// color-themed sub-accordion elements +@include themify($themes) { + .mini-dropdown select{ + color: themed('accordion-font-color'); + } +} + .mini-dropdown select { -moz-appearance: none; -webkit-appearance: none; diff --git a/IDE/frontend-dev/scss/_dropdown.scss b/IDE/frontend-dev/scss/_dropdown.scss index e50574677..3e2d16a3d 100644 --- a/IDE/frontend-dev/scss/_dropdown.scss +++ b/IDE/frontend-dev/scss/_dropdown.scss @@ -1,7 +1,29 @@ -/* Dropdown Button */ +// color-themed dropdown button elements +@include themify($themes) { + button.dropbtn { + background-color: themed('selected-tab-color'); + } + .dropdown-content { + background-color: themed('hovered-accordion-color-two'); + select { + option { + color: themed('main-font-color'); + } + } + ul { + > li, span, a { + color: themed('main-font-color'); + &:hover { + background-color: themed('cursor-color'); + color: themed('main-font-color-accent'); + } + } + } + } +} +/* Dropdown Button */ button.dropbtn { - background-color: #fff; border: 1px solid $teal-main; color: $teal-main; cursor: pointer; @@ -75,7 +97,6 @@ select.dropdown-num { /* Dropdown content (hidden by default) */ .dropdown-content { - background-color: #f9f9f9; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); display: none; min-width: 160px; @@ -92,7 +113,6 @@ select.dropdown-num { padding-top: 0; width: 200px; option { - color: black; cursor: pointer; display: block; font-family: poppins_regular; @@ -123,7 +143,6 @@ select.dropdown-num { user-select: none; } > li, span, a { - color: black; cursor: pointer; display: block; font-family: poppins_regular; @@ -131,10 +150,6 @@ select.dropdown-num { opacity: 1; padding: 8px 16px; text-decoration: none; - &:hover { - background-color: $grey-light; - color: rgba(0, 0, 0, 0.9); - } } } &.show { diff --git a/IDE/frontend-dev/scss/_editor.scss b/IDE/frontend-dev/scss/_editor.scss index 7201705f3..6ff7b8b88 100644 --- a/IDE/frontend-dev/scss/_editor.scss +++ b/IDE/frontend-dev/scss/_editor.scss @@ -1,5 +1,9 @@ +// color-themed editor elements +@include themify($themes) { + background: themed('main-background-color'); +} + #editor { - background: #fff; display: none; float: left; height: calc(100% - 70px); diff --git a/IDE/frontend-dev/scss/_library-list.scss b/IDE/frontend-dev/scss/_library-list.scss index 4bffad8c6..27766faea 100644 --- a/IDE/frontend-dev/scss/_library-list.scss +++ b/IDE/frontend-dev/scss/_library-list.scss @@ -1,3 +1,14 @@ +// color-themed library list elements +@include themify($themes) { + ul { + .libraries-list { + li { + color: themed('accordion-font-color-accent'); + } + } + } +} + ul { &.libraries-list-parent { list-style: none; @@ -68,7 +79,6 @@ ul { } .libraries-list { li { - color: rgba(0, 0, 0, 0.8); cursor: pointer; font-family: inconsolata; font-size: 14px; diff --git a/IDE/frontend-dev/scss/_popup.scss b/IDE/frontend-dev/scss/_popup.scss index 4bcec16f0..5483cc4fc 100644 --- a/IDE/frontend-dev/scss/_popup.scss +++ b/IDE/frontend-dev/scss/_popup.scss @@ -1,3 +1,15 @@ +// color-themed popup elements +@include themify($themes) { + #popup { + background: themed('selected-tab-color'); + } + button { + &.cancel { + background: themed('selected-tab-color'); + } + } +} + #popup-nointeraction { display: none; height: 100vh; @@ -134,7 +146,6 @@ } } &.cancel { - background: $white; border: 1px solid $grey-mid; &:hover { background: $grey-light-mid; diff --git a/IDE/frontend-dev/scss/_tab-content.scss b/IDE/frontend-dev/scss/_tab-content.scss index 0478d785b..ce4b66961 100644 --- a/IDE/frontend-dev/scss/_tab-content.scss +++ b/IDE/frontend-dev/scss/_tab-content.scss @@ -1,5 +1,29 @@ +// color-themed tab elements +@include themify($themes) { + .choice { + color: themed('accordion-font-color'); + } + p.project { + color: themed('main-font-color') + } + .project-actions { + >.project-text { + color: themed('accordion-font-color-accent'); + } + } + input[type="checkbox"].checkbox-slider, + .checkbox-slider input[type="checkbox"] { + &::before { + background: themed('checkbox-slider-color'); + } + } + textarea { + background-color: themed('text-area-color'); + color: themed('main-font-color'); + } +} + .choice { - color: rgba(0, 0, 0, 0.6); font-family: poppins_light; font-size: 12px; padding-bottom: 10px; @@ -82,7 +106,6 @@ input[type="checkbox"].checkbox-slider, } &::before { - background: #ccc; border-radius: 18px; height: 18px; transition: background-color 200ms; @@ -161,7 +184,6 @@ p.project { >.project-text { display: inline; font-family: 'inconsolata'; - color: $grey-dark; font-size: .85em; position: absolute; top: 0; diff --git a/IDE/frontend-dev/scss/_tab-menu.scss b/IDE/frontend-dev/scss/_tab-menu.scss index d69dfad42..b98af5720 100644 --- a/IDE/frontend-dev/scss/_tab-menu.scss +++ b/IDE/frontend-dev/scss/_tab-menu.scss @@ -1,15 +1,60 @@ +// color-themed tab menu elements +@include themify($themes) { + #tab-menu { + li#open-tab { + background-color: themed('tabs-color'); + } + li { + background: themed('tabs-color'); + &.explorer { + &.active{ + background: themed('selected-tab-color') url('../images/icons/folder_active.svg') no-repeat center; + } + } + &.examples { + &.active { + background: themed('selected-tab-color') url('../images/icons/examples_active.svg') no-repeat center; + } + } + &.settings { + &.active { + background: themed('selected-tab-color') url('../images/icons/settings_active.svg') no-repeat center; + } + } + &.pins { + &.active { + background: themed('selected-tab-color') url('../images/icons/pins_active.svg') no-repeat center; + } + } + &.refs { + &.active { + background: themed('selected-tab-color') url('../images/icons/refs_active.svg') no-repeat center; + } + } + &.libraries { + &.active { + background: themed('selected-tab-color') url('../images/icons/library_green.svg') no-repeat center; + } + } + &.feedback { + &.active { + background: themed('selected-tab-color') url('../images/icons/feedback_active.svg') no-repeat center; + } + } + } + } +} + /* * Make each label stack on top of one another. * */ #tab-menu { li#open-tab { - background-color: $grey-tabs; max-width: 40px; padding-left: 10px; } li { - background: $grey-tabs; cursor: pointer; height: 50px; padding: 0; @@ -31,54 +76,36 @@ &:hover { background: url('../images/icons/folder_active.svg') no-repeat center; } - &.active{ - background: $white url('../images/icons/folder_active.svg') no-repeat center; - } } &.examples { background: url('../images/icons/examples_inactive.svg') no-repeat center; &:hover { background: url('../images/icons/examples_active.svg') no-repeat center; } - &.active { - background: $white url('../images/icons/examples_active.svg') no-repeat center; - } } &.settings { background: url('../images/icons/settings_inactive.svg') no-repeat center; &:hover { background: url('../images/icons/settings_active.svg') no-repeat center; } - &.active { - background: $white url('../images/icons/settings_active.svg') no-repeat center; - } } &.pins { background: url('../images/icons/pins_inactive.svg') no-repeat center; &:hover { background: url('../images/icons/pins_active.svg') no-repeat center; } - &.active { - background: $white url('../images/icons/pins_active.svg') no-repeat center; - } } &.refs { background: url('../images/icons/refs_inactive.svg') no-repeat center; &:hover { background: url('../images/icons/refs_active.svg') no-repeat center; } - &.active { - background: $white url('../images/icons/refs_active.svg') no-repeat center; - } } &.libraries { background: url('../images/icons/library_white.svg') no-repeat center; &:hover { background: url('../images/icons/library_green.svg') no-repeat center; } - &.active { - background: $white url('../images/icons/library_green.svg') no-repeat center; - } } &.feedback { background: url('../images/icons/feedback_inactive.svg') no-repeat center; @@ -86,7 +113,6 @@ background: url('../images/icons/feedback_active.svg') no-repeat center; } &.active { - background: $white url('../images/icons/feedback_active.svg') no-repeat center; border-left: 5px solid $accent-red; } } diff --git a/IDE/frontend-dev/scss/_tabs.scss b/IDE/frontend-dev/scss/_tabs.scss index babf9bd14..65e2bda63 100644 --- a/IDE/frontend-dev/scss/_tabs.scss +++ b/IDE/frontend-dev/scss/_tabs.scss @@ -1,8 +1,28 @@ +// color-themed tabs elements +@include themify($themes) { + //.tabs { + //background-color: themed('tabs-color'); + //} + #tab-menu { + background-color: themed('tabs-color'); + } + #tab-content-area { + background-color: themed('main-background-color'); + } + section#tab-content { + .title-container { + background-color: themed('main-background-color'); + h1 { + color: themed('accordion-font-color-accent'); + } + } + } +} + $tab-width: 450px; /* Tabbed content */ .tabs { - background-color: white; height: calc(100% + 35px); left: calc(100% - 50px); position: absolute; @@ -23,14 +43,12 @@ $tab-width: 450px; } #tab-menu { - background-color: $grey-tabs; float: left; height: 100%; width: 50px; } #tab-content-area { - background-color: #fff; height: calc(100% - 76px); overflow: auto; } @@ -43,7 +61,6 @@ section#tab-content { display: none; } .title-container { - background-color: $white; height: 75px; position: sticky; position: -webkit-sticky; /* Required for Safari */ @@ -56,7 +73,6 @@ section#tab-content { } h1 { border-bottom: 10px solid $teal-01; - color: rgba(0, 0, 0, 0.8); display: inline-block; font-family: space_bold; font-size: 24px; diff --git a/IDE/frontend-dev/scss/_text-input.scss b/IDE/frontend-dev/scss/_text-input.scss index 0d358ecbb..0797ad114 100644 --- a/IDE/frontend-dev/scss/_text-input.scss +++ b/IDE/frontend-dev/scss/_text-input.scss @@ -1,9 +1,17 @@ +// color-themed text input elements +@include themify($themes) { + input[type="text"], + input[type="number"] { + background: themed('main-background-color'); + color: themed('main-font-color-accent'); + } +} + // INPUTS input[type="text"], input[type="number"] { height: 25px; border: 1px solid $grey-mid; - background: $white; &.number-picker { border-radius: 0; width: 5em; diff --git a/IDE/frontend-dev/scss/_toolbar.scss b/IDE/frontend-dev/scss/_toolbar.scss index 7231df15a..fdaf3e139 100644 --- a/IDE/frontend-dev/scss/_toolbar.scss +++ b/IDE/frontend-dev/scss/_toolbar.scss @@ -1,3 +1,16 @@ +// color-themed toolbar elements +@include themify($themes) { + .toolbar { + background: themed('tabs-color'); + .tool-text { + color: themed('main-font-color'); + } + .system-status-text { + color: themed('main-font-color') !important; + } + } +} + @keyframes running-button { from { transform: rotate(0deg); @@ -17,7 +30,6 @@ .toolbar { - background: $grey-toolbar; bottom: 0; box-shadow: 5px 5px #eee; display: block; diff --git a/IDE/frontend-dev/scss/_upper.scss b/IDE/frontend-dev/scss/_upper.scss index bb651ffda..379fcefaa 100644 --- a/IDE/frontend-dev/scss/_upper.scss +++ b/IDE/frontend-dev/scss/_upper.scss @@ -1,3 +1,13 @@ +// color-themed top bar elements +@include themify($themes) { + .file-status { + .current { + color: themed('accordion-font-color'); + background-color: themed('top-file-status-color'); + } + } +} + .file-status { margin-left: 60px; white-space: nowrap; @@ -30,7 +40,6 @@ } .current { font-family: poppins_regular; - color: rgba(0, 0, 0, 0.7); padding-right: 20px; font-size: 12px; } From 51f33d30a981f76e8e1d4dc01aa8cb83d220905c Mon Sep 17 00:00:00 2001 From: Laimonade Date: Wed, 14 Feb 2024 23:22:50 +0000 Subject: [PATCH 184/188] implemented main logic for color-theme switching --- IDE/frontend-dev/scss/base.scss | 78 +++++++++++++++++++++++++++++++-- 1 file changed, 75 insertions(+), 3 deletions(-) diff --git a/IDE/frontend-dev/scss/base.scss b/IDE/frontend-dev/scss/base.scss index 26e061da4..55625b800 100644 --- a/IDE/frontend-dev/scss/base.scss +++ b/IDE/frontend-dev/scss/base.scss @@ -5,7 +5,7 @@ $black: #000; $white: #ffffff; // Base Material palette teal: -$teal-base: #009587; +$teal-base: #950000; // Main Bela color: $teal-main: #00bea4; //rgb(0,190,164) @@ -38,6 +38,59 @@ $trans-reg: 0.1s; $yellow-accent: #fff07c; $yellow-accent-fade: #FFFFC9; +$themes: ( + light: ( + main-background-color: $white, + tabs-color: $grey-toolbar, + selected-tab-color: $white, + top-file-status-color: #e1e1e1, + accordion-background-color: $grey-light, + hovered-accordion-color: $grey-mid, + accordion-font-color: rgba(0, 0, 0, 0.6), + accordion-font-color-accent: $grey-dark, + main-font-color: $black, + hovered-accordion-color-two: #f9f9f9, + main-font-color-accent: $black, + cursor-color: $grey-light, + console-dragger-color: #999, + console-dragger-opacity: 0.001, + console-dragged-color: #bbb, + checkbox-slider-color: #ccc, + text-area-color: $white, + ), + dark: ( + main-background-color: #292a2f, + tabs-color: #252729, + selected-tab-color: #252729, + top-file-status-color: #252729, + accordion-background-color: #3f4045, + hovered-accordion-color: #3e4d5c, + accordion-font-color: #dfdfe0, + accordion-font-color-accent: #ededf2, + main-font-color: #dfdfe0, + hovered-accordion-color-two: #3f4045, + main-font-color-accent: #ededf2, + cursor-color: rgb(44,44,44), + console-dragger-color: #3f4045, + console-dragger-opacity: 1, + console-dragged-color: #5a5a62, + checkbox-slider-color: #5a5a62, + text-area-color: #292a2f, + ) +); + +@mixin themify($themes) { + @each $name, $values in $themes { + .#{$name}-theme { + $theme-map: $values !global; + @content; + } + } +} +@function themed($key) { + @return map-get($theme-map, $key); +} + @import 'reset'; @import 'fonts'; @@ -61,9 +114,28 @@ img { display: none; } +// color-themed top bar elements +@include themify($themes) { + .upper { + background-color: themed('top-file-status-color'); + } + .lm_content { + border: 1px solid themed('tabs-color'); + } + .lm_splitter { + background-color: themed('console-dragger-color') !important; + opacity: themed('console-dragger-opacity'); + &:hover { + background-color: themed('console-dragged-color') !important; + } + } + + +} + .upper { - height: 100%; - position: relative; + height: 100%; + position: relative; z-index: 96; } From f7c020b5d84698bc996f22215b58d0894d78d606 Mon Sep 17 00:00:00 2001 From: Laimonade Date: Wed, 14 Feb 2024 23:24:37 +0000 Subject: [PATCH 185/188] implemented function to switch editor & css class themes --- IDE/frontend-dev/src/Views/EditorView.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/IDE/frontend-dev/src/Views/EditorView.js b/IDE/frontend-dev/src/Views/EditorView.js index 8cc7f5a63..0541902d0 100644 --- a/IDE/frontend-dev/src/Views/EditorView.js +++ b/IDE/frontend-dev/src/Views/EditorView.js @@ -338,6 +338,20 @@ class EditorView extends View { currentFile = name; } + // switch between light and dark theme + _darkTheme(isDarkTheme){ + var body = $('body'); + if (isDarkTheme) { + this.editor.setTheme("ace/theme/xcode_dark"); + body.toggleClass('light-theme', Boolean(false)); + body.toggleClass('dark-theme', Boolean(true)); + } else { + this.editor.setTheme("ace/theme/chrome"); + body.toggleClass('dark-theme', Boolean(false)); + body.toggleClass('light-theme', Boolean(true)); + } + } + getCurrentWord(){ var pos = this.editor.getCursorPosition(); //var range = this.editor.session.getAWordRange(pos.row, pos.column); From 01d4c9ae53155b0ec1174907e69678f59a4cfcb1 Mon Sep 17 00:00:00 2001 From: Laimonade Date: Wed, 14 Feb 2024 23:25:48 +0000 Subject: [PATCH 186/188] implemented custom xcode dark theme editor --- IDE/public/js/ace/theme-xcode_dark.js | 1 - 1 file changed, 1 deletion(-) diff --git a/IDE/public/js/ace/theme-xcode_dark.js b/IDE/public/js/ace/theme-xcode_dark.js index 55ad74580..53fcf4d45 100644 --- a/IDE/public/js/ace/theme-xcode_dark.js +++ b/IDE/public/js/ace/theme-xcode_dark.js @@ -15,7 +15,6 @@ background: #292A2F;\ .ace-xcode-dark {\ display: block;\ overflow-x: auto;\ -padding: .5em;\ color: #DFDFE0;\ background-color: #292A2F;\ }\ From ac5085aef23e28a0e59b41e259c47e9febf404ec Mon Sep 17 00:00:00 2001 From: Laimonade Date: Wed, 14 Feb 2024 23:27:48 +0000 Subject: [PATCH 187/188] transpiled css from scss --- IDE/public/css/style.css | 353 ++++++++++++++++++++++++++++++++------- 1 file changed, 295 insertions(+), 58 deletions(-) diff --git a/IDE/public/css/style.css b/IDE/public/css/style.css index 674045dff..06facdf6e 100644 --- a/IDE/public/css/style.css +++ b/IDE/public/css/style.css @@ -80,6 +80,30 @@ img { .hidden { display: none; } +.light-theme .upper { + background-color: #e1e1e1; } + +.light-theme .lm_content { + border: 1px solid #c9c9c9; } + +.light-theme .lm_splitter { + background-color: #999 !important; + opacity: 0.001; } + .light-theme .lm_splitter:hover { + background-color: #bbb !important; } + +.dark-theme .upper { + background-color: #252729; } + +.dark-theme .lm_content { + border: 1px solid #252729; } + +.dark-theme .lm_splitter { + background-color: #3f4045 !important; + opacity: 1; } + .dark-theme .lm_splitter:hover { + background-color: #5a5a62 !important; } + .upper { height: 100%; position: relative; @@ -143,11 +167,68 @@ body.uploading { ul { font-family: inconsolata; } -button.accordion { +.light-theme button.accordion { background-color: #f1f1f1; + border-bottom: 2px solid #ffffff; + color: rgba(0, 0, 0, 0.6); } + .light-theme button.accordion:hover { + background: #bdbdbd; } + .light-theme button.accordion.active { + background-color: #f1f1f1; + color: rgba(0, 0, 0, 0.8); } + .light-theme button.accordion.active:hover { + color: rgba(0, 0, 0, 0.8); } + .light-theme button.accordion:after { + color: rgba(0, 0, 0, 0.6); } + +.light-theme button.accordion-sub { + border-bottom: 1px solid #c9c9c9; + color: rgba(0, 0, 0, 0.8); } + .light-theme button.accordion-sub:hover { + color: rgba(0, 0, 0, 0.8); } + .light-theme button.accordion-sub.active { + color: rgba(0, 0, 0, 0.8); } + .light-theme button.accordion-sub.active:hover { + color: rgba(0, 0, 0, 0.8); } + +.light-theme .docs-content { + color: #000; } + +.light-theme .panel.show { + color: #000; } + +.dark-theme button.accordion { + background-color: #3f4045; + border-bottom: 2px solid #292a2f; + color: #dfdfe0; } + .dark-theme button.accordion:hover { + background: #3e4d5c; } + .dark-theme button.accordion.active { + background-color: #3f4045; + color: #ededf2; } + .dark-theme button.accordion.active:hover { + color: #ededf2; } + .dark-theme button.accordion:after { + color: #dfdfe0; } + +.dark-theme button.accordion-sub { + border-bottom: 1px solid #252729; + color: #ededf2; } + .dark-theme button.accordion-sub:hover { + color: #ededf2; } + .dark-theme button.accordion-sub.active { + color: #ededf2; } + .dark-theme button.accordion-sub.active:hover { + color: #ededf2; } + +.dark-theme .docs-content { + color: #dfdfe0; } + +.dark-theme .panel.show { + color: #dfdfe0; } + +button.accordion { border: none; - border-bottom: 2px solid #fff; - color: rgba(0, 0, 0, 0.6); cursor: pointer; font-family: poppins_regular; font-size: 16px; @@ -159,20 +240,14 @@ button.accordion { transition: 0.25s ease-in-out; width: 100%; } button.accordion:hover { - background: #bdbdbd; border-bottom: 2px solid #00bea4; } button.accordion.active { - background-color: #f1f1f1; border-bottom: 2px solid #00bea4; - color: rgba(0, 0, 0, 0.8); padding: 8px 14px; } - button.accordion.active:hover { - color: rgba(0, 0, 0, 0.8); } button.accordion.active:after { content: "\2796"; /* Unicode character for "minus" sign (-) */ } button.accordion:after { - color: rgba(0, 0, 0, 0.6); content: '\02795'; /* Unicode character for "plus" sign (+) */ float: right; @@ -181,28 +256,22 @@ button.accordion { button.accordion-sub { background: transparent; - border-bottom: 1px solid #c9c9c9; border-top: 0; border-left: 0; border-right: 0; border-radius: 0; - color: rgba(0, 0, 0, 0.8); font-size: 1em; font-family: 'poppins_regular'; padding: .4em .8em .25em; text-align: left; width: 100%; } button.accordion-sub:hover { - background: rgba(201, 201, 201, 0.2); - color: rgba(0, 0, 0, 0.8); } + background: rgba(201, 201, 201, 0.2); } button.accordion-sub.active { background: transparent; border-bottom: 2px solid #1ce8b5; - color: rgba(0, 0, 0, 0.8); padding-bottom: .2em; margin-top: .2em; } - button.accordion-sub.active:hover { - color: rgba(0, 0, 0, 0.8); } button.accordion-sub.active:after { content: "\2796"; /* Unicode character for "minus" sign (-) */ @@ -240,6 +309,22 @@ button.accordion-sub { /* Whatever you like, as long as its more than the height of the content (on all screen sizes) */ opacity: 1; } +.light-theme button, +.light-theme .button { + background-color: #ffffff; + color: #000; } + .light-theme button.create-project:before, + .light-theme .button.create-project:before { + color: rgba(0, 0, 0, 0.8); } + +.dark-theme button, +.dark-theme .button { + background-color: #292a2f; + color: #dfdfe0; } + .dark-theme button.create-project:before, + .dark-theme .button.create-project:before { + color: #ededf2; } + a.button { color: black; font-size: 11px; @@ -250,9 +335,7 @@ a.button { button, .button { border: 1px solid #00bea4; - background-color: #ffffff; border-radius: 3px; - color: #000; font-size: .8em; cursor: pointer; font-family: poppins_light; @@ -279,7 +362,6 @@ button, color: #ffffff; } button.create-project:before, .button.create-project:before { - color: rgba(0, 0, 0, 0.8); content: '+'; /* Unicode character for "plus" sign (+) */ font-family: space_bold; @@ -339,8 +421,15 @@ input[type="range"].range-slider { -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4); box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4); } +.light-theme #beaglert-console { + background-color: #ffffff; + color: #000; } + +.dark-theme #beaglert-console { + background-color: #292a2f; + color: #dfdfe0; } + #beaglert-console { - background-color: white; -webkit-box-sizing: border-box; box-sizing: border-box; font-family: inconsolata, monospace; @@ -608,14 +697,39 @@ input[type="range"].range-slider { margin: 0; } .subsections .examples-header { - color: #009587; + color: #950000; font-family: space_bold; font-size: 1.1em; margin: .5em; } +.light-theme button.dropbtn { + background-color: #ffffff; } + +.light-theme .dropdown-content { + background-color: #f9f9f9; } + .light-theme .dropdown-content select option { + color: #000; } + .light-theme .dropdown-content ul > li, .light-theme .dropdown-content ul span, .light-theme .dropdown-content ul a { + color: #000; } + .light-theme .dropdown-content ul > li:hover, .light-theme .dropdown-content ul span:hover, .light-theme .dropdown-content ul a:hover { + background-color: #f1f1f1; + color: #000; } + +.dark-theme button.dropbtn { + background-color: #252729; } + +.dark-theme .dropdown-content { + background-color: #3f4045; } + .dark-theme .dropdown-content select option { + color: #dfdfe0; } + .dark-theme .dropdown-content ul > li, .dark-theme .dropdown-content ul span, .dark-theme .dropdown-content ul a { + color: #dfdfe0; } + .dark-theme .dropdown-content ul > li:hover, .dark-theme .dropdown-content ul span:hover, .dark-theme .dropdown-content ul a:hover { + background-color: #2c2c2c; + color: #ededf2; } + /* Dropdown Button */ button.dropbtn { - background-color: #fff; border: 1px solid #00bea4; color: #00bea4; cursor: pointer; @@ -677,7 +791,6 @@ select.dropdown-num { /* Dropdown content (hidden by default) */ .dropdown-content { - background-color: #f9f9f9; -webkit-box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2); box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2); display: none; @@ -695,7 +808,6 @@ select.dropdown-num { padding-top: 0; width: 200px; } .dropdown-content select option { - color: black; cursor: pointer; display: block; font-family: poppins_regular; @@ -724,7 +836,6 @@ select.dropdown-num { -ms-user-select: none; user-select: none; } .dropdown-content ul > li, .dropdown-content ul span, .dropdown-content ul a { - color: black; cursor: pointer; display: block; font-family: poppins_regular; @@ -732,12 +843,15 @@ select.dropdown-num { opacity: 1; padding: 8px 16px; text-decoration: none; } - .dropdown-content ul > li:hover, .dropdown-content ul span:hover, .dropdown-content ul a:hover { - background-color: #f1f1f1; - color: rgba(0, 0, 0, 0.9); } .dropdown-content.show { display: block; } +.light-theme .mini-dropdown select { + color: rgba(0, 0, 0, 0.6); } + +.dark-theme .mini-dropdown select { + color: #dfdfe0; } + .mini-dropdown select { -moz-appearance: none; -webkit-appearance: none; @@ -785,8 +899,13 @@ select.dropdown-num { .mini-dropdown.disabled:after { color: rgba(0, 0, 0, 0.4); } +.light-theme { + background: #ffffff; } + +.dark-theme { + background: #292a2f; } + #editor { - background: #fff; display: none; float: left; height: calc(100% - 70px); @@ -982,6 +1101,12 @@ img.explorer { img.explorer:hover { background: url("images/icons/explorer_green.svg"); } +.light-theme ul .libraries-list li { + color: rgba(0, 0, 0, 0.8); } + +.dark-theme ul .libraries-list li { + color: #ededf2; } + ul.libraries-list-parent { list-style: none; margin: 0; @@ -1044,7 +1169,6 @@ ul.libraries-list-parent { margin-block-end: 0; margin: .5em 0 0 .5em; } ul.libraries-list-parent .libraries-list li { - color: rgba(0, 0, 0, 0.8); cursor: pointer; font-family: inconsolata; font-size: 14px; @@ -1183,6 +1307,18 @@ ul dl { fill: rgba(0, 255, 0, 0.6); stroke: none; } +.light-theme #popup { + background: #ffffff; } + +.light-theme button.cancel { + background: #ffffff; } + +.dark-theme #popup { + background: #252729; } + +.dark-theme button.cancel { + background: #252729; } + #popup-nointeraction { display: none; height: 100vh; @@ -1294,7 +1430,6 @@ ul dl { #popup button.confirm.button-disabled { background: #bdbdbd; } #popup button.cancel { - background: #ffffff; border: 1px solid #bdbdbd; } #popup button.cancel:hover { background: #e5e5e5; @@ -1329,9 +1464,30 @@ ul dl { border-radius: 10px; -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.5); } +.light-theme #tab-menu { + background-color: #c9c9c9; } + +.light-theme #tab-content-area { + background-color: #ffffff; } + +.light-theme section#tab-content .title-container { + background-color: #ffffff; } + .light-theme section#tab-content .title-container h1 { + color: rgba(0, 0, 0, 0.8); } + +.dark-theme #tab-menu { + background-color: #252729; } + +.dark-theme #tab-content-area { + background-color: #292a2f; } + +.dark-theme section#tab-content .title-container { + background-color: #292a2f; } + .dark-theme section#tab-content .title-container h1 { + color: #ededf2; } + /* Tabbed content */ .tabs { - background-color: white; height: calc(100% + 35px); left: calc(100% - 50px); position: absolute; @@ -1350,13 +1506,11 @@ ul dl { left: calc(100% - 438px); } #tab-menu { - background-color: #c9c9c9; float: left; height: 100%; width: 50px; } #tab-content-area { - background-color: #fff; height: calc(100% - 76px); overflow: auto; } @@ -1367,7 +1521,6 @@ section#tab-content { section#tab-content .tab-info { display: none; } section#tab-content .title-container { - background-color: #ffffff; height: 75px; position: sticky; position: -webkit-sticky; @@ -1380,7 +1533,6 @@ section#tab-content { background: transparent; } section#tab-content .title-container h1 { border-bottom: 10px solid #1ce8b5; - color: rgba(0, 0, 0, 0.8); display: inline-block; font-family: space_bold; font-size: 24px; @@ -1389,8 +1541,41 @@ section#tab-content { .disabled { display: none; } +.light-theme .choice { + color: rgba(0, 0, 0, 0.6); } + +.light-theme p.project { + color: #000; } + +.light-theme .project-actions > .project-text { + color: rgba(0, 0, 0, 0.8); } + +.light-theme input[type="checkbox"].checkbox-slider::before, +.light-theme .checkbox-slider input[type="checkbox"]::before { + background: #ccc; } + +.light-theme textarea { + background-color: #ffffff; + color: #000; } + +.dark-theme .choice { + color: #dfdfe0; } + +.dark-theme p.project { + color: #dfdfe0; } + +.dark-theme .project-actions > .project-text { + color: #ededf2; } + +.dark-theme input[type="checkbox"].checkbox-slider::before, +.dark-theme .checkbox-slider input[type="checkbox"]::before { + background: #5a5a62; } + +.dark-theme textarea { + background-color: #292a2f; + color: #dfdfe0; } + .choice { - color: rgba(0, 0, 0, 0.6); font-family: poppins_light; font-size: 12px; padding-bottom: 10px; } @@ -1461,7 +1646,6 @@ input[type="checkbox"].checkbox-slider, position: absolute; } input[type="checkbox"].checkbox-slider::before, .checkbox-slider input[type="checkbox"]::before { - background: #ccc; border-radius: 18px; height: 18px; -webkit-transition: background-color 200ms; @@ -1530,7 +1714,6 @@ p.project { .project-actions > .project-text { display: inline; font-family: 'inconsolata'; - color: rgba(0, 0, 0, 0.8); font-size: .85em; position: absolute; top: 0; @@ -1619,17 +1802,55 @@ p.project { .tab-info button.feedback.bug:hover { background-color: #ff5e5b; } +.light-theme #tab-menu li#open-tab { + background-color: #c9c9c9; } + +.light-theme #tab-menu li { + background: #c9c9c9; } + .light-theme #tab-menu li.explorer.active { + background: #ffffff url("../images/icons/folder_active.svg") no-repeat center; } + .light-theme #tab-menu li.examples.active { + background: #ffffff url("../images/icons/examples_active.svg") no-repeat center; } + .light-theme #tab-menu li.settings.active { + background: #ffffff url("../images/icons/settings_active.svg") no-repeat center; } + .light-theme #tab-menu li.pins.active { + background: #ffffff url("../images/icons/pins_active.svg") no-repeat center; } + .light-theme #tab-menu li.refs.active { + background: #ffffff url("../images/icons/refs_active.svg") no-repeat center; } + .light-theme #tab-menu li.libraries.active { + background: #ffffff url("../images/icons/library_green.svg") no-repeat center; } + .light-theme #tab-menu li.feedback.active { + background: #ffffff url("../images/icons/feedback_active.svg") no-repeat center; } + +.dark-theme #tab-menu li#open-tab { + background-color: #252729; } + +.dark-theme #tab-menu li { + background: #252729; } + .dark-theme #tab-menu li.explorer.active { + background: #252729 url("../images/icons/folder_active.svg") no-repeat center; } + .dark-theme #tab-menu li.examples.active { + background: #252729 url("../images/icons/examples_active.svg") no-repeat center; } + .dark-theme #tab-menu li.settings.active { + background: #252729 url("../images/icons/settings_active.svg") no-repeat center; } + .dark-theme #tab-menu li.pins.active { + background: #252729 url("../images/icons/pins_active.svg") no-repeat center; } + .dark-theme #tab-menu li.refs.active { + background: #252729 url("../images/icons/refs_active.svg") no-repeat center; } + .dark-theme #tab-menu li.libraries.active { + background: #252729 url("../images/icons/library_green.svg") no-repeat center; } + .dark-theme #tab-menu li.feedback.active { + background: #252729 url("../images/icons/feedback_active.svg") no-repeat center; } + /* * Make each label stack on top of one another. * */ #tab-menu li#open-tab { - background-color: #c9c9c9; max-width: 40px; padding-left: 10px; } #tab-menu li { - background: #c9c9c9; cursor: pointer; height: 50px; padding: 0; @@ -1650,44 +1871,31 @@ p.project { background: url("../images/icons/folder_inactive.svg") no-repeat center; } #tab-menu li.explorer:hover { background: url("../images/icons/folder_active.svg") no-repeat center; } - #tab-menu li.explorer.active { - background: #ffffff url("../images/icons/folder_active.svg") no-repeat center; } #tab-menu li.examples { background: url("../images/icons/examples_inactive.svg") no-repeat center; } #tab-menu li.examples:hover { background: url("../images/icons/examples_active.svg") no-repeat center; } - #tab-menu li.examples.active { - background: #ffffff url("../images/icons/examples_active.svg") no-repeat center; } #tab-menu li.settings { background: url("../images/icons/settings_inactive.svg") no-repeat center; } #tab-menu li.settings:hover { background: url("../images/icons/settings_active.svg") no-repeat center; } - #tab-menu li.settings.active { - background: #ffffff url("../images/icons/settings_active.svg") no-repeat center; } #tab-menu li.pins { background: url("../images/icons/pins_inactive.svg") no-repeat center; } #tab-menu li.pins:hover { background: url("../images/icons/pins_active.svg") no-repeat center; } - #tab-menu li.pins.active { - background: #ffffff url("../images/icons/pins_active.svg") no-repeat center; } #tab-menu li.refs { background: url("../images/icons/refs_inactive.svg") no-repeat center; } #tab-menu li.refs:hover { background: url("../images/icons/refs_active.svg") no-repeat center; } - #tab-menu li.refs.active { - background: #ffffff url("../images/icons/refs_active.svg") no-repeat center; } #tab-menu li.libraries { background: url("../images/icons/library_white.svg") no-repeat center; } #tab-menu li.libraries:hover { background: url("../images/icons/library_green.svg") no-repeat center; } - #tab-menu li.libraries.active { - background: #ffffff url("../images/icons/library_green.svg") no-repeat center; } #tab-menu li.feedback { background: url("../images/icons/feedback_inactive.svg") no-repeat center; } #tab-menu li.feedback:hover { background: url("../images/icons/feedback_active.svg") no-repeat center; } #tab-menu li.feedback.active { - background: #ffffff url("../images/icons/feedback_active.svg") no-repeat center; border-left: 5px solid #ff5e5b; } #tab-menu li.active { background: #ffffff; @@ -1718,11 +1926,20 @@ p.project { .tab-content-area { display: none; } +.light-theme input[type="text"], +.light-theme input[type="number"] { + background: #ffffff; + color: #000; } + +.dark-theme input[type="text"], +.dark-theme input[type="number"] { + background: #292a2f; + color: #ededf2; } + input[type="text"], input[type="number"] { height: 25px; - border: 1px solid #bdbdbd; - background: #ffffff; } + border: 1px solid #bdbdbd; } input[type="text"].number-picker, input[type="number"].number-picker { border-radius: 0; @@ -1732,6 +1949,20 @@ input[type="number"] { input[type="number"]:disabled { background: #f1f1f1; } +.light-theme .toolbar { + background: #c9c9c9; } + .light-theme .toolbar .tool-text { + color: #000; } + .light-theme .toolbar .system-status-text { + color: #000 !important; } + +.dark-theme .toolbar { + background: #252729; } + .dark-theme .toolbar .tool-text { + color: #dfdfe0; } + .dark-theme .toolbar .system-status-text { + color: #dfdfe0 !important; } + @-webkit-keyframes running-button { from { -webkit-transform: rotate(0deg); @@ -1757,7 +1988,6 @@ input[type="number"] { animation: running-button 2s linear infinite; } .toolbar { - background: #c9c9c9; bottom: 0; -webkit-box-shadow: 5px 5px #eee; box-shadow: 5px 5px #eee; @@ -1864,6 +2094,14 @@ input[type="number"] { margin-top: -14px; padding-right: 2.3em; } +.light-theme .file-status .current { + color: rgba(0, 0, 0, 0.6); + background-color: #e1e1e1; } + +.dark-theme .file-status .current { + color: #dfdfe0; + background-color: #252729; } + .file-status { margin-left: 60px; white-space: nowrap; } @@ -1898,7 +2136,6 @@ input[type="number"] { display: inline-block; } .file-status .current { font-family: poppins_regular; - color: rgba(0, 0, 0, 0.7); padding-right: 20px; font-size: 12px; } From fe7dabbe6a658addcb3f20cf362151c60046f2f0 Mon Sep 17 00:00:00 2001 From: Laimonade Date: Wed, 14 Feb 2024 23:28:18 +0000 Subject: [PATCH 188/188] transpiled js from gulp --- IDE/public/js/bundle.js | 37 ++++++++++++++++++------------------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/IDE/public/js/bundle.js b/IDE/public/js/bundle.js index 3324b3a1a..f16f8bc48 100644 --- a/IDE/public/js/bundle.js +++ b/IDE/public/js/bundle.js @@ -2179,25 +2179,6 @@ var EditorView = function (_View) { this.__focus(opts.focus); } } - // editor theme has changed - - }, { - key: '_darkTheme', - value: function _darkTheme(value) { - var isDarkTheme = parseInt(value) - var body = $('body'); - - if (isDarkTheme) { - this.editor.setTheme("ace/theme/xcode_dark"); - // this.editor.setTheme("ace/theme/monokai"); - body.toggleClass('light-theme', Boolean(false)); - body.toggleClass('dark-theme', Boolean(true)); - } else { - this.editor.setTheme("ace/theme/chrome"); - body.toggleClass('dark-theme', Boolean(false)); - body.toggleClass('light-theme', Boolean(true)); - } - } // editor focus has changed }, { @@ -2269,6 +2250,24 @@ var EditorView = function (_View) { value: function _fileName(name, data) { currentFile = name; } + + // switch between light and dark theme + + }, { + key: '_darkTheme', + value: function _darkTheme(isDarkTheme) { + var body = $('body'); + if (isDarkTheme) { + this.editor.setTheme("ace/theme/xcode_dark"); + // this.editor.setTheme("ace/theme/monokai"); + body.toggleClass('light-theme', Boolean(false)); + body.toggleClass('dark-theme', Boolean(true)); + } else { + this.editor.setTheme("ace/theme/chrome"); + body.toggleClass('dark-theme', Boolean(false)); + body.toggleClass('light-theme', Boolean(true)); + } + } }, { key: 'getCurrentWord', value: function getCurrentWord() {