diff --git a/VoiceChangerDemo.ipynb b/VoiceChangerDemo.ipynb
new file mode 100644
index 00000000..bae6e760
--- /dev/null
+++ b/VoiceChangerDemo.ipynb
@@ -0,0 +1,580 @@
+{
+ "nbformat": 4,
+ "nbformat_minor": 0,
+ "metadata": {
+ "colab": {
+ "name": "VoiceChangerDemo",
+ "provenance": [],
+ "collapsed_sections": [],
+ "authorship_tag": "ABX9TyN+8irLJYUFlwMPzvHMSJof",
+ "include_colab_link": true
+ },
+ "kernelspec": {
+ "name": "python3",
+ "display_name": "Python 3"
+ },
+ "language_info": {
+ "name": "python"
+ },
+ "accelerator": "GPU",
+ "gpuClass": "standard"
+ },
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "view-in-github",
+ "colab_type": "text"
+ },
+ "source": [
+ "
"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "source": [],
+ "metadata": {
+ "id": "57p7pA1Qb5wa"
+ }
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "!nvidia-smi"
+ ],
+ "metadata": {
+ "colab": {
+ "base_uri": "https://localhost:8080/"
+ },
+ "id": "vV1t7PBRm-o6",
+ "outputId": "60fc80b2-a39e-4840-88c1-0d8d483a36ca"
+ },
+ "execution_count": 1,
+ "outputs": [
+ {
+ "output_type": "stream",
+ "name": "stdout",
+ "text": [
+ "Wed Aug 31 06:14:56 2022 \n",
+ "+-----------------------------------------------------------------------------+\n",
+ "| NVIDIA-SMI 460.32.03 Driver Version: 460.32.03 CUDA Version: 11.2 |\n",
+ "|-------------------------------+----------------------+----------------------+\n",
+ "| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |\n",
+ "| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |\n",
+ "| | | MIG M. |\n",
+ "|===============================+======================+======================|\n",
+ "| 0 Tesla T4 Off | 00000000:00:04.0 Off | 0 |\n",
+ "| N/A 72C P8 12W / 70W | 0MiB / 15109MiB | 0% Default |\n",
+ "| | | N/A |\n",
+ "+-------------------------------+----------------------+----------------------+\n",
+ " \n",
+ "+-----------------------------------------------------------------------------+\n",
+ "| Processes: |\n",
+ "| GPU GI CI PID Type Process name GPU Memory |\n",
+ "| ID ID Usage |\n",
+ "|=============================================================================|\n",
+ "| No running processes found |\n",
+ "+-----------------------------------------------------------------------------+\n"
+ ]
+ }
+ ]
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "CONFIG=\"/content/drive/MyDrive/VoiceChanger/config.json\"\n",
+ "MODEL=\"/content/drive/MyDrive/VoiceChanger/G_326000.pth\""
+ ],
+ "metadata": {
+ "id": "nSXATMWYb4Ik"
+ },
+ "execution_count": 2,
+ "outputs": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {
+ "colab": {
+ "base_uri": "https://localhost:8080/"
+ },
+ "id": "2wxD-gRSMU5R",
+ "outputId": "83bb80fa-9ced-43e2-a304-d53a3501b142"
+ },
+ "outputs": [
+ {
+ "output_type": "stream",
+ "name": "stdout",
+ "text": [
+ "Mounted at /content/drive\n"
+ ]
+ }
+ ],
+ "source": [
+ "from google.colab import drive\n",
+ "drive.mount('/content/drive')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "!git clone https://github.com/w-okada/voice-changer.git\n",
+ "%cd voice-changer/demo/\n"
+ ],
+ "metadata": {
+ "colab": {
+ "base_uri": "https://localhost:8080/"
+ },
+ "id": "86wTFmqsNMnD",
+ "outputId": "3fc68f14-b6b7-48bb-e285-5bed78e74f26"
+ },
+ "execution_count": 4,
+ "outputs": [
+ {
+ "output_type": "stream",
+ "name": "stdout",
+ "text": [
+ "Cloning into 'voice-changer'...\n",
+ "remote: Enumerating objects: 266, done.\u001b[K\n",
+ "remote: Counting objects: 100% (266/266), done.\u001b[K\n",
+ "remote: Compressing objects: 100% (189/189), done.\u001b[K\n",
+ "remote: Total 266 (delta 123), reused 194 (delta 65), pack-reused 0\u001b[K\n",
+ "Receiving objects: 100% (266/266), 19.11 MiB | 35.44 MiB/s, done.\n",
+ "Resolving deltas: 100% (123/123), done.\n",
+ "/content/voice-changer/demo\n"
+ ]
+ }
+ ]
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "!git checkout dev\n"
+ ],
+ "metadata": {
+ "colab": {
+ "base_uri": "https://localhost:8080/"
+ },
+ "id": "CBsogR-zWH4r",
+ "outputId": "f4c9737b-831d-4938-d387-caf07693030e"
+ },
+ "execution_count": 5,
+ "outputs": [
+ {
+ "output_type": "stream",
+ "name": "stdout",
+ "text": [
+ "Branch 'dev' set up to track remote branch 'dev' from 'origin'.\n",
+ "Switched to a new branch 'dev'\n"
+ ]
+ }
+ ]
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "!mkdir -p ../frontend/dist\n",
+ "!cp -r ../docs/* ../frontend/dist/\n",
+ "!ls ../frontend/dist\n"
+ ],
+ "metadata": {
+ "colab": {
+ "base_uri": "https://localhost:8080/"
+ },
+ "id": "uCEKf3_JNoyq",
+ "outputId": "746e1946-5c3a-49af-df26-d86149f8adb1"
+ },
+ "execution_count": 6,
+ "outputs": [
+ {
+ "output_type": "stream",
+ "name": "stdout",
+ "text": [
+ "assets\t coffee.png index.html index.js.LICENSE.txt\n",
+ "audiolet favicon.ico index.js\n"
+ ]
+ }
+ ]
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "!cp ../template/setting_colab.json ../frontend/dist/assets/setting.json"
+ ],
+ "metadata": {
+ "id": "Bn4kV8TgXp8i"
+ },
+ "execution_count": 11,
+ "outputs": []
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "!cat ../frontend/dist/assets/setting.json"
+ ],
+ "metadata": {
+ "colab": {
+ "base_uri": "https://localhost:8080/"
+ },
+ "id": "pjxPsOOaXXTj",
+ "outputId": "1bf85102-87ed-462c-e732-cffb878d95f3"
+ },
+ "execution_count": 12,
+ "outputs": [
+ {
+ "output_type": "stream",
+ "name": "stdout",
+ "text": [
+ "{\n",
+ " \"app_title\": \"voice-changer\",\n",
+ " \"majar_mode\": \"colab\",\n",
+ " \"voice_changer_server_url\": \"http://localhost:8080/test\",\n",
+ " \"sample_rate\": 48000,\n",
+ " \"buffer_size\": 1024,\n",
+ " \"prefix_chunk_size\": 24,\n",
+ " \"chunk_size\": 24,\n",
+ " \"speaker_ids\": [100, 107, 101, 102, 103],\n",
+ " \"speaker_names\": [\"ずんだもん\", \"user\", \"そら\", \"めたん\", \"つぐみ\"],\n",
+ " \"src_id\": 107,\n",
+ " \"dst_id\": 100,\n",
+ " \"vf_enable\": true,\n",
+ " \"voice_changer_mode\": \"realtime\",\n",
+ " \"gpu\": 0,\n",
+ " \"available_gpus\": [-1, 0, 1, 2, 3, 4],\n",
+ " \"avatar\": {\n",
+ " \"motion_capture_face\": true,\n",
+ " \"motion_capture_upperbody\": true,\n",
+ " \"lip_overwrite_with_voice\": true,\n",
+ " \"avatar_url\": \"./assets/vrm/zundamon/zundamon.vrm\",\n",
+ " \"backgournd_image_url\": \"./assets/images/bg_natural_sougen.jpg\",\n",
+ " \"background_color\": \"#0000dd\",\n",
+ " \"chroma_key\": \"#0000dd\",\n",
+ " \"avatar_canvas_size\": [1280, 720],\n",
+ " \"screen_canvas_size\": [1280, 720]\n",
+ " },\n",
+ " \"advance\": {\n",
+ " \"avatar_draw_skip_rate\": 3,\n",
+ " \"screen_draw_skip_rate\": 3,\n",
+ " \"visualizer_draw_skip_rate\": 3,\n",
+ " \"cross_fade_lower_value\": 0.1,\n",
+ " \"cross_fade_overlap_rate\": 0.03\n",
+ " }\n",
+ "}\n"
+ ]
+ }
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# 手作業\n",
+ "\n",
+ "・configとモデルをdemoフォルダにコピー\n",
+ "\n",
+ "・docsをfrontendに変更\n",
+ "\n",
+ "・setting.jsonをfrontendにコピー\n"
+ ],
+ "metadata": {
+ "id": "8Na2PbLZSWgZ"
+ }
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "!apt-get install -y espeak libsndfile1-dev\n",
+ "!pip install flask\n",
+ "!pip install python-socketio\n",
+ "!pip install eventlet\n",
+ "!pip install unidecode\n",
+ "!pip install phonemizer\n",
+ "!pip install retry\n",
+ "!pip install flask\n",
+ "!pip install flask_cors\n"
+ ],
+ "metadata": {
+ "colab": {
+ "base_uri": "https://localhost:8080/"
+ },
+ "id": "LwZAAuqxX7yY",
+ "outputId": "c67b2741-7a1e-448d-abf9-7b8d8f5e3d15"
+ },
+ "execution_count": 13,
+ "outputs": [
+ {
+ "output_type": "stream",
+ "name": "stdout",
+ "text": [
+ "Reading package lists... Done\n",
+ "Building dependency tree \n",
+ "Reading state information... Done\n",
+ "libsndfile1-dev is already the newest version (1.0.28-4ubuntu0.18.04.2).\n",
+ "The following package was automatically installed and is no longer required:\n",
+ " libnvidia-common-460\n",
+ "Use 'apt autoremove' to remove it.\n",
+ "The following additional packages will be installed:\n",
+ " espeak-data libespeak1 libportaudio2 libsonic0\n",
+ "The following NEW packages will be installed:\n",
+ " espeak espeak-data libespeak1 libportaudio2 libsonic0\n",
+ "0 upgraded, 5 newly installed, 0 to remove and 20 not upgraded.\n",
+ "Need to get 1,219 kB of archives.\n",
+ "After this operation, 3,031 kB of additional disk space will be used.\n",
+ "Get:1 http://archive.ubuntu.com/ubuntu bionic/universe amd64 libportaudio2 amd64 19.6.0-1 [64.6 kB]\n",
+ "Get:2 http://archive.ubuntu.com/ubuntu bionic/main amd64 libsonic0 amd64 0.2.0-6 [13.4 kB]\n",
+ "Get:3 http://archive.ubuntu.com/ubuntu bionic/universe amd64 espeak-data amd64 1.48.04+dfsg-5 [934 kB]\n",
+ "Get:4 http://archive.ubuntu.com/ubuntu bionic/universe amd64 libespeak1 amd64 1.48.04+dfsg-5 [145 kB]\n",
+ "Get:5 http://archive.ubuntu.com/ubuntu bionic/universe amd64 espeak amd64 1.48.04+dfsg-5 [61.6 kB]\n",
+ "Fetched 1,219 kB in 1s (1,636 kB/s)\n",
+ "Selecting previously unselected package libportaudio2:amd64.\n",
+ "(Reading database ... 155676 files and directories currently installed.)\n",
+ "Preparing to unpack .../libportaudio2_19.6.0-1_amd64.deb ...\n",
+ "Unpacking libportaudio2:amd64 (19.6.0-1) ...\n",
+ "Selecting previously unselected package libsonic0:amd64.\n",
+ "Preparing to unpack .../libsonic0_0.2.0-6_amd64.deb ...\n",
+ "Unpacking libsonic0:amd64 (0.2.0-6) ...\n",
+ "Selecting previously unselected package espeak-data:amd64.\n",
+ "Preparing to unpack .../espeak-data_1.48.04+dfsg-5_amd64.deb ...\n",
+ "Unpacking espeak-data:amd64 (1.48.04+dfsg-5) ...\n",
+ "Selecting previously unselected package libespeak1:amd64.\n",
+ "Preparing to unpack .../libespeak1_1.48.04+dfsg-5_amd64.deb ...\n",
+ "Unpacking libespeak1:amd64 (1.48.04+dfsg-5) ...\n",
+ "Selecting previously unselected package espeak.\n",
+ "Preparing to unpack .../espeak_1.48.04+dfsg-5_amd64.deb ...\n",
+ "Unpacking espeak (1.48.04+dfsg-5) ...\n",
+ "Setting up libportaudio2:amd64 (19.6.0-1) ...\n",
+ "Setting up espeak-data:amd64 (1.48.04+dfsg-5) ...\n",
+ "Setting up libsonic0:amd64 (0.2.0-6) ...\n",
+ "Setting up libespeak1:amd64 (1.48.04+dfsg-5) ...\n",
+ "Setting up espeak (1.48.04+dfsg-5) ...\n",
+ "Processing triggers for man-db (2.8.3-2ubuntu0.1) ...\n",
+ "Processing triggers for libc-bin (2.27-3ubuntu1.5) ...\n",
+ "Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
+ "Requirement already satisfied: flask in /usr/local/lib/python3.7/dist-packages (1.1.4)\n",
+ "Requirement already satisfied: click<8.0,>=5.1 in /usr/local/lib/python3.7/dist-packages (from flask) (7.1.2)\n",
+ "Requirement already satisfied: Jinja2<3.0,>=2.10.1 in /usr/local/lib/python3.7/dist-packages (from flask) (2.11.3)\n",
+ "Requirement already satisfied: itsdangerous<2.0,>=0.24 in /usr/local/lib/python3.7/dist-packages (from flask) (1.1.0)\n",
+ "Requirement already satisfied: Werkzeug<2.0,>=0.15 in /usr/local/lib/python3.7/dist-packages (from flask) (1.0.1)\n",
+ "Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from Jinja2<3.0,>=2.10.1->flask) (2.0.1)\n",
+ "Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
+ "Collecting python-socketio\n",
+ " Downloading python_socketio-5.7.1-py3-none-any.whl (56 kB)\n",
+ "\u001b[K |████████████████████████████████| 56 kB 5.0 MB/s \n",
+ "\u001b[?25hCollecting bidict>=0.21.0\n",
+ " Downloading bidict-0.22.0-py3-none-any.whl (36 kB)\n",
+ "Collecting python-engineio>=4.3.0\n",
+ " Downloading python_engineio-4.3.4-py3-none-any.whl (52 kB)\n",
+ "\u001b[K |████████████████████████████████| 52 kB 2.0 MB/s \n",
+ "\u001b[?25hInstalling collected packages: python-engineio, bidict, python-socketio\n",
+ "Successfully installed bidict-0.22.0 python-engineio-4.3.4 python-socketio-5.7.1\n",
+ "Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
+ "Collecting eventlet\n",
+ " Downloading eventlet-0.33.1-py2.py3-none-any.whl (226 kB)\n",
+ "\u001b[K |████████████████████████████████| 226 kB 33.3 MB/s \n",
+ "\u001b[?25hCollecting dnspython>=1.15.0\n",
+ " Downloading dnspython-2.2.1-py3-none-any.whl (269 kB)\n",
+ "\u001b[K |████████████████████████████████| 269 kB 52.5 MB/s \n",
+ "\u001b[?25hRequirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.7/dist-packages (from eventlet) (1.15.0)\n",
+ "Requirement already satisfied: greenlet>=0.3 in /usr/local/lib/python3.7/dist-packages (from eventlet) (1.1.3)\n",
+ "Installing collected packages: dnspython, eventlet\n",
+ "Successfully installed dnspython-2.2.1 eventlet-0.33.1\n",
+ "Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
+ "Collecting unidecode\n",
+ " Downloading Unidecode-1.3.4-py3-none-any.whl (235 kB)\n",
+ "\u001b[K |████████████████████████████████| 235 kB 28.6 MB/s \n",
+ "\u001b[?25hInstalling collected packages: unidecode\n",
+ "Successfully installed unidecode-1.3.4\n",
+ "Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
+ "Collecting phonemizer\n",
+ " Downloading phonemizer-3.2.1-py3-none-any.whl (90 kB)\n",
+ "\u001b[K |████████████████████████████████| 90 kB 9.5 MB/s \n",
+ "\u001b[?25hCollecting segments\n",
+ " Downloading segments-2.2.1-py2.py3-none-any.whl (15 kB)\n",
+ "Requirement already satisfied: joblib in /usr/local/lib/python3.7/dist-packages (from phonemizer) (1.1.0)\n",
+ "Collecting dlinfo\n",
+ " Downloading dlinfo-1.2.1-py3-none-any.whl (3.6 kB)\n",
+ "Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from phonemizer) (4.1.1)\n",
+ "Requirement already satisfied: attrs>=18.1 in /usr/local/lib/python3.7/dist-packages (from phonemizer) (22.1.0)\n",
+ "Collecting csvw>=1.5.6\n",
+ " Downloading csvw-3.1.1-py2.py3-none-any.whl (56 kB)\n",
+ "\u001b[K |████████████████████████████████| 56 kB 5.7 MB/s \n",
+ "\u001b[?25hRequirement already satisfied: regex in /usr/local/lib/python3.7/dist-packages (from segments->phonemizer) (2022.6.2)\n",
+ "Collecting clldutils>=1.7.3\n",
+ " Downloading clldutils-3.12.0-py2.py3-none-any.whl (197 kB)\n",
+ "\u001b[K |████████████████████████████████| 197 kB 63.8 MB/s \n",
+ "\u001b[?25hRequirement already satisfied: python-dateutil in /usr/local/lib/python3.7/dist-packages (from clldutils>=1.7.3->segments->phonemizer) (2.8.2)\n",
+ "Requirement already satisfied: tabulate>=0.7.7 in /usr/local/lib/python3.7/dist-packages (from clldutils>=1.7.3->segments->phonemizer) (0.8.10)\n",
+ "Collecting colorlog\n",
+ " Downloading colorlog-6.7.0-py2.py3-none-any.whl (11 kB)\n",
+ "Collecting colorama\n",
+ " Downloading colorama-0.4.5-py2.py3-none-any.whl (16 kB)\n",
+ "Requirement already satisfied: jsonschema in /usr/local/lib/python3.7/dist-packages (from csvw>=1.5.6->segments->phonemizer) (4.3.3)\n",
+ "Collecting rdflib\n",
+ " Downloading rdflib-6.2.0-py3-none-any.whl (500 kB)\n",
+ "\u001b[K |████████████████████████████████| 500 kB 53.6 MB/s \n",
+ "\u001b[?25hRequirement already satisfied: babel in /usr/local/lib/python3.7/dist-packages (from csvw>=1.5.6->segments->phonemizer) (2.10.3)\n",
+ "Collecting language-tags\n",
+ " Downloading language_tags-1.1.0-py2.py3-none-any.whl (210 kB)\n",
+ "\u001b[K |████████████████████████████████| 210 kB 65.4 MB/s \n",
+ "\u001b[?25hCollecting rfc3986<2\n",
+ " Downloading rfc3986-1.5.0-py2.py3-none-any.whl (31 kB)\n",
+ "Requirement already satisfied: uritemplate>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from csvw>=1.5.6->segments->phonemizer) (3.0.1)\n",
+ "Collecting isodate\n",
+ " Downloading isodate-0.6.1-py2.py3-none-any.whl (41 kB)\n",
+ "\u001b[K |████████████████████████████████| 41 kB 763 kB/s \n",
+ "\u001b[?25hRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from csvw>=1.5.6->segments->phonemizer) (2.23.0)\n",
+ "Requirement already satisfied: pytz>=2015.7 in /usr/local/lib/python3.7/dist-packages (from babel->csvw>=1.5.6->segments->phonemizer) (2022.2.1)\n",
+ "Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from isodate->csvw>=1.5.6->segments->phonemizer) (1.15.0)\n",
+ "Requirement already satisfied: pyrsistent!=0.17.0,!=0.17.1,!=0.17.2,>=0.14.0 in /usr/local/lib/python3.7/dist-packages (from jsonschema->csvw>=1.5.6->segments->phonemizer) (0.18.1)\n",
+ "Requirement already satisfied: importlib-resources>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from jsonschema->csvw>=1.5.6->segments->phonemizer) (5.9.0)\n",
+ "Requirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from jsonschema->csvw>=1.5.6->segments->phonemizer) (4.12.0)\n",
+ "Requirement already satisfied: zipp>=3.1.0 in /usr/local/lib/python3.7/dist-packages (from importlib-resources>=1.4.0->jsonschema->csvw>=1.5.6->segments->phonemizer) (3.8.1)\n",
+ "Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from rdflib->csvw>=1.5.6->segments->phonemizer) (57.4.0)\n",
+ "Requirement already satisfied: pyparsing in /usr/local/lib/python3.7/dist-packages (from rdflib->csvw>=1.5.6->segments->phonemizer) (3.0.9)\n",
+ "Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->csvw>=1.5.6->segments->phonemizer) (3.0.4)\n",
+ "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->csvw>=1.5.6->segments->phonemizer) (2022.6.15)\n",
+ "Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->csvw>=1.5.6->segments->phonemizer) (2.10)\n",
+ "Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->csvw>=1.5.6->segments->phonemizer) (1.24.3)\n",
+ "Installing collected packages: isodate, rfc3986, rdflib, language-tags, colorama, csvw, colorlog, clldutils, segments, dlinfo, phonemizer\n",
+ "Successfully installed clldutils-3.12.0 colorama-0.4.5 colorlog-6.7.0 csvw-3.1.1 dlinfo-1.2.1 isodate-0.6.1 language-tags-1.1.0 phonemizer-3.2.1 rdflib-6.2.0 rfc3986-1.5.0 segments-2.2.1\n",
+ "Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
+ "Collecting retry\n",
+ " Downloading retry-0.9.2-py2.py3-none-any.whl (8.0 kB)\n",
+ "Requirement already satisfied: decorator>=3.4.2 in /usr/local/lib/python3.7/dist-packages (from retry) (4.4.2)\n",
+ "Requirement already satisfied: py<2.0.0,>=1.4.26 in /usr/local/lib/python3.7/dist-packages (from retry) (1.11.0)\n",
+ "Installing collected packages: retry\n",
+ "Successfully installed retry-0.9.2\n",
+ "Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
+ "Requirement already satisfied: flask in /usr/local/lib/python3.7/dist-packages (1.1.4)\n",
+ "Requirement already satisfied: itsdangerous<2.0,>=0.24 in /usr/local/lib/python3.7/dist-packages (from flask) (1.1.0)\n",
+ "Requirement already satisfied: Jinja2<3.0,>=2.10.1 in /usr/local/lib/python3.7/dist-packages (from flask) (2.11.3)\n",
+ "Requirement already satisfied: Werkzeug<2.0,>=0.15 in /usr/local/lib/python3.7/dist-packages (from flask) (1.0.1)\n",
+ "Requirement already satisfied: click<8.0,>=5.1 in /usr/local/lib/python3.7/dist-packages (from flask) (7.1.2)\n",
+ "Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from Jinja2<3.0,>=2.10.1->flask) (2.0.1)\n",
+ "Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
+ "Collecting flask_cors\n",
+ " Downloading Flask_Cors-3.0.10-py2.py3-none-any.whl (14 kB)\n",
+ "Requirement already satisfied: Flask>=0.9 in /usr/local/lib/python3.7/dist-packages (from flask_cors) (1.1.4)\n",
+ "Requirement already satisfied: Six in /usr/local/lib/python3.7/dist-packages (from flask_cors) (1.15.0)\n",
+ "Requirement already satisfied: itsdangerous<2.0,>=0.24 in /usr/local/lib/python3.7/dist-packages (from Flask>=0.9->flask_cors) (1.1.0)\n",
+ "Requirement already satisfied: Jinja2<3.0,>=2.10.1 in /usr/local/lib/python3.7/dist-packages (from Flask>=0.9->flask_cors) (2.11.3)\n",
+ "Requirement already satisfied: Werkzeug<2.0,>=0.15 in /usr/local/lib/python3.7/dist-packages (from Flask>=0.9->flask_cors) (1.0.1)\n",
+ "Requirement already satisfied: click<8.0,>=5.1 in /usr/local/lib/python3.7/dist-packages (from Flask>=0.9->flask_cors) (7.1.2)\n",
+ "Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from Jinja2<3.0,>=2.10.1->Flask>=0.9->flask_cors) (2.0.1)\n",
+ "Installing collected packages: flask-cors\n",
+ "Successfully installed flask-cors-3.0.10\n"
+ ]
+ }
+ ]
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "get_ipython().system_raw(f'python3 serverFlask.py 8082 {CONFIG} {MODEL} >foo 2>&1 &')"
+ ],
+ "metadata": {
+ "id": "iNOAB7zISI6J"
+ },
+ "execution_count": 14,
+ "outputs": []
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "!cat foo"
+ ],
+ "metadata": {
+ "colab": {
+ "base_uri": "https://localhost:8080/"
+ },
+ "id": "chu06KpAjEK6",
+ "outputId": "887c2d50-c49f-4a22-f0d0-8a3667511466"
+ },
+ "execution_count": 18,
+ "outputs": [
+ {
+ "output_type": "stream",
+ "name": "stdout",
+ "text": [
+ "[2022-08-31 06:17:58,669] INFO in serverFlask: INITIALIZE MODEL\n",
+ "[2022-08-31 06:18:08,764] INFO in utils: Loaded checkpoint '/content/drive/MyDrive/VoiceChanger/G_326000.pth' (iteration 1136)\n"
+ ]
+ }
+ ]
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "from google.colab import output\n",
+ "\n",
+ "output.serve_kernel_port_as_window(8082)"
+ ],
+ "metadata": {
+ "id": "nkRjZm95l87C",
+ "colab": {
+ "base_uri": "https://localhost:8080/",
+ "height": 34
+ },
+ "outputId": "abf57f92-5cb6-4325-b64a-095d42f561d5"
+ },
+ "execution_count": 27,
+ "outputs": [
+ {
+ "output_type": "display_data",
+ "data": {
+ "text/plain": [
+ ""
+ ],
+ "application/javascript": [
+ "(async (port, path, text, element) => {\n",
+ " if (!google.colab.kernel.accessAllowed) {\n",
+ " return;\n",
+ " }\n",
+ " element.appendChild(document.createTextNode(''));\n",
+ " const url = await google.colab.kernel.proxyPort(port);\n",
+ " const anchor = document.createElement('a');\n",
+ " anchor.href = new URL(path, url).toString();\n",
+ " anchor.target = '_blank';\n",
+ " anchor.setAttribute('data-href', url + path);\n",
+ " anchor.textContent = text;\n",
+ " element.appendChild(anchor);\n",
+ " })(8082, \"/\", \"https://localhost:8082/\", window.element)"
+ ]
+ },
+ "metadata": {}
+ }
+ ]
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "! ls ../frontend/dist/index.html"
+ ],
+ "metadata": {
+ "id": "DKWni4moSyzO",
+ "colab": {
+ "base_uri": "https://localhost:8080/"
+ },
+ "outputId": "b5635a1e-6ac6-41db-a706-dc3e5fb866a5"
+ },
+ "execution_count": 23,
+ "outputs": [
+ {
+ "output_type": "stream",
+ "name": "stdout",
+ "text": [
+ "../frontend/dist/index.html\n"
+ ]
+ }
+ ]
+ },
+ {
+ "cell_type": "code",
+ "source": [],
+ "metadata": {
+ "id": "3hwJmseXZhJY"
+ },
+ "execution_count": null,
+ "outputs": []
+ }
+ ]
+}
\ No newline at end of file
diff --git a/demo/dummy.wav b/demo/dummy.wav
new file mode 100755
index 00000000..f213db64
Binary files /dev/null and b/demo/dummy.wav differ
diff --git a/demo/logs/.gitignore b/demo/logs/.gitignore
new file mode 100755
index 00000000..d6b7ef32
--- /dev/null
+++ b/demo/logs/.gitignore
@@ -0,0 +1,2 @@
+*
+!.gitignore
diff --git a/demo/mod/attentions.py b/demo/mod/attentions.py
new file mode 100755
index 00000000..4e0b0c1f
--- /dev/null
+++ b/demo/mod/attentions.py
@@ -0,0 +1,303 @@
+import copy
+import math
+import numpy as np
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+import commons
+import modules
+from modules import LayerNorm
+
+
+class Encoder(nn.Module):
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., window_size=4, **kwargs):
+ super().__init__()
+ self.hidden_channels = hidden_channels
+ self.filter_channels = filter_channels
+ self.n_heads = n_heads
+ self.n_layers = n_layers
+ self.kernel_size = kernel_size
+ self.p_dropout = p_dropout
+ self.window_size = window_size
+
+ self.drop = nn.Dropout(p_dropout)
+ self.attn_layers = nn.ModuleList()
+ self.norm_layers_1 = nn.ModuleList()
+ self.ffn_layers = nn.ModuleList()
+ self.norm_layers_2 = nn.ModuleList()
+ for i in range(self.n_layers):
+ self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, window_size=window_size))
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
+ self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout))
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
+
+ def forward(self, x, x_mask):
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
+ x = x * x_mask
+ for i in range(self.n_layers):
+ y = self.attn_layers[i](x, x, attn_mask)
+ y = self.drop(y)
+ x = self.norm_layers_1[i](x + y)
+
+ y = self.ffn_layers[i](x, x_mask)
+ y = self.drop(y)
+ x = self.norm_layers_2[i](x + y)
+ x = x * x_mask
+ return x
+
+
+class Decoder(nn.Module):
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., proximal_bias=False, proximal_init=True, **kwargs):
+ super().__init__()
+ self.hidden_channels = hidden_channels
+ self.filter_channels = filter_channels
+ self.n_heads = n_heads
+ self.n_layers = n_layers
+ self.kernel_size = kernel_size
+ self.p_dropout = p_dropout
+ self.proximal_bias = proximal_bias
+ self.proximal_init = proximal_init
+
+ self.drop = nn.Dropout(p_dropout)
+ self.self_attn_layers = nn.ModuleList()
+ self.norm_layers_0 = nn.ModuleList()
+ self.encdec_attn_layers = nn.ModuleList()
+ self.norm_layers_1 = nn.ModuleList()
+ self.ffn_layers = nn.ModuleList()
+ self.norm_layers_2 = nn.ModuleList()
+ for i in range(self.n_layers):
+ self.self_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias, proximal_init=proximal_init))
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
+ self.encdec_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout))
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
+ self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True))
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
+
+ def forward(self, x, x_mask, h, h_mask):
+ """
+ x: decoder input
+ h: encoder output
+ """
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
+ encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
+ x = x * x_mask
+ for i in range(self.n_layers):
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
+ y = self.drop(y)
+ x = self.norm_layers_0[i](x + y)
+
+ y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
+ y = self.drop(y)
+ x = self.norm_layers_1[i](x + y)
+
+ y = self.ffn_layers[i](x, x_mask)
+ y = self.drop(y)
+ x = self.norm_layers_2[i](x + y)
+ x = x * x_mask
+ return x
+
+
+class MultiHeadAttention(nn.Module):
+ def __init__(self, channels, out_channels, n_heads, p_dropout=0., window_size=None, heads_share=True, block_length=None, proximal_bias=False, proximal_init=False):
+ super().__init__()
+ assert channels % n_heads == 0
+
+ self.channels = channels
+ self.out_channels = out_channels
+ self.n_heads = n_heads
+ self.p_dropout = p_dropout
+ self.window_size = window_size
+ self.heads_share = heads_share
+ self.block_length = block_length
+ self.proximal_bias = proximal_bias
+ self.proximal_init = proximal_init
+ self.attn = None
+
+ self.k_channels = channels // n_heads
+ self.conv_q = nn.Conv1d(channels, channels, 1)
+ self.conv_k = nn.Conv1d(channels, channels, 1)
+ self.conv_v = nn.Conv1d(channels, channels, 1)
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
+ self.drop = nn.Dropout(p_dropout)
+
+ if window_size is not None:
+ n_heads_rel = 1 if heads_share else n_heads
+ rel_stddev = self.k_channels**-0.5
+ self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
+ self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
+
+ nn.init.xavier_uniform_(self.conv_q.weight)
+ nn.init.xavier_uniform_(self.conv_k.weight)
+ nn.init.xavier_uniform_(self.conv_v.weight)
+ if proximal_init:
+ with torch.no_grad():
+ self.conv_k.weight.copy_(self.conv_q.weight)
+ self.conv_k.bias.copy_(self.conv_q.bias)
+
+ def forward(self, x, c, attn_mask=None):
+ q = self.conv_q(x)
+ k = self.conv_k(c)
+ v = self.conv_v(c)
+
+ x, self.attn = self.attention(q, k, v, mask=attn_mask)
+
+ x = self.conv_o(x)
+ return x
+
+ def attention(self, query, key, value, mask=None):
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
+ b, d, t_s, t_t = (*key.size(), query.size(2))
+ query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
+ value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
+
+ scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
+ if self.window_size is not None:
+ assert t_s == t_t, "Relative attention is only available for self-attention."
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
+ rel_logits = self._matmul_with_relative_keys(query /math.sqrt(self.k_channels), key_relative_embeddings)
+ scores_local = self._relative_position_to_absolute_position(rel_logits)
+ scores = scores + scores_local
+ if self.proximal_bias:
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
+ scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
+ if mask is not None:
+ scores = scores.masked_fill(mask == 0, -1e4)
+ if self.block_length is not None:
+ assert t_s == t_t, "Local attention is only available for self-attention."
+ block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length)
+ scores = scores.masked_fill(block_mask == 0, -1e4)
+ p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
+ p_attn = self.drop(p_attn)
+ output = torch.matmul(p_attn, value)
+ if self.window_size is not None:
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
+ value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
+ output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)
+ output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t]
+ return output, p_attn
+
+ def _matmul_with_relative_values(self, x, y):
+ """
+ x: [b, h, l, m]
+ y: [h or 1, m, d]
+ ret: [b, h, l, d]
+ """
+ ret = torch.matmul(x, y.unsqueeze(0))
+ return ret
+
+ def _matmul_with_relative_keys(self, x, y):
+ """
+ x: [b, h, l, d]
+ y: [h or 1, m, d]
+ ret: [b, h, l, m]
+ """
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
+ return ret
+
+ def _get_relative_embeddings(self, relative_embeddings, length):
+ max_relative_position = 2 * self.window_size + 1
+ # Pad first before slice to avoid using cond ops.
+ pad_length = max(length - (self.window_size + 1), 0)
+ slice_start_position = max((self.window_size + 1) - length, 0)
+ slice_end_position = slice_start_position + 2 * length - 1
+ if pad_length > 0:
+ padded_relative_embeddings = F.pad(
+ relative_embeddings,
+ commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]))
+ else:
+ padded_relative_embeddings = relative_embeddings
+ used_relative_embeddings = padded_relative_embeddings[:,slice_start_position:slice_end_position]
+ return used_relative_embeddings
+
+ def _relative_position_to_absolute_position(self, x):
+ """
+ x: [b, h, l, 2*l-1]
+ ret: [b, h, l, l]
+ """
+ batch, heads, length, _ = x.size()
+ # Concat columns of pad to shift from relative to absolute indexing.
+ x = F.pad(x, commons.convert_pad_shape([[0,0],[0,0],[0,0],[0,1]]))
+
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
+ x_flat = x.view([batch, heads, length * 2 * length])
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0,0],[0,0],[0,length-1]]))
+
+ # Reshape and slice out the padded elements.
+ x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:]
+ return x_final
+
+ def _absolute_position_to_relative_position(self, x):
+ """
+ x: [b, h, l, l]
+ ret: [b, h, l, 2*l-1]
+ """
+ batch, heads, length, _ = x.size()
+ # padd along column
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length-1]]))
+ x_flat = x.view([batch, heads, length**2 + length*(length -1)])
+ # add 0's in the beginning that will skew the elements after reshape
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
+ x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:]
+ return x_final
+
+ def _attention_bias_proximal(self, length):
+ """Bias for self-attention to encourage attention to close positions.
+ Args:
+ length: an integer scalar.
+ Returns:
+ a Tensor with shape [1, 1, length, length]
+ """
+ r = torch.arange(length, dtype=torch.float32)
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
+
+
+class FFN(nn.Module):
+ def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None, causal=False):
+ super().__init__()
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.filter_channels = filter_channels
+ self.kernel_size = kernel_size
+ self.p_dropout = p_dropout
+ self.activation = activation
+ self.causal = causal
+
+ if causal:
+ self.padding = self._causal_padding
+ else:
+ self.padding = self._same_padding
+
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
+ self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
+ self.drop = nn.Dropout(p_dropout)
+
+ def forward(self, x, x_mask):
+ x = self.conv_1(self.padding(x * x_mask))
+ if self.activation == "gelu":
+ x = x * torch.sigmoid(1.702 * x)
+ else:
+ x = torch.relu(x)
+ x = self.drop(x)
+ x = self.conv_2(self.padding(x * x_mask))
+ return x * x_mask
+
+ def _causal_padding(self, x):
+ if self.kernel_size == 1:
+ return x
+ pad_l = self.kernel_size - 1
+ pad_r = 0
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
+ x = F.pad(x, commons.convert_pad_shape(padding))
+ return x
+
+ def _same_padding(self, x):
+ if self.kernel_size == 1:
+ return x
+ pad_l = (self.kernel_size - 1) // 2
+ pad_r = self.kernel_size // 2
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
+ x = F.pad(x, commons.convert_pad_shape(padding))
+ return x
diff --git a/demo/mod/commons.py b/demo/mod/commons.py
new file mode 100755
index 00000000..9ad0444b
--- /dev/null
+++ b/demo/mod/commons.py
@@ -0,0 +1,161 @@
+import math
+import numpy as np
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+
+def init_weights(m, mean=0.0, std=0.01):
+ classname = m.__class__.__name__
+ if classname.find("Conv") != -1:
+ m.weight.data.normal_(mean, std)
+
+
+def get_padding(kernel_size, dilation=1):
+ return int((kernel_size*dilation - dilation)/2)
+
+
+def convert_pad_shape(pad_shape):
+ l = pad_shape[::-1]
+ pad_shape = [item for sublist in l for item in sublist]
+ return pad_shape
+
+
+def intersperse(lst, item):
+ result = [item] * (len(lst) * 2 + 1)
+ result[1::2] = lst
+ return result
+
+
+def kl_divergence(m_p, logs_p, m_q, logs_q):
+ """KL(P||Q)"""
+ kl = (logs_q - logs_p) - 0.5
+ kl += 0.5 * (torch.exp(2. * logs_p) + ((m_p - m_q)**2)) * torch.exp(-2. * logs_q)
+ return kl
+
+
+def rand_gumbel(shape):
+ """Sample from the Gumbel distribution, protect from overflows."""
+ uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
+ return -torch.log(-torch.log(uniform_samples))
+
+
+def rand_gumbel_like(x):
+ g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
+ return g
+
+
+def slice_segments(x, ids_str, segment_size=4):
+ ret = torch.zeros_like(x[:, :, :segment_size])
+ for i in range(x.size(0)):
+ idx_str = ids_str[i]
+ idx_end = idx_str + segment_size
+ ret[i] = x[i, :, idx_str:idx_end]
+ return ret
+
+
+def rand_slice_segments(x, x_lengths=None, segment_size=4):
+ b, d, t = x.size()
+ if x_lengths is None:
+ x_lengths = t
+ ids_str_max = x_lengths - segment_size + 1
+ ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
+ ret = slice_segments(x, ids_str, segment_size)
+ return ret, ids_str
+
+
+def get_timing_signal_1d(
+ length, channels, min_timescale=1.0, max_timescale=1.0e4):
+ position = torch.arange(length, dtype=torch.float)
+ num_timescales = channels // 2
+ log_timescale_increment = (
+ math.log(float(max_timescale) / float(min_timescale)) /
+ (num_timescales - 1))
+ inv_timescales = min_timescale * torch.exp(
+ torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment)
+ scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
+ signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
+ signal = F.pad(signal, [0, 0, 0, channels % 2])
+ signal = signal.view(1, channels, length)
+ return signal
+
+
+def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
+ b, channels, length = x.size()
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
+ return x + signal.to(dtype=x.dtype, device=x.device)
+
+
+def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
+ b, channels, length = x.size()
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
+ return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
+
+
+def subsequent_mask(length):
+ mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
+ return mask
+
+
+@torch.jit.script
+def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
+ n_channels_int = n_channels[0]
+ in_act = input_a + input_b
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
+ acts = t_act * s_act
+ return acts
+
+
+def convert_pad_shape(pad_shape):
+ l = pad_shape[::-1]
+ pad_shape = [item for sublist in l for item in sublist]
+ return pad_shape
+
+
+def shift_1d(x):
+ x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
+ return x
+
+
+def sequence_mask(length, max_length=None):
+ if max_length is None:
+ max_length = length.max()
+ x = torch.arange(max_length, dtype=length.dtype, device=length.device)
+ return x.unsqueeze(0) < length.unsqueeze(1)
+
+
+def generate_path(duration, mask):
+ """
+ duration: [b, 1, t_x]
+ mask: [b, 1, t_y, t_x]
+ """
+ device = duration.device
+
+ b, _, t_y, t_x = mask.shape
+ cum_duration = torch.cumsum(duration, -1)
+
+ cum_duration_flat = cum_duration.view(b * t_x)
+ path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
+ path = path.view(b, t_x, t_y)
+ path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
+ path = path.unsqueeze(1).transpose(2,3) * mask
+ return path
+
+
+def clip_grad_value_(parameters, clip_value, norm_type=2):
+ if isinstance(parameters, torch.Tensor):
+ parameters = [parameters]
+ parameters = list(filter(lambda p: p.grad is not None, parameters))
+ norm_type = float(norm_type)
+ if clip_value is not None:
+ clip_value = float(clip_value)
+
+ total_norm = 0
+ for p in parameters:
+ param_norm = p.grad.data.norm(norm_type)
+ total_norm += param_norm.item() ** norm_type
+ if clip_value is not None:
+ p.grad.data.clamp_(min=-clip_value, max=clip_value)
+ total_norm = total_norm ** (1. / norm_type)
+ return total_norm
diff --git a/demo/mod/data_utils.py b/demo/mod/data_utils.py
new file mode 100755
index 00000000..3e06620f
--- /dev/null
+++ b/demo/mod/data_utils.py
@@ -0,0 +1,492 @@
+import time
+import os
+import random
+import numpy as np
+import torch
+import torch.utils.data
+import tqdm
+
+import commons
+from mel_processing import spectrogram_torch
+from utils import load_wav_to_torch, load_filepaths_and_text
+from text import text_to_sequence, cleaned_text_to_sequence
+import struct
+#add
+from retry import retry
+import random
+import torchaudio
+from scipy.io.wavfile import write
+
+class TextAudioLoader(torch.utils.data.Dataset):
+ """
+ 1) loads audio, text pairs
+ 2) normalizes text and converts them to sequences of integers
+ 3) computes spectrograms from audio files.
+ """
+ def __init__(self, audiopaths_and_text, hparams, use_test = True):
+ self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text)
+ self.text_cleaners = hparams.text_cleaners
+ self.max_wav_value = hparams.max_wav_value
+ self.sampling_rate = hparams.sampling_rate
+ self.filter_length = hparams.filter_length
+ self.hop_length = hparams.hop_length
+ self.win_length = hparams.win_length
+ self.sampling_rate = hparams.sampling_rate
+ self.use_test = use_test
+
+ self.cleaned_text = getattr(hparams, "cleaned_text", False)
+
+ self.add_blank = hparams.add_blank
+ self.min_text_len = getattr(hparams, "min_text_len", 1)
+ self.max_text_len = getattr(hparams, "max_text_len", 190)
+
+ random.seed(1234)
+ random.shuffle(self.audiopaths_and_text)
+ self._filter()
+
+
+ def _filter(self):
+ """
+ Filter text & store spec lengths
+ """
+ # Store spectrogram lengths for Bucketing
+ # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
+ # spec_length = wav_length // hop_length
+
+ audiopaths_and_text_new = []
+ lengths = []
+ for audiopath, text in self.audiopaths_and_text:
+ if self.min_text_len <= len(text) and len(text) <= self.max_text_len:
+ audiopaths_and_text_new.append([audiopath, text])
+ lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length))
+ self.audiopaths_and_text = audiopaths_and_text_new
+ self.lengths = lengths
+
+ def get_audio_text_pair(self, audiopath_and_text):
+ # separate filename and text
+ audiopath, text = audiopath_and_text[0], audiopath_and_text[1]
+ text = self.get_text(text)
+ if self.use_test != True:
+ text = torch.as_tensor("a")
+ spec, wav = self.get_audio(audiopath)
+ return (text, spec, wav)
+
+ def get_audio(self, filename):
+ audio, sampling_rate = load_wav_to_torch(filename)
+ if sampling_rate != self.sampling_rate:
+ raise ValueError("{} {} SR doesn't match target {} SR".format(
+ sampling_rate, self.sampling_rate))
+ audio_norm = audio / self.max_wav_value
+ audio_norm = audio_norm.unsqueeze(0)
+ spec_filename = filename.replace(".wav", ".spec.pt")
+ if os.path.exists(spec_filename):
+ spec = torch.load(spec_filename)
+ else:
+ spec = spectrogram_torch(audio_norm, self.filter_length,
+ self.sampling_rate, self.hop_length, self.win_length,
+ center=False)
+ spec = torch.squeeze(spec, 0)
+ torch.save(spec, spec_filename)
+ return spec, audio_norm
+
+ def get_text(self, text):
+ if self.cleaned_text:
+ text_norm = cleaned_text_to_sequence(text)
+ else:
+ text_norm = text_to_sequence(text, self.text_cleaners)
+ if self.add_blank:
+ text_norm = commons.intersperse(text_norm, 0)
+ text_norm = torch.LongTensor(text_norm)
+ return text_norm
+
+ def __getitem__(self, index):
+ return self.get_audio_text_pair(self.audiopaths_and_text[index])
+
+ def __len__(self):
+ return len(self.audiopaths_and_text)
+
+
+class TextAudioCollate():
+ """ Zero-pads model inputs and targets
+ """
+ def __init__(self, return_ids=False):
+ self.return_ids = return_ids
+
+ def __call__(self, batch):
+ """Collate's training batch from normalized text and aduio
+ PARAMS
+ ------
+ batch: [text_normalized, spec_normalized, wav_normalized]
+ """
+ # Right zero-pad all one-hot text sequences to max input length
+ _, ids_sorted_decreasing = torch.sort(
+ torch.LongTensor([x[1].size(1) for x in batch]),
+ dim=0, descending=True)
+
+ max_text_len = max([len(x[0]) for x in batch])
+ max_spec_len = max([x[1].size(1) for x in batch])
+ max_wav_len = max([x[2].size(1) for x in batch])
+
+ text_lengths = torch.LongTensor(len(batch))
+ spec_lengths = torch.LongTensor(len(batch))
+ wav_lengths = torch.LongTensor(len(batch))
+
+ text_padded = torch.LongTensor(len(batch), max_text_len)
+ spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
+ wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
+ text_padded.zero_()
+ spec_padded.zero_()
+ wav_padded.zero_()
+ for i in range(len(ids_sorted_decreasing)):
+ row = batch[ids_sorted_decreasing[i]]
+
+ text = row[0]
+ text_padded[i, :text.size(0)] = text
+ text_lengths[i] = text.size(0)
+
+ spec = row[1]
+ spec_padded[i, :, :spec.size(1)] = spec
+ spec_lengths[i] = spec.size(1)
+
+ wav = row[2]
+ wav_padded[i, :, :wav.size(1)] = wav
+ wav_lengths[i] = wav.size(1)
+
+ if self.return_ids:
+ return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, ids_sorted_decreasing
+ return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths
+
+
+"""Multi speaker version"""
+class TextAudioSpeakerLoader(torch.utils.data.Dataset):
+ """
+ 1) loads audio, speaker_id, text pairs
+ 2) normalizes text and converts them to sequences of integers
+ 3) computes spectrograms from audio files.
+ """
+ def __init__(self, audiopaths_sid_text, hparams, no_text=False, augmentation=False, augmentation_params=None, no_use_textfile = False):
+ if no_use_textfile:
+ self.audiopaths_sid_text = list()
+ else:
+ self.audiopaths_sid_text = load_filepaths_and_text(audiopaths_sid_text)
+
+ self.text_cleaners = hparams.text_cleaners
+ self.max_wav_value = hparams.max_wav_value
+ self.sampling_rate = hparams.sampling_rate
+ self.filter_length = hparams.filter_length
+ self.hop_length = hparams.hop_length
+ self.win_length = hparams.win_length
+ self.sampling_rate = hparams.sampling_rate
+ self.no_text = no_text
+ self.augmentation = augmentation
+ if augmentation :
+ self.gain_p = augmentation_params.gain_p
+ self.min_gain_in_db = augmentation_params.min_gain_in_db
+ self.max_gain_in_db = augmentation_params.max_gain_in_db
+ self.time_stretch_p = augmentation_params.time_stretch_p
+ self.min_rate = augmentation_params.min_rate
+ self.max_rate = augmentation_params.max_rate
+ self.pitch_shift_p = augmentation_params.pitch_shift_p
+ self.min_semitones = augmentation_params.min_semitones
+ self.max_semitones = augmentation_params.max_semitones
+ self.add_gaussian_noise_p = augmentation_params.add_gaussian_noise_p
+ self.min_amplitude = augmentation_params.min_amplitude
+ self.max_amplitude = augmentation_params.max_amplitude
+ self.frequency_mask_p = augmentation_params.frequency_mask_p
+
+ self.cleaned_text = getattr(hparams, "cleaned_text", False)
+
+ self.add_blank = hparams.add_blank
+ self.min_text_len = getattr(hparams, "min_text_len", 1)
+ self.max_text_len = getattr(hparams, "max_text_len", 1000)
+
+ random.seed(1234)
+ random.shuffle(self.audiopaths_sid_text)
+ self._filter()
+
+ @retry(tries=30, delay=10)
+ def _filter(self):
+ """
+ Filter text & store spec lengths
+ """
+ audiopaths_sid_text_new = []
+ lengths = []
+
+ # for audiopath, sid, text in tqdm.tqdm(self.audiopaths_sid_text):
+ for audiopath, sid, text in self.audiopaths_sid_text:
+ if self.min_text_len <= len(text) and len(text) <= self.max_text_len:
+ audiopaths_sid_text_new.append([audiopath, sid, text])
+ lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length))
+ self.audiopaths_sid_text = audiopaths_sid_text_new
+ self.lengths = lengths
+
+ def get_audio_text_speaker_pair(self, audiopath_sid_text):
+ # separate filename, speaker_id and text
+ wavdata, sid, text = audiopath_sid_text[0], audiopath_sid_text[1], audiopath_sid_text[2]
+ text = self.get_text(text)
+ if self.no_text:
+ text = self.get_text("a")
+ spec, wav = self.get_audio(wavdata)
+ sid = self.get_sid(sid)
+ return (text, spec, wav, sid)
+
+ @retry(exceptions=(PermissionError), tries=100, delay=10)
+ def get_audio(self, wavdata):
+ # 音声データは±1.0内に正規化したtorchベクトルでunsqueeze(0)で外側1次元くるんだものを扱う
+ audio = torch.FloatTensor(wavdata.astype(np.float32))
+ sampling_rate=24000
+ try:
+ if sampling_rate != self.sampling_rate:
+ raise ValueError("[Error] Exception: source {} SR doesn't match target {} SR".format(
+ sampling_rate, self.sampling_rate))
+ except ValueError as e:
+ print(e)
+ exit()
+ audio_norm = self.get_normalized_audio(audio, self.max_wav_value)
+
+ if self.augmentation:
+ audio_augmented = self.add_augmentation(audio_norm, sampling_rate)
+ audio_noised = self.add_noise(audio_augmented, sampling_rate)
+ # ノーマライズ後のaugmentationとnoise付加で範囲外になったところを削る
+ audio_augmented = torch.clamp(audio_augmented, -1, 1)
+ audio_noised = torch.clamp(audio_noised, -1, 1)
+ # audio(音声波形)は教師信号となるのでノイズは含まずaugmentationのみしたものを使用
+ audio_norm = audio_augmented
+ # spec(スペクトログラム)は入力信号となるのでaugmentationしてさらにノイズを付加したものを使用
+ spec = spectrogram_torch(audio_noised, self.filter_length,
+ self.sampling_rate, self.hop_length, self.win_length,
+ center=False)
+ spec_noised = self.add_spectrogram_noise(spec)
+ spec = torch.squeeze(spec_noised, 0)
+ else:
+ spec = spectrogram_torch(audio_norm, self.filter_length,
+ self.sampling_rate, self.hop_length, self.win_length,
+ center=False)
+ spec = torch.squeeze(spec, 0)
+ return spec, audio_norm
+
+ def add_augmentation(self, audio, sampling_rate):
+ gain_in_db = 0.0
+ if random.random() <= self.gain_p:
+ gain_in_db = random.uniform(self.min_gain_in_db, self.max_gain_in_db)
+ time_stretch_rate = 1.0
+ if random.random() <= self.time_stretch_p:
+ time_stretch_rate = random.uniform(self.min_rate, self.max_rate)
+ pitch_shift_semitones = 0
+ if random.random() <= self.pitch_shift_p:
+ pitch_shift_semitones = random.uniform(self.min_semitones, self.max_semitones) * 100 # 1/100 semitone 単位指定のため
+ augmentation_effects = [
+ ["gain", f"{gain_in_db}"],
+ ["tempo", f"{time_stretch_rate}"],
+ ["pitch", f"{pitch_shift_semitones}"],
+ ["rate", f"{sampling_rate}"]
+ ]
+ audio_augmented, _ = torchaudio.sox_effects.apply_effects_tensor(audio, sampling_rate, augmentation_effects)
+ return audio_augmented
+
+ def add_noise(self, audio, sampling_rate):
+ # AddGaussianNoise
+ audio = self.add_gaussian_noise(audio)
+ return audio
+
+ def add_gaussian_noise(self, audio):
+ assert self.min_amplitude >= 0.0
+ assert self.max_amplitude >= 0.0
+ assert self.max_amplitude >= self.min_amplitude
+ if random.random() > self.add_gaussian_noise_p:
+ return audio
+ amplitude = random.uniform(self.min_amplitude, self.max_amplitude)
+ noise = torch.randn(audio.size())
+ noised_audio = audio + amplitude * noise
+ return noised_audio
+
+ def add_spectrogram_noise(self, spec):
+ # FrequencyMask
+ masking = torchaudio.transforms.FrequencyMasking(freq_mask_param=80)
+ masked = masking(spec)
+ return masked
+
+ def get_normalized_audio(self, audio, max_wav_value):
+ audio_norm = audio / max_wav_value
+ audio_norm = audio_norm.unsqueeze(0)
+ return audio_norm
+
+ def get_text(self, text):
+ if self.cleaned_text:
+ text_norm = cleaned_text_to_sequence(text)
+ else:
+ text_norm = text_to_sequence(text, self.text_cleaners)
+ if self.add_blank:
+ text_norm = commons.intersperse(text_norm, 0)
+ text_norm = torch.LongTensor(text_norm)
+ return text_norm
+
+ def get_sid(self, sid):
+ sid = torch.LongTensor([int(sid)])
+ return sid
+
+ def __getitem__(self, index):
+ return self.get_audio_text_speaker_pair(self.audiopaths_sid_text[index])
+
+ def __len__(self):
+ return len(self.audiopaths_sid_text)
+
+
+class TextAudioSpeakerCollate():
+ """ Zero-pads model inputs and targets
+ """
+ def __init__(self, return_ids=False, no_text = False):
+ self.return_ids = return_ids
+ self.no_text = no_text
+
+ def __call__(self, batch):
+ """Collate's training batch from normalized text, audio and speaker identities
+ PARAMS
+ ------
+ batch: [text_normalized, spec_normalized, wav_normalized, sid]
+ """
+ # Right zero-pad all one-hot text sequences to max input length
+
+ _, ids_sorted_decreasing = torch.sort(
+ torch.LongTensor([x[1].size(1) for x in batch]),
+ dim=0, descending=True)
+
+ max_text_len = max([len(x[0]) for x in batch])
+ max_spec_len = max([x[1].size(1) for x in batch])
+ max_wav_len = max([x[2].size(1) for x in batch])
+
+ text_lengths = torch.LongTensor(len(batch))
+ spec_lengths = torch.LongTensor(len(batch))
+ wav_lengths = torch.LongTensor(len(batch))
+ sid = torch.LongTensor(len(batch))
+
+ text_padded = torch.LongTensor(len(batch), max_text_len)
+ spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
+ wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
+ text_padded.zero_()
+ spec_padded.zero_()
+ wav_padded.zero_()
+ for i in range(len(ids_sorted_decreasing)):
+ row = batch[ids_sorted_decreasing[i]]
+
+ text = row[0]
+ text_padded[i, :text.size(0)] = text
+ text_lengths[i] = text.size(0)
+
+ spec = row[1]
+ spec_padded[i, :, :spec.size(1)] = spec
+ spec_lengths[i] = spec.size(1)
+
+ wav = row[2]
+ wav_padded[i, :, :wav.size(1)] = wav
+ wav_lengths[i] = wav.size(1)
+
+ sid[i] = row[3]
+
+ if self.return_ids:
+ return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, sid, ids_sorted_decreasing
+ return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, sid
+
+
+class DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler):
+ """
+ Maintain similar input lengths in a batch.
+ Length groups are specified by boundaries.
+ Ex) boundaries = [b1, b2, b3] -> any batch is included either {x | b1 < length(x) <=b2} or {x | b2 < length(x) <= b3}.
+
+ It removes samples which are not included in the boundaries.
+ Ex) boundaries = [b1, b2, b3] -> any x s.t. length(x) <= b1 or length(x) > b3 are discarded.
+ """
+ def __init__(self, dataset, batch_size, boundaries, num_replicas=None, rank=None, shuffle=True):
+ super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle)
+ self.lengths = dataset.lengths
+ self.batch_size = batch_size
+ self.boundaries = boundaries
+
+ self.buckets, self.num_samples_per_bucket = self._create_buckets()
+ self.total_size = sum(self.num_samples_per_bucket)
+ self.num_samples = self.total_size // self.num_replicas
+
+ def _create_buckets(self):
+ buckets = [[] for _ in range(len(self.boundaries) - 1)]
+ for i in range(len(self.lengths)):
+ length = self.lengths[i]
+ idx_bucket = self._bisect(length)
+ if idx_bucket != -1:
+ buckets[idx_bucket].append(i)
+
+ for i in range(len(buckets) - 1, 0, -1):
+ if len(buckets[i]) == 0:
+ buckets.pop(i)
+ self.boundaries.pop(i+1)
+
+ num_samples_per_bucket = []
+ for i in range(len(buckets)):
+ len_bucket = len(buckets[i])
+ total_batch_size = self.num_replicas * self.batch_size
+ rem = (total_batch_size - (len_bucket % total_batch_size)) % total_batch_size
+ num_samples_per_bucket.append(len_bucket + rem)
+ return buckets, num_samples_per_bucket
+
+ def __iter__(self):
+ # deterministically shuffle based on epoch
+ g = torch.Generator()
+ g.manual_seed(self.epoch)
+
+ indices = []
+ if self.shuffle:
+ for bucket in self.buckets:
+ indices.append(torch.randperm(len(bucket), generator=g).tolist())
+ else:
+ for bucket in self.buckets:
+ indices.append(list(range(len(bucket))))
+
+ batches = []
+ for i in range(len(self.buckets)):
+ next_bucket = (i+1) % len(self.buckets)
+ bucket = self.buckets[i]
+ len_bucket = len(bucket)
+ ids_bucket = indices[i]
+ num_samples_bucket = self.num_samples_per_bucket[i]
+
+ if len_bucket == 0:
+ print("[Warn] Exception: length of buckets {} is 0. ID:{} Skip.".format(i,i))
+ continue
+
+ # add extra samples to make it evenly divisible
+ rem = num_samples_bucket - len_bucket
+ ids_bucket = ids_bucket + ids_bucket * (rem // len_bucket) + ids_bucket[:(rem % len_bucket)]
+
+ # subsample
+ ids_bucket = ids_bucket[self.rank::self.num_replicas]
+
+ # batching
+ for j in range(len(ids_bucket) // self.batch_size):
+ batch = [bucket[idx] for idx in ids_bucket[j*self.batch_size:(j+1)*self.batch_size]]
+ batches.append(batch)
+
+ if self.shuffle:
+ batch_ids = torch.randperm(len(batches), generator=g).tolist()
+ batches = [batches[i] for i in batch_ids]
+ self.batches = batches
+
+ assert len(self.batches) * self.batch_size == self.num_samples
+ return iter(self.batches)
+
+ def _bisect(self, x, lo=0, hi=None):
+ if hi is None:
+ hi = len(self.boundaries) - 1
+
+ if hi > lo:
+ mid = (hi + lo) // 2
+ if self.boundaries[mid] < x and x <= self.boundaries[mid+1]:
+ return mid
+ elif x <= self.boundaries[mid]:
+ return self._bisect(x, lo, mid)
+ else:
+ return self._bisect(x, mid + 1, hi)
+ else:
+ return -1
+
+ def __len__(self):
+ return self.num_samples // self.batch_size
diff --git a/demo/mod/mel_processing.py b/demo/mod/mel_processing.py
new file mode 100755
index 00000000..cb33b76d
--- /dev/null
+++ b/demo/mod/mel_processing.py
@@ -0,0 +1,114 @@
+import math
+import os
+import random
+import torch
+from torch import nn
+import torch.nn.functional as F
+import torch.utils.data
+import numpy as np
+import librosa
+import librosa.util as librosa_util
+from librosa.util import normalize, pad_center, tiny
+from scipy.signal import get_window
+from scipy.io.wavfile import read
+from librosa.filters import mel as librosa_mel_fn
+
+MAX_WAV_VALUE = 32768.0
+
+
+def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
+ """
+ PARAMS
+ ------
+ C: compression factor
+ """
+ return torch.log(torch.clamp(x, min=clip_val) * C)
+
+
+def dynamic_range_decompression_torch(x, C=1):
+ """
+ PARAMS
+ ------
+ C: compression factor used to compress
+ """
+ return torch.exp(x) / C
+
+
+def spectral_normalize_torch(magnitudes):
+ output = dynamic_range_compression_torch(magnitudes)
+ return output
+
+
+def spectral_de_normalize_torch(magnitudes):
+ output = dynamic_range_decompression_torch(magnitudes)
+ return output
+
+
+mel_basis = {}
+hann_window = {}
+
+
+def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
+ if torch.min(y) < -1.:
+ print('min value is ', torch.min(y))
+ if torch.max(y) > 1.:
+ print('max value is ', torch.max(y))
+
+ global hann_window
+ dtype_device = str(y.dtype) + '_' + str(y.device)
+ wnsize_dtype_device = str(win_size) + '_' + dtype_device
+ if wnsize_dtype_device not in hann_window:
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
+
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
+ y = y.squeeze(1)
+
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
+ center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=True)
+ spec = torch.view_as_real(spec)
+
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
+ return spec
+
+
+def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
+ global mel_basis
+ dtype_device = str(spec.dtype) + '_' + str(spec.device)
+ fmax_dtype_device = str(fmax) + '_' + dtype_device
+ if fmax_dtype_device not in mel_basis:
+ mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=spec.dtype, device=spec.device)
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
+ spec = spectral_normalize_torch(spec)
+ return spec
+
+
+def mel_spectrogram_torch(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
+ if torch.min(y) < -1.:
+ print('min value is ', torch.min(y))
+ if torch.max(y) > 1.:
+ print('max value is ', torch.max(y))
+
+ global mel_basis, hann_window
+ dtype_device = str(y.dtype) + '_' + str(y.device)
+ fmax_dtype_device = str(fmax) + '_' + dtype_device
+ wnsize_dtype_device = str(win_size) + '_' + dtype_device
+ if fmax_dtype_device not in mel_basis:
+ mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=y.dtype, device=y.device)
+ if wnsize_dtype_device not in hann_window:
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
+
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
+ y = y.squeeze(1)
+
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
+ center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=True)
+ spec = torch.view_as_real(spec)
+
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
+
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
+ spec = spectral_normalize_torch(spec)
+
+ return spec
diff --git a/demo/mod/models.py b/demo/mod/models.py
new file mode 100755
index 00000000..7b40b95f
--- /dev/null
+++ b/demo/mod/models.py
@@ -0,0 +1,407 @@
+import copy
+import math
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+import commons
+import modules
+import attentions
+import monotonic_align
+
+from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
+from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
+from commons import init_weights, get_padding
+
+
+class TextEncoder(nn.Module):
+ def __init__(self,
+ n_vocab,
+ out_channels,
+ hidden_channels,
+ filter_channels,
+ n_heads,
+ n_layers,
+ kernel_size,
+ p_dropout):
+ super().__init__()
+ self.n_vocab = n_vocab
+ self.out_channels = out_channels
+ self.hidden_channels = hidden_channels
+ self.filter_channels = filter_channels
+ self.n_heads = n_heads
+ self.n_layers = n_layers
+ self.kernel_size = kernel_size
+ self.p_dropout = p_dropout
+
+ self.emb = nn.Embedding(n_vocab, hidden_channels)
+ nn.init.normal_(self.emb.weight, 0.0, hidden_channels**-0.5)
+
+ self.encoder = attentions.Encoder(
+ hidden_channels,
+ filter_channels,
+ n_heads,
+ n_layers,
+ kernel_size,
+ p_dropout)
+ self.proj= nn.Conv1d(hidden_channels, out_channels * 2, 1)
+
+ def forward(self, x, x_lengths):
+ x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h]
+ x = torch.transpose(x, 1, -1) # [b, h, t]
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
+
+ x = self.encoder(x * x_mask, x_mask)
+ stats = self.proj(x) * x_mask
+
+ m, logs = torch.split(stats, self.out_channels, dim=1)
+ return x, m, logs, x_mask
+
+
+class ResidualCouplingBlock(nn.Module):
+ def __init__(self,
+ channels,
+ hidden_channels,
+ kernel_size,
+ dilation_rate,
+ n_layers,
+ n_flows=4,
+ gin_channels=0):
+ super().__init__()
+ self.channels = channels
+ self.hidden_channels = hidden_channels
+ self.kernel_size = kernel_size
+ self.dilation_rate = dilation_rate
+ self.n_layers = n_layers
+ self.n_flows = n_flows
+ self.gin_channels = gin_channels
+
+ self.flows = nn.ModuleList()
+ for i in range(n_flows):
+ self.flows.append(modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels, mean_only=True))
+ self.flows.append(modules.Flip())
+
+ def forward(self, x, x_mask, g=None, reverse=False):
+ if not reverse:
+ for flow in self.flows:
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
+ else:
+ for flow in reversed(self.flows):
+ x = flow(x, x_mask, g=g, reverse=reverse)
+ return x
+
+
+class PosteriorEncoder(nn.Module):
+ def __init__(self,
+ in_channels,
+ out_channels,
+ hidden_channels,
+ kernel_size,
+ dilation_rate,
+ n_layers,
+ gin_channels=0):
+ super().__init__()
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.hidden_channels = hidden_channels
+ self.kernel_size = kernel_size
+ self.dilation_rate = dilation_rate
+ self.n_layers = n_layers
+ self.gin_channels = gin_channels
+
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
+ self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
+
+ def forward(self, x, x_lengths, g=None):
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
+ x = self.pre(x) * x_mask
+ x = self.enc(x, x_mask, g=g)
+ stats = self.proj(x) * x_mask
+ m, logs = torch.split(stats, self.out_channels, dim=1)
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
+ return z, m, logs, x_mask
+
+
+class Generator(torch.nn.Module):
+ def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=0):
+ super(Generator, self).__init__()
+ self.num_kernels = len(resblock_kernel_sizes)
+ self.num_upsamples = len(upsample_rates)
+ self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3)
+ resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2
+
+ self.ups = nn.ModuleList()
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
+ self.ups.append(weight_norm(
+ ConvTranspose1d(upsample_initial_channel//(2**i), upsample_initial_channel//(2**(i+1)),
+ k, u, padding=(k-u)//2)))
+
+ self.resblocks = nn.ModuleList()
+ for i in range(len(self.ups)):
+ ch = upsample_initial_channel//(2**(i+1))
+ for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
+ self.resblocks.append(resblock(ch, k, d))
+
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
+ self.ups.apply(init_weights)
+
+ if gin_channels != 0:
+ #self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
+ gin_channels = 0
+
+ def forward(self, x, g=None):
+ x = self.conv_pre(x)
+ if g is not None:
+ #x = x + self.cond(g)
+ g=None
+
+ for i in range(self.num_upsamples):
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
+ x = self.ups[i](x)
+ xs = None
+ for j in range(self.num_kernels):
+ if xs is None:
+ xs = self.resblocks[i*self.num_kernels+j](x)
+ else:
+ xs += self.resblocks[i*self.num_kernels+j](x)
+ x = xs / self.num_kernels
+ x = F.leaky_relu(x)
+ x = self.conv_post(x)
+ x = torch.tanh(x)
+
+ return x
+
+ def remove_weight_norm(self):
+ print('Removing weight norm...')
+ for l in self.ups:
+ remove_weight_norm(l)
+ for l in self.resblocks:
+ l.remove_weight_norm()
+
+
+class DiscriminatorP(torch.nn.Module):
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
+ super(DiscriminatorP, self).__init__()
+ self.period = period
+ self.use_spectral_norm = use_spectral_norm
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
+ self.convs = nn.ModuleList([
+ norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
+ norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
+ norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
+ norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
+ norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))),
+ ])
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
+
+ def forward(self, x):
+ fmap = []
+
+ # 1d to 2d
+ b, c, t = x.shape
+ if t % self.period != 0: # pad first
+ n_pad = self.period - (t % self.period)
+ x = F.pad(x, (0, n_pad), "reflect")
+ t = t + n_pad
+ x = x.view(b, c, t // self.period, self.period)
+
+ for l in self.convs:
+ x = l(x)
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
+ fmap.append(x)
+ x = self.conv_post(x)
+ fmap.append(x)
+ x = torch.flatten(x, 1, -1)
+
+ return x, fmap
+
+
+class DiscriminatorS(torch.nn.Module):
+ def __init__(self, use_spectral_norm=False):
+ super(DiscriminatorS, self).__init__()
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
+ self.convs = nn.ModuleList([
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
+ ])
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
+
+ def forward(self, x):
+ fmap = []
+
+ for l in self.convs:
+ x = l(x)
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
+ fmap.append(x)
+ x = self.conv_post(x)
+ fmap.append(x)
+ x = torch.flatten(x, 1, -1)
+
+ return x, fmap
+
+
+class MultiPeriodDiscriminator(torch.nn.Module):
+ def __init__(self, use_spectral_norm=False):
+ super(MultiPeriodDiscriminator, self).__init__()
+ periods = [2,3,5,7,11]
+
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
+ discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods]
+ self.discriminators = nn.ModuleList(discs)
+
+ def forward(self, y, y_hat):
+ y_d_rs = []
+ y_d_gs = []
+ fmap_rs = []
+ fmap_gs = []
+ for i, d in enumerate(self.discriminators):
+ y_d_r, fmap_r = d(y)
+ y_d_g, fmap_g = d(y_hat)
+ y_d_rs.append(y_d_r)
+ y_d_gs.append(y_d_g)
+ fmap_rs.append(fmap_r)
+ fmap_gs.append(fmap_g)
+
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
+
+
+
+class SynthesizerTrn(nn.Module):
+ """
+ Synthesizer for Training
+ """
+
+ def __init__(self,
+ n_vocab,
+ spec_channels,
+ segment_size,
+ inter_channels,
+ hidden_channels,
+ filter_channels,
+ n_heads,
+ n_layers,
+ kernel_size,
+ p_dropout,
+ resblock,
+ resblock_kernel_sizes,
+ resblock_dilation_sizes,
+ upsample_rates,
+ upsample_initial_channel,
+ upsample_kernel_sizes,
+ n_flow,
+ n_speakers=0,
+ gin_channels=0,
+ use_sdp=True,
+ **kwargs):
+
+ super().__init__()
+ self.n_vocab = n_vocab
+ self.spec_channels = spec_channels
+ self.hidden_channels = hidden_channels
+ self.filter_channels = filter_channels
+ self.n_heads = n_heads
+ self.n_layers = n_layers
+ self.kernel_size = kernel_size
+ self.p_dropout = p_dropout
+ self.resblock = resblock
+ self.resblock_kernel_sizes = resblock_kernel_sizes
+ self.resblock_dilation_sizes = resblock_dilation_sizes
+ self.upsample_rates = upsample_rates
+ self.upsample_initial_channel = upsample_initial_channel
+ self.upsample_kernel_sizes = upsample_kernel_sizes
+ self.segment_size = segment_size
+ self.n_speakers = n_speakers
+ self.gin_channels = gin_channels
+
+ self.use_sdp = use_sdp
+
+ self.enc_p = TextEncoder(n_vocab,
+ inter_channels,
+ hidden_channels,
+ filter_channels,
+ n_heads,
+ n_layers,
+ kernel_size,
+ p_dropout)
+ self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels)
+ self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
+ self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, n_flows=n_flow, gin_channels=gin_channels)
+
+ if n_speakers > 1:
+ self.emb_g = nn.Embedding(n_speakers, gin_channels)
+
+ def forward(self, x, x_lengths, y, y_lengths, sid=None):
+
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
+ if self.n_speakers > 0:
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
+ else:
+ g = None
+
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
+ z_p = self.flow(z, y_mask, g=g)
+
+ with torch.no_grad():
+ # negative cross-entropy
+ s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t]
+ neg_cent1 = torch.sum(-0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True) # [b, 1, t_s]
+ neg_cent2 = torch.matmul(-0.5 * (z_p ** 2).transpose(1, 2), s_p_sq_r) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
+ neg_cent3 = torch.matmul(z_p.transpose(1, 2), (m_p * s_p_sq_r)) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
+ neg_cent4 = torch.sum(-0.5 * (m_p ** 2) * s_p_sq_r, [1], keepdim=True) # [b, 1, t_s]
+ neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
+
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
+ attn = monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1)).unsqueeze(1).detach()
+
+ # expand prior
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2)
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2)
+
+ z_slice, ids_slice = commons.rand_slice_segments(z, y_lengths, self.segment_size)
+ o = self.dec(z_slice, g=g)
+ return o, attn, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
+
+ def voice_conversion(self, y, y_lengths, sid_src, sid_tgt):
+ assert self.n_speakers > 0, "n_speakers have to be larger than 0."
+ g_src = self.emb_g(sid_src).unsqueeze(-1)
+ g_tgt = self.emb_g(sid_tgt).unsqueeze(-1)
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g_src)
+ z_p = self.flow(z, y_mask, g=g_src)
+ z_hat = self.flow(z_p, y_mask, g=g_tgt, reverse=True)
+ o_hat = self.dec(z_hat * y_mask, g=g_tgt)
+ return o_hat, y_mask, (z, z_p, z_hat)
+
+ def voice_ra_pa_db(self, y, y_lengths, sid_src, sid_tgt):
+ assert self.n_speakers > 0, "n_speakers have to be larger than 0."
+ g_src = self.emb_g(sid_src).unsqueeze(-1)
+ g_tgt = self.emb_g(sid_tgt).unsqueeze(-1)
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g_src)
+ o_hat = self.dec(z * y_mask, g=g_tgt)
+ return o_hat, y_mask, (z)
+
+ def voice_ra_pa_da(self, y, y_lengths, sid_src, sid_tgt):
+ assert self.n_speakers > 0, "n_speakers have to be larger than 0."
+ g_src = self.emb_g(sid_src).unsqueeze(-1)
+ g_tgt = self.emb_g(sid_tgt).unsqueeze(-1)
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g_src)
+ o_hat = self.dec(z * y_mask, g=g_src)
+ return o_hat, y_mask, (z)
+
+ def voice_conversion_cycle(self, y, y_lengths, sid_src, sid_tgt):
+ assert self.n_speakers > 0, "n_speakers have to be larger than 0."
+ g_src = self.emb_g(sid_src).unsqueeze(-1)
+ g_tgt = self.emb_g(sid_tgt).unsqueeze(-1)
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g_src)
+ z_p = self.flow(z, y_mask, g=g_src)
+ z_hat = self.flow(z_p, y_mask, g=g_tgt, reverse=True)
+ z_p_hat = self.flow(z_hat, y_mask, g=g_tgt)
+ z_hat_hat = self.flow(z_p_hat, y_mask, g=g_src, reverse=True)
+ o_hat = self.dec(z_hat_hat * y_mask, g=g_tgt)
+ return o_hat, y_mask, (z, z_p, z_hat)
+
+
diff --git a/demo/mod/modules.py b/demo/mod/modules.py
new file mode 100755
index 00000000..9c7fd9cd
--- /dev/null
+++ b/demo/mod/modules.py
@@ -0,0 +1,390 @@
+import copy
+import math
+import numpy as np
+import scipy
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
+from torch.nn.utils import weight_norm, remove_weight_norm
+
+import commons
+from commons import init_weights, get_padding
+from transforms import piecewise_rational_quadratic_transform
+
+
+LRELU_SLOPE = 0.1
+
+
+class LayerNorm(nn.Module):
+ def __init__(self, channels, eps=1e-5):
+ super().__init__()
+ self.channels = channels
+ self.eps = eps
+
+ self.gamma = nn.Parameter(torch.ones(channels))
+ self.beta = nn.Parameter(torch.zeros(channels))
+
+ def forward(self, x):
+ x = x.transpose(1, -1)
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
+ return x.transpose(1, -1)
+
+
+class ConvReluNorm(nn.Module):
+ def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
+ super().__init__()
+ self.in_channels = in_channels
+ self.hidden_channels = hidden_channels
+ self.out_channels = out_channels
+ self.kernel_size = kernel_size
+ self.n_layers = n_layers
+ self.p_dropout = p_dropout
+ assert n_layers > 1, "Number of layers should be larger than 0."
+
+ self.conv_layers = nn.ModuleList()
+ self.norm_layers = nn.ModuleList()
+ self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2))
+ self.norm_layers.append(LayerNorm(hidden_channels))
+ self.relu_drop = nn.Sequential(
+ nn.ReLU(),
+ nn.Dropout(p_dropout))
+ for _ in range(n_layers-1):
+ self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2))
+ self.norm_layers.append(LayerNorm(hidden_channels))
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
+ self.proj.weight.data.zero_()
+ self.proj.bias.data.zero_()
+
+ def forward(self, x, x_mask):
+ x_org = x
+ for i in range(self.n_layers):
+ x = self.conv_layers[i](x * x_mask)
+ x = self.norm_layers[i](x)
+ x = self.relu_drop(x)
+ x = x_org + self.proj(x)
+ return x * x_mask
+
+
+class DDSConv(nn.Module):
+ """
+ Dialted and Depth-Separable Convolution
+ """
+ def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
+ super().__init__()
+ self.channels = channels
+ self.kernel_size = kernel_size
+ self.n_layers = n_layers
+ self.p_dropout = p_dropout
+
+ self.drop = nn.Dropout(p_dropout)
+ self.convs_sep = nn.ModuleList()
+ self.convs_1x1 = nn.ModuleList()
+ self.norms_1 = nn.ModuleList()
+ self.norms_2 = nn.ModuleList()
+ for i in range(n_layers):
+ dilation = kernel_size ** i
+ padding = (kernel_size * dilation - dilation) // 2
+ self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size,
+ groups=channels, dilation=dilation, padding=padding
+ ))
+ self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
+ self.norms_1.append(LayerNorm(channels))
+ self.norms_2.append(LayerNorm(channels))
+
+ def forward(self, x, x_mask, g=None):
+ if g is not None:
+ x = x + g
+ for i in range(self.n_layers):
+ y = self.convs_sep[i](x * x_mask)
+ y = self.norms_1[i](y)
+ y = F.gelu(y)
+ y = self.convs_1x1[i](y)
+ y = self.norms_2[i](y)
+ y = F.gelu(y)
+ y = self.drop(y)
+ x = x + y
+ return x * x_mask
+
+
+class WN(torch.nn.Module):
+ def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
+ super(WN, self).__init__()
+ assert(kernel_size % 2 == 1)
+ self.hidden_channels =hidden_channels
+ self.kernel_size = kernel_size,
+ self.dilation_rate = dilation_rate
+ self.n_layers = n_layers
+ self.gin_channels = gin_channels
+ self.p_dropout = p_dropout
+
+ self.in_layers = torch.nn.ModuleList()
+ self.res_skip_layers = torch.nn.ModuleList()
+ self.drop = nn.Dropout(p_dropout)
+
+ if gin_channels != 0:
+ cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)
+ self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
+
+ for i in range(n_layers):
+ dilation = dilation_rate ** i
+ padding = int((kernel_size * dilation - dilation) / 2)
+ in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size,
+ dilation=dilation, padding=padding)
+ in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
+ self.in_layers.append(in_layer)
+
+ # last one is not necessary
+ if i < n_layers - 1:
+ res_skip_channels = 2 * hidden_channels
+ else:
+ res_skip_channels = hidden_channels
+
+ res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
+ res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
+ self.res_skip_layers.append(res_skip_layer)
+
+ def forward(self, x, x_mask, g=None, **kwargs):
+ output = torch.zeros_like(x)
+ n_channels_tensor = torch.IntTensor([self.hidden_channels])
+
+ if g is not None:
+ g = self.cond_layer(g)
+
+ for i in range(self.n_layers):
+ x_in = self.in_layers[i](x)
+ if g is not None:
+ cond_offset = i * 2 * self.hidden_channels
+ g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]
+ else:
+ g_l = torch.zeros_like(x_in)
+
+ acts = commons.fused_add_tanh_sigmoid_multiply(
+ x_in,
+ g_l,
+ n_channels_tensor)
+ acts = self.drop(acts)
+
+ res_skip_acts = self.res_skip_layers[i](acts)
+ if i < self.n_layers - 1:
+ res_acts = res_skip_acts[:,:self.hidden_channels,:]
+ x = (x + res_acts) * x_mask
+ output = output + res_skip_acts[:,self.hidden_channels:,:]
+ else:
+ output = output + res_skip_acts
+ return output * x_mask
+
+ def remove_weight_norm(self):
+ if self.gin_channels != 0:
+ torch.nn.utils.remove_weight_norm(self.cond_layer)
+ for l in self.in_layers:
+ torch.nn.utils.remove_weight_norm(l)
+ for l in self.res_skip_layers:
+ torch.nn.utils.remove_weight_norm(l)
+
+
+class ResBlock1(torch.nn.Module):
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
+ super(ResBlock1, self).__init__()
+ self.convs1 = nn.ModuleList([
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
+ padding=get_padding(kernel_size, dilation[0]))),
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
+ padding=get_padding(kernel_size, dilation[1]))),
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
+ padding=get_padding(kernel_size, dilation[2])))
+ ])
+ self.convs1.apply(init_weights)
+
+ self.convs2 = nn.ModuleList([
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
+ padding=get_padding(kernel_size, 1))),
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
+ padding=get_padding(kernel_size, 1))),
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
+ padding=get_padding(kernel_size, 1)))
+ ])
+ self.convs2.apply(init_weights)
+
+ def forward(self, x, x_mask=None):
+ for c1, c2 in zip(self.convs1, self.convs2):
+ xt = F.leaky_relu(x, LRELU_SLOPE)
+ if x_mask is not None:
+ xt = xt * x_mask
+ xt = c1(xt)
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
+ if x_mask is not None:
+ xt = xt * x_mask
+ xt = c2(xt)
+ x = xt + x
+ if x_mask is not None:
+ x = x * x_mask
+ return x
+
+ def remove_weight_norm(self):
+ for l in self.convs1:
+ remove_weight_norm(l)
+ for l in self.convs2:
+ remove_weight_norm(l)
+
+
+class ResBlock2(torch.nn.Module):
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
+ super(ResBlock2, self).__init__()
+ self.convs = nn.ModuleList([
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
+ padding=get_padding(kernel_size, dilation[0]))),
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
+ padding=get_padding(kernel_size, dilation[1])))
+ ])
+ self.convs.apply(init_weights)
+
+ def forward(self, x, x_mask=None):
+ for c in self.convs:
+ xt = F.leaky_relu(x, LRELU_SLOPE)
+ if x_mask is not None:
+ xt = xt * x_mask
+ xt = c(xt)
+ x = xt + x
+ if x_mask is not None:
+ x = x * x_mask
+ return x
+
+ def remove_weight_norm(self):
+ for l in self.convs:
+ remove_weight_norm(l)
+
+
+class Log(nn.Module):
+ def forward(self, x, x_mask, reverse=False, **kwargs):
+ if not reverse:
+ y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
+ logdet = torch.sum(-y, [1, 2])
+ return y, logdet
+ else:
+ x = torch.exp(x) * x_mask
+ return x
+
+
+class Flip(nn.Module):
+ def forward(self, x, *args, reverse=False, **kwargs):
+ x = torch.flip(x, [1])
+ if not reverse:
+ logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
+ return x, logdet
+ else:
+ return x
+
+
+class ElementwiseAffine(nn.Module):
+ def __init__(self, channels):
+ super().__init__()
+ self.channels = channels
+ self.m = nn.Parameter(torch.zeros(channels,1))
+ self.logs = nn.Parameter(torch.zeros(channels,1))
+
+ def forward(self, x, x_mask, reverse=False, **kwargs):
+ if not reverse:
+ y = self.m + torch.exp(self.logs) * x
+ y = y * x_mask
+ logdet = torch.sum(self.logs * x_mask, [1,2])
+ return y, logdet
+ else:
+ x = (x - self.m) * torch.exp(-self.logs) * x_mask
+ return x
+
+
+class ResidualCouplingLayer(nn.Module):
+ def __init__(self,
+ channels,
+ hidden_channels,
+ kernel_size,
+ dilation_rate,
+ n_layers,
+ p_dropout=0,
+ gin_channels=0,
+ mean_only=False):
+ assert channels % 2 == 0, "channels should be divisible by 2"
+ super().__init__()
+ self.channels = channels
+ self.hidden_channels = hidden_channels
+ self.kernel_size = kernel_size
+ self.dilation_rate = dilation_rate
+ self.n_layers = n_layers
+ self.half_channels = channels // 2
+ self.mean_only = mean_only
+
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
+ self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels)
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
+ self.post.weight.data.zero_()
+ self.post.bias.data.zero_()
+
+ def forward(self, x, x_mask, g=None, reverse=False):
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
+ h = self.pre(x0) * x_mask
+ h = self.enc(h, x_mask, g=g)
+ stats = self.post(h) * x_mask
+ if not self.mean_only:
+ m, logs = torch.split(stats, [self.half_channels]*2, 1)
+ else:
+ m = stats
+ logs = torch.zeros_like(m)
+
+ if not reverse:
+ x1 = m + x1 * torch.exp(logs) * x_mask
+ x = torch.cat([x0, x1], 1)
+ logdet = torch.sum(logs, [1,2])
+ return x, logdet
+ else:
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
+ x = torch.cat([x0, x1], 1)
+ return x
+
+
+class ConvFlow(nn.Module):
+ def __init__(self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0):
+ super().__init__()
+ self.in_channels = in_channels
+ self.filter_channels = filter_channels
+ self.kernel_size = kernel_size
+ self.n_layers = n_layers
+ self.num_bins = num_bins
+ self.tail_bound = tail_bound
+ self.half_channels = in_channels // 2
+
+ self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
+ self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.)
+ self.proj = nn.Conv1d(filter_channels, self.half_channels * (num_bins * 3 - 1), 1)
+ self.proj.weight.data.zero_()
+ self.proj.bias.data.zero_()
+
+ def forward(self, x, x_mask, g=None, reverse=False):
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
+ h = self.pre(x0)
+ h = self.convs(h, x_mask, g=g)
+ h = self.proj(h) * x_mask
+
+ b, c, t = x0.shape
+ h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
+
+ unnormalized_widths = h[..., :self.num_bins] / math.sqrt(self.filter_channels)
+ unnormalized_heights = h[..., self.num_bins:2*self.num_bins] / math.sqrt(self.filter_channels)
+ unnormalized_derivatives = h[..., 2 * self.num_bins:]
+
+ x1, logabsdet = piecewise_rational_quadratic_transform(x1,
+ unnormalized_widths,
+ unnormalized_heights,
+ unnormalized_derivatives,
+ inverse=reverse,
+ tails='linear',
+ tail_bound=self.tail_bound
+ )
+
+ x = torch.cat([x0, x1], 1) * x_mask
+ logdet = torch.sum(logabsdet * x_mask, [1,2])
+ if not reverse:
+ return x, logdet
+ else:
+ return x
diff --git a/demo/mod/monotonic_align/__init__.py b/demo/mod/monotonic_align/__init__.py
new file mode 100755
index 00000000..3d7009c4
--- /dev/null
+++ b/demo/mod/monotonic_align/__init__.py
@@ -0,0 +1,19 @@
+import numpy as np
+import torch
+from .monotonic_align.core import maximum_path_c
+
+
+def maximum_path(neg_cent, mask):
+ """ Cython optimized version.
+ neg_cent: [b, t_t, t_s]
+ mask: [b, t_t, t_s]
+ """
+ device = neg_cent.device
+ dtype = neg_cent.dtype
+ neg_cent = neg_cent.data.cpu().numpy().astype(np.float32)
+ path = np.zeros(neg_cent.shape, dtype=np.int32)
+
+ t_t_max = mask.sum(1)[:, 0].data.cpu().numpy().astype(np.int32)
+ t_s_max = mask.sum(2)[:, 0].data.cpu().numpy().astype(np.int32)
+ maximum_path_c(path, neg_cent, t_t_max, t_s_max)
+ return torch.from_numpy(path).to(device=device, dtype=dtype)
diff --git a/demo/mod/monotonic_align/core.pyx b/demo/mod/monotonic_align/core.pyx
new file mode 100755
index 00000000..bfaabd4d
--- /dev/null
+++ b/demo/mod/monotonic_align/core.pyx
@@ -0,0 +1,42 @@
+cimport cython
+from cython.parallel import prange
+
+
+@cython.boundscheck(False)
+@cython.wraparound(False)
+cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_y, int t_x, float max_neg_val=-1e9) nogil:
+ cdef int x
+ cdef int y
+ cdef float v_prev
+ cdef float v_cur
+ cdef float tmp
+ cdef int index = t_x - 1
+
+ for y in range(t_y):
+ for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)):
+ if x == y:
+ v_cur = max_neg_val
+ else:
+ v_cur = value[y-1, x]
+ if x == 0:
+ if y == 0:
+ v_prev = 0.
+ else:
+ v_prev = max_neg_val
+ else:
+ v_prev = value[y-1, x-1]
+ value[y, x] += max(v_prev, v_cur)
+
+ for y in range(t_y - 1, -1, -1):
+ path[y, index] = 1
+ if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]):
+ index = index - 1
+
+
+@cython.boundscheck(False)
+@cython.wraparound(False)
+cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_ys, int[::1] t_xs) nogil:
+ cdef int b = paths.shape[0]
+ cdef int i
+ for i in prange(b, nogil=True):
+ maximum_path_each(paths[i], values[i], t_ys[i], t_xs[i])
diff --git a/demo/mod/monotonic_align/monotonic_align/core.cpython-37m-x86_64-linux-gnu.so b/demo/mod/monotonic_align/monotonic_align/core.cpython-37m-x86_64-linux-gnu.so
new file mode 100755
index 00000000..0ea56ee9
Binary files /dev/null and b/demo/mod/monotonic_align/monotonic_align/core.cpython-37m-x86_64-linux-gnu.so differ
diff --git a/demo/mod/monotonic_align/monotonic_align/core.cpython-39-x86_64-linux-gnu.so b/demo/mod/monotonic_align/monotonic_align/core.cpython-39-x86_64-linux-gnu.so
new file mode 100755
index 00000000..d42eff71
Binary files /dev/null and b/demo/mod/monotonic_align/monotonic_align/core.cpython-39-x86_64-linux-gnu.so differ
diff --git a/demo/mod/monotonic_align/setup.py b/demo/mod/monotonic_align/setup.py
new file mode 100755
index 00000000..d68e6672
--- /dev/null
+++ b/demo/mod/monotonic_align/setup.py
@@ -0,0 +1,23 @@
+import numpy as np
+import torch
+import sys
+print(sys.path)
+sys.path.append("/backend/mod/")
+print(sys.path)
+from .monotonic_align.core import maximum_path_c
+
+
+def maximum_path(neg_cent, mask):
+ """ Cython optimized version.
+ neg_cent: [b, t_t, t_s]
+ mask: [b, t_t, t_s]
+ """
+ device = neg_cent.device
+ dtype = neg_cent.dtype
+ neg_cent = neg_cent.data.cpu().numpy().astype(np.float32)
+ path = np.zeros(neg_cent.shape, dtype=np.int32)
+
+ t_t_max = mask.sum(1)[:, 0].data.cpu().numpy().astype(np.int32)
+ t_s_max = mask.sum(2)[:, 0].data.cpu().numpy().astype(np.int32)
+ maximum_path_c(path, neg_cent, t_t_max, t_s_max)
+ return torch.from_numpy(path).to(device=device, dtype=dtype)
diff --git a/demo/mod/text/__init__.py b/demo/mod/text/__init__.py
new file mode 100755
index 00000000..4ac41f90
--- /dev/null
+++ b/demo/mod/text/__init__.py
@@ -0,0 +1,54 @@
+""" from https://github.com/keithito/tacotron """
+from text import cleaners
+from text.symbols import symbols
+
+
+# Mappings from symbol to numeric ID and vice versa:
+_symbol_to_id = {s: i for i, s in enumerate(symbols)}
+_id_to_symbol = {i: s for i, s in enumerate(symbols)}
+
+
+def text_to_sequence(text, cleaner_names):
+ '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
+ Args:
+ text: string to convert to a sequence
+ cleaner_names: names of the cleaner functions to run the text through
+ Returns:
+ List of integers corresponding to the symbols in the text
+ '''
+ sequence = []
+
+ clean_text = _clean_text(text, cleaner_names)
+ for symbol in clean_text:
+ symbol_id = _symbol_to_id[symbol]
+ sequence += [symbol_id]
+ return sequence
+
+
+def cleaned_text_to_sequence(cleaned_text):
+ '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
+ Args:
+ text: string to convert to a sequence
+ Returns:
+ List of integers corresponding to the symbols in the text
+ '''
+ sequence = [_symbol_to_id[symbol] for symbol in cleaned_text]
+ return sequence
+
+
+def sequence_to_text(sequence):
+ '''Converts a sequence of IDs back to a string'''
+ result = ''
+ for symbol_id in sequence:
+ s = _id_to_symbol[symbol_id]
+ result += s
+ return result
+
+
+def _clean_text(text, cleaner_names):
+ for name in cleaner_names:
+ cleaner = getattr(cleaners, name)
+ if not cleaner:
+ raise Exception('Unknown cleaner: %s' % name)
+ text = cleaner(text)
+ return text
diff --git a/demo/mod/text/cleaners.py b/demo/mod/text/cleaners.py
new file mode 100755
index 00000000..32afd52c
--- /dev/null
+++ b/demo/mod/text/cleaners.py
@@ -0,0 +1,105 @@
+""" The following information was added with reference to https://github.com/jaywalnut310/vits/tree/1eef52ed50743f77fca9ff6773ba673497f6bf9d. """
+""" from https://github.com/keithito/tacotron """
+
+'''
+Cleaners are transformations that run over the input text at both training and eval time.
+
+Cleaners can be selected by passing a comma-delimited list of cleaner names as the "cleaners"
+hyperparameter. Some cleaners are English-specific. You'll typically want to use:
+ 1. "english_cleaners" for English text
+ 2. "transliteration_cleaners" for non-English text that can be transliterated to ASCII using
+ the Unidecode library (https://pypi.python.org/pypi/Unidecode)
+ 3. "basic_cleaners" if you do not want to transliterate (in this case, you should also update
+ the symbols in symbols.py to match your data).
+'''
+
+import re
+from unidecode import unidecode
+from phonemizer import phonemize
+
+
+# Regular expression matching whitespace:
+_whitespace_re = re.compile(r'\s+')
+
+# List of (regular expression, replacement) pairs for abbreviations:
+_abbreviations = [(re.compile('\\b%s\\.' % x[0], re.IGNORECASE), x[1]) for x in [
+ ('mrs', 'misess'),
+ ('mr', 'mister'),
+ ('dr', 'doctor'),
+ ('st', 'saint'),
+ ('co', 'company'),
+ ('jr', 'junior'),
+ ('maj', 'major'),
+ ('gen', 'general'),
+ ('drs', 'doctors'),
+ ('rev', 'reverend'),
+ ('lt', 'lieutenant'),
+ ('hon', 'honorable'),
+ ('sgt', 'sergeant'),
+ ('capt', 'captain'),
+ ('esq', 'esquire'),
+ ('ltd', 'limited'),
+ ('col', 'colonel'),
+ ('ft', 'fort'),
+]]
+
+
+def expand_abbreviations(text):
+ for regex, replacement in _abbreviations:
+ text = re.sub(regex, replacement, text)
+ return text
+
+
+def expand_numbers(text):
+ return normalize_numbers(text)
+
+
+def lowercase(text):
+ return text.lower()
+
+
+def collapse_whitespace(text):
+ return re.sub(_whitespace_re, ' ', text)
+
+
+def convert_to_ascii(text):
+ return unidecode(text)
+
+
+def basic_cleaners(text):
+ '''Basic pipeline that lowercases and collapses whitespace without transliteration.'''
+ text = lowercase(text)
+ text = collapse_whitespace(text)
+ return text
+
+
+def transliteration_cleaners(text):
+ '''Pipeline for non-English text that transliterates to ASCII.'''
+ text = convert_to_ascii(text)
+ text = lowercase(text)
+ text = collapse_whitespace(text)
+ return text
+
+
+def english_cleaners(text):
+ '''Pipeline for English text, including abbreviation expansion.'''
+ text = convert_to_ascii(text)
+ text = lowercase(text)
+ text = expand_abbreviations(text)
+ phonemes = phonemize(text, language='en-us', backend='espeak', strip=True)
+ phonemes = collapse_whitespace(phonemes)
+ return phonemes
+
+
+def english_cleaners2(text):
+ '''Pipeline for English text, including abbreviation expansion. + punctuation + stress'''
+ text = convert_to_ascii(text)
+ text = lowercase(text)
+ text = expand_abbreviations(text)
+ phonemes = phonemize(text, language='en-us', backend='espeak', strip=True, preserve_punctuation=True, with_stress=True)
+ phonemes = collapse_whitespace(phonemes)
+ return phonemes
+
+def japanese_cleaners(text):
+ phonemes = text.split('-')
+ return phonemes
\ No newline at end of file
diff --git a/demo/mod/text/symbols.py b/demo/mod/text/symbols.py
new file mode 100755
index 00000000..2a46c1fa
--- /dev/null
+++ b/demo/mod/text/symbols.py
@@ -0,0 +1,64 @@
+""" The following information was added with reference to https://github.com/jaywalnut310/vits/tree/1eef52ed50743f77fca9ff6773ba673497f6bf9d """
+""" from https://github.com/keithito/tacotron """
+
+'''
+Defines the set of symbols used in text input to the model.
+'''
+_pad = '_'
+_punctuation = ';:,.!?¡¿—…"«»“” '
+_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
+_letters_ipa = "ɑɐɒæɓʙβɔɕçɗɖðʤəɘɚɛɜɝɞɟʄɡɠɢʛɦɧħɥʜɨɪʝɭɬɫɮʟɱɯɰŋɳɲɴøɵɸθœɶʘɹɺɾɻʀʁɽʂʃʈʧʉʊʋⱱʌɣɤʍχʎʏʑʐʒʔʡʕʢǀǁǂǃˈˌːˑʼʴʰʱʲʷˠˤ˞↓↑→↗↘'̩'ᵻ"
+
+
+# Export all symbols:
+symbols = [_pad] + list(_punctuation) + list(_letters) + list(_letters_ipa)
+
+# Special symbol ids
+SPACE_ID = symbols.index(" ")
+
+symbols = [
+ "A",
+ "E",
+ "I",
+ "N",
+ "O",
+ "U",
+ "a",
+ "b",
+ "by",
+ "ch",
+ "cl",
+ "d",
+ "dy",
+ "e",
+ "f",
+ "g",
+ "gy",
+ "h",
+ "hy",
+ "i",
+ "j",
+ "k",
+ "ky",
+ "m",
+ "my",
+ "n",
+ "ny",
+ "o",
+ "p",
+ "py",
+ "r",
+ "ry",
+ "s",
+ "sh",
+ "t",
+ "ts",
+ "ty",
+ "u",
+ "v",
+ "w",
+ "y",
+ "z",
+ "pau",
+ "sil"
+]
diff --git a/demo/mod/transforms.py b/demo/mod/transforms.py
new file mode 100755
index 00000000..4793d67c
--- /dev/null
+++ b/demo/mod/transforms.py
@@ -0,0 +1,193 @@
+import torch
+from torch.nn import functional as F
+
+import numpy as np
+
+
+DEFAULT_MIN_BIN_WIDTH = 1e-3
+DEFAULT_MIN_BIN_HEIGHT = 1e-3
+DEFAULT_MIN_DERIVATIVE = 1e-3
+
+
+def piecewise_rational_quadratic_transform(inputs,
+ unnormalized_widths,
+ unnormalized_heights,
+ unnormalized_derivatives,
+ inverse=False,
+ tails=None,
+ tail_bound=1.,
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
+ min_derivative=DEFAULT_MIN_DERIVATIVE):
+
+ if tails is None:
+ spline_fn = rational_quadratic_spline
+ spline_kwargs = {}
+ else:
+ spline_fn = unconstrained_rational_quadratic_spline
+ spline_kwargs = {
+ 'tails': tails,
+ 'tail_bound': tail_bound
+ }
+
+ outputs, logabsdet = spline_fn(
+ inputs=inputs,
+ unnormalized_widths=unnormalized_widths,
+ unnormalized_heights=unnormalized_heights,
+ unnormalized_derivatives=unnormalized_derivatives,
+ inverse=inverse,
+ min_bin_width=min_bin_width,
+ min_bin_height=min_bin_height,
+ min_derivative=min_derivative,
+ **spline_kwargs
+ )
+ return outputs, logabsdet
+
+
+def searchsorted(bin_locations, inputs, eps=1e-6):
+ bin_locations[..., -1] += eps
+ return torch.sum(
+ inputs[..., None] >= bin_locations,
+ dim=-1
+ ) - 1
+
+
+def unconstrained_rational_quadratic_spline(inputs,
+ unnormalized_widths,
+ unnormalized_heights,
+ unnormalized_derivatives,
+ inverse=False,
+ tails='linear',
+ tail_bound=1.,
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
+ min_derivative=DEFAULT_MIN_DERIVATIVE):
+ inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
+ outside_interval_mask = ~inside_interval_mask
+
+ outputs = torch.zeros_like(inputs)
+ logabsdet = torch.zeros_like(inputs)
+
+ if tails == 'linear':
+ unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1))
+ constant = np.log(np.exp(1 - min_derivative) - 1)
+ unnormalized_derivatives[..., 0] = constant
+ unnormalized_derivatives[..., -1] = constant
+
+ outputs[outside_interval_mask] = inputs[outside_interval_mask]
+ logabsdet[outside_interval_mask] = 0
+ else:
+ raise RuntimeError('{} tails are not implemented.'.format(tails))
+
+ outputs[inside_interval_mask], logabsdet[inside_interval_mask] = rational_quadratic_spline(
+ inputs=inputs[inside_interval_mask],
+ unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
+ unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
+ unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :],
+ inverse=inverse,
+ left=-tail_bound, right=tail_bound, bottom=-tail_bound, top=tail_bound,
+ min_bin_width=min_bin_width,
+ min_bin_height=min_bin_height,
+ min_derivative=min_derivative
+ )
+
+ return outputs, logabsdet
+
+def rational_quadratic_spline(inputs,
+ unnormalized_widths,
+ unnormalized_heights,
+ unnormalized_derivatives,
+ inverse=False,
+ left=0., right=1., bottom=0., top=1.,
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
+ min_derivative=DEFAULT_MIN_DERIVATIVE):
+ if torch.min(inputs) < left or torch.max(inputs) > right:
+ raise ValueError('Input to a transform is not within its domain')
+
+ num_bins = unnormalized_widths.shape[-1]
+
+ if min_bin_width * num_bins > 1.0:
+ raise ValueError('Minimal bin width too large for the number of bins')
+ if min_bin_height * num_bins > 1.0:
+ raise ValueError('Minimal bin height too large for the number of bins')
+
+ widths = F.softmax(unnormalized_widths, dim=-1)
+ widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
+ cumwidths = torch.cumsum(widths, dim=-1)
+ cumwidths = F.pad(cumwidths, pad=(1, 0), mode='constant', value=0.0)
+ cumwidths = (right - left) * cumwidths + left
+ cumwidths[..., 0] = left
+ cumwidths[..., -1] = right
+ widths = cumwidths[..., 1:] - cumwidths[..., :-1]
+
+ derivatives = min_derivative + F.softplus(unnormalized_derivatives)
+
+ heights = F.softmax(unnormalized_heights, dim=-1)
+ heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
+ cumheights = torch.cumsum(heights, dim=-1)
+ cumheights = F.pad(cumheights, pad=(1, 0), mode='constant', value=0.0)
+ cumheights = (top - bottom) * cumheights + bottom
+ cumheights[..., 0] = bottom
+ cumheights[..., -1] = top
+ heights = cumheights[..., 1:] - cumheights[..., :-1]
+
+ if inverse:
+ bin_idx = searchsorted(cumheights, inputs)[..., None]
+ else:
+ bin_idx = searchsorted(cumwidths, inputs)[..., None]
+
+ input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
+ input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
+
+ input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
+ delta = heights / widths
+ input_delta = delta.gather(-1, bin_idx)[..., 0]
+
+ input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
+ input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
+
+ input_heights = heights.gather(-1, bin_idx)[..., 0]
+
+ if inverse:
+ a = (((inputs - input_cumheights) * (input_derivatives
+ + input_derivatives_plus_one
+ - 2 * input_delta)
+ + input_heights * (input_delta - input_derivatives)))
+ b = (input_heights * input_derivatives
+ - (inputs - input_cumheights) * (input_derivatives
+ + input_derivatives_plus_one
+ - 2 * input_delta))
+ c = - input_delta * (inputs - input_cumheights)
+
+ discriminant = b.pow(2) - 4 * a * c
+ assert (discriminant >= 0).all()
+
+ root = (2 * c) / (-b - torch.sqrt(discriminant))
+ outputs = root * input_bin_widths + input_cumwidths
+
+ theta_one_minus_theta = root * (1 - root)
+ denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta)
+ * theta_one_minus_theta)
+ derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * root.pow(2)
+ + 2 * input_delta * theta_one_minus_theta
+ + input_derivatives * (1 - root).pow(2))
+ logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
+
+ return outputs, -logabsdet
+ else:
+ theta = (inputs - input_cumwidths) / input_bin_widths
+ theta_one_minus_theta = theta * (1 - theta)
+
+ numerator = input_heights * (input_delta * theta.pow(2)
+ + input_derivatives * theta_one_minus_theta)
+ denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta)
+ * theta_one_minus_theta)
+ outputs = input_cumheights + numerator / denominator
+
+ derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * theta.pow(2)
+ + 2 * input_delta * theta_one_minus_theta
+ + input_derivatives * (1 - theta).pow(2))
+ logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
+
+ return outputs, logabsdet
diff --git a/demo/mod/utils.py b/demo/mod/utils.py
new file mode 100755
index 00000000..fae83f01
--- /dev/null
+++ b/demo/mod/utils.py
@@ -0,0 +1,270 @@
+import os
+import glob
+import sys
+import argparse
+import logging
+import json
+import subprocess
+import numpy as np
+from scipy.io.wavfile import read
+import torch
+
+MATPLOTLIB_FLAG = False
+
+logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
+logger = logging
+
+
+def load_checkpoint(checkpoint_path, model, optimizer=None):
+ assert os.path.isfile(checkpoint_path), f"No such file or directory: {checkpoint_path}"
+ checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
+ iteration = checkpoint_dict['iteration']
+ learning_rate = checkpoint_dict['learning_rate']
+ if optimizer is not None:
+ optimizer.load_state_dict(checkpoint_dict['optimizer'])
+ saved_state_dict = checkpoint_dict['model']
+ if hasattr(model, 'module'):
+ state_dict = model.module.state_dict()
+ else:
+ state_dict = model.state_dict()
+ new_state_dict= {}
+ for k, v in state_dict.items():
+ try:
+ new_state_dict[k] = saved_state_dict[k]
+ except:
+ logger.info("%s is not in the checkpoint" % k)
+ new_state_dict[k] = v
+ if hasattr(model, 'module'):
+ model.module.load_state_dict(new_state_dict)
+ else:
+ model.load_state_dict(new_state_dict)
+ logger.info("Loaded checkpoint '{}' (iteration {})" .format(
+ checkpoint_path, iteration))
+ return model, optimizer, learning_rate, iteration
+
+
+def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path):
+ logger.info("Saving model and optimizer state at iteration {} to {}".format(
+ iteration, checkpoint_path))
+ if hasattr(model, 'module'):
+ state_dict = model.module.state_dict()
+ else:
+ state_dict = model.state_dict()
+ torch.save({'model': state_dict,
+ 'iteration': iteration,
+ 'optimizer': optimizer.state_dict(),
+ 'learning_rate': learning_rate}, checkpoint_path)
+
+
+def summarize(writer, global_step, scalars={}, histograms={}, images={}, audios={}, audio_sampling_rate=22050):
+ for k, v in scalars.items():
+ writer.add_scalar(k, v, global_step)
+ for k, v in histograms.items():
+ writer.add_histogram(k, v, global_step)
+ for k, v in images.items():
+ writer.add_image(k, v, global_step, dataformats='HWC')
+ for k, v in audios.items():
+ writer.add_audio(k, v, global_step, audio_sampling_rate)
+
+
+def latest_checkpoint_path(dir_path, regex="G_*.pth"):
+ f_list = glob.glob(os.path.join(dir_path, regex))
+ f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
+ x = f_list[-1]
+ print(x)
+ return x
+
+
+def plot_spectrogram_to_numpy(spectrogram):
+ global MATPLOTLIB_FLAG
+ if not MATPLOTLIB_FLAG:
+ import matplotlib
+ matplotlib.use("Agg")
+ MATPLOTLIB_FLAG = True
+ mpl_logger = logging.getLogger('matplotlib')
+ mpl_logger.setLevel(logging.WARNING)
+ import matplotlib.pylab as plt
+ import numpy as np
+
+ fig, ax = plt.subplots(figsize=(10,2))
+ im = ax.imshow(spectrogram, aspect="auto", origin="lower",
+ interpolation='none')
+ plt.colorbar(im, ax=ax)
+ plt.xlabel("Frames")
+ plt.ylabel("Channels")
+ plt.tight_layout()
+
+ fig.canvas.draw()
+ data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
+ data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
+ plt.close()
+ return data
+
+
+def plot_alignment_to_numpy(alignment, info=None):
+ global MATPLOTLIB_FLAG
+ if not MATPLOTLIB_FLAG:
+ import matplotlib
+ matplotlib.use("Agg")
+ MATPLOTLIB_FLAG = True
+ mpl_logger = logging.getLogger('matplotlib')
+ mpl_logger.setLevel(logging.WARNING)
+ import matplotlib.pylab as plt
+ import numpy as np
+
+ fig, ax = plt.subplots(figsize=(6, 4))
+ im = ax.imshow(alignment.transpose(), aspect='auto', origin='lower',
+ interpolation='none')
+ fig.colorbar(im, ax=ax)
+ xlabel = 'Decoder timestep'
+ if info is not None:
+ xlabel += '\n\n' + info
+ plt.xlabel(xlabel)
+ plt.ylabel('Encoder timestep')
+ plt.tight_layout()
+
+ fig.canvas.draw()
+ data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
+ data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
+ plt.close()
+ return data
+
+
+def load_wav_to_torch(full_path):
+ sampling_rate, data = read(full_path) # scipy.io.wavfile
+ return torch.FloatTensor(data.astype(np.float32)), sampling_rate
+
+
+def load_filepaths_and_text(filename, split="|"):
+ with open(filename, encoding='utf-8') as f:
+ filepaths_and_text = [line.strip().split(split) for line in f]
+ return filepaths_and_text
+
+
+def get_hparams(init=True):
+ parser = argparse.ArgumentParser()
+ parser.add_argument('-c', '--config', type=str, default="./configs/base.json",
+ help='JSON file for configuration')
+ parser.add_argument('-m', '--model', type=str, required=True,
+ help='Model name')
+ parser.add_argument('-fg', '--fine_tuning_g', type=str, default=None,
+ help='If fine tuning, please specify model(G)')
+ parser.add_argument('-fd', '--fine_tuning_d', type=str, default=None,
+ help='If fine tuning, please specify model(D)')
+
+ args = parser.parse_args()
+ model_dir = os.path.join("./logs", args.model)
+
+ if not os.path.exists(model_dir):
+ os.makedirs(model_dir)
+
+ config_path = args.config
+ config_save_path = os.path.join(model_dir, "config.json")
+ if init:
+ with open(config_path, "r") as f:
+ data = f.read()
+ with open(config_save_path, "w") as f:
+ f.write(data)
+ else:
+ with open(config_save_path, "r") as f:
+ data = f.read()
+ config = json.loads(data)
+
+ #Added about fine tuning
+ if args.fine_tuning_g != None and args.fine_tuning_d != None:
+ config['fine_flag'] = True
+ config['fine_model_g'] = args.fine_tuning_g
+ config['fine_model_d'] = args.fine_tuning_d
+ else:
+ config['fine_flag'] = False
+
+ hparams = HParams(**config)
+ hparams.model_dir = model_dir
+ return hparams
+
+
+def get_hparams_from_dir(model_dir):
+ config_save_path = os.path.join(model_dir, "config.json")
+ with open(config_save_path, "r") as f:
+ data = f.read()
+ config = json.loads(data)
+
+ hparams =HParams(**config)
+ hparams.model_dir = model_dir
+ return hparams
+
+
+def get_hparams_from_file(config_path):
+ with open(config_path, "r") as f:
+ data = f.read()
+ config = json.loads(data)
+
+ hparams =HParams(**config)
+ return hparams
+
+
+def check_git_hash(model_dir):
+ source_dir = os.path.dirname(os.path.realpath(__file__))
+ if not os.path.exists(os.path.join(source_dir, ".git")):
+ logger.warn("{} is not a git repository, therefore hash value comparison will be ignored.".format(
+ source_dir
+ ))
+ return
+
+ cur_hash = subprocess.getoutput("git rev-parse HEAD")
+
+ path = os.path.join(model_dir, "githash")
+ if os.path.exists(path):
+ saved_hash = open(path).read()
+ if saved_hash != cur_hash:
+ logger.warn("git hash values are different. {}(saved) != {}(current)".format(
+ saved_hash[:8], cur_hash[:8]))
+ else:
+ open(path, "w").write(cur_hash)
+
+
+def get_logger(model_dir, filename="train.log"):
+ global logger
+ logger = logging.getLogger(os.path.basename(model_dir))
+ logger.setLevel(logging.DEBUG)
+
+ formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s")
+ if not os.path.exists(model_dir):
+ os.makedirs(model_dir)
+ h = logging.FileHandler(os.path.join(model_dir, filename))
+ h.setLevel(logging.DEBUG)
+ h.setFormatter(formatter)
+ logger.addHandler(h)
+ return logger
+
+
+class HParams():
+ def __init__(self, **kwargs):
+ for k, v in kwargs.items():
+ if type(v) == dict:
+ v = HParams(**v)
+ self[k] = v
+
+ def keys(self):
+ return self.__dict__.keys()
+
+ def items(self):
+ return self.__dict__.items()
+
+ def values(self):
+ return self.__dict__.values()
+
+ def __len__(self):
+ return len(self.__dict__)
+
+ def __getitem__(self, key):
+ return getattr(self, key)
+
+ def __setitem__(self, key, value):
+ return setattr(self, key, value)
+
+ def __contains__(self, key):
+ return key in self.__dict__
+
+ def __repr__(self):
+ return self.__dict__.__repr__()
diff --git a/demo/requirements.txt b/demo/requirements.txt
new file mode 100644
index 00000000..d6f87d68
--- /dev/null
+++ b/demo/requirements.txt
@@ -0,0 +1,85 @@
+absl-py==1.2.0
+appdirs==1.4.4
+attrs==22.1.0
+audioread==3.0.0
+Babel==2.10.3
+bidict==0.22.0
+cachetools==5.2.0
+certifi==2022.6.15
+cffi==1.15.1
+charset-normalizer==2.1.1
+clldutils==3.12.0
+colorama==0.4.5
+colorlog==6.6.0
+csvw==3.1.1
+cycler==0.11.0
+Cython==0.29.32
+decorator==5.1.1
+dlinfo==1.2.1
+dnspython==2.2.1
+eventlet==0.33.1
+fonttools==4.36.0
+google-auth==2.11.0
+google-auth-oauthlib==0.4.6
+greenlet==1.1.2
+grpcio==1.47.0
+idna==3.3
+importlib-metadata==4.12.0
+isodate==0.6.1
+joblib==1.1.0
+jsonschema==4.14.0
+kiwisolver==1.4.4
+language-tags==1.1.0
+librosa==0.9.2
+llvmlite==0.39.0
+Markdown==3.4.1
+MarkupSafe==2.1.1
+matplotlib==3.5.3
+numba==0.56.0
+numpy==1.22.4
+oauthlib==3.2.0
+packaging==21.3
+phonemizer==3.2.1
+Pillow==9.2.0
+pooch==1.6.0
+protobuf==3.19.4
+psutil==5.9.1
+py==1.11.0
+pyasn1==0.4.8
+pyasn1-modules==0.2.8
+pycparser==2.21
+pyopenjtalk==0.2.0
+pyparsing==3.0.9
+pyrsistent==0.18.1
+python-dateutil==2.8.2
+python-engineio==4.3.4
+python-socketio==5.7.1
+pytz==2022.2.1
+rdflib==6.2.0
+regex==2022.8.17
+requests==2.28.1
+requests-oauthlib==1.3.1
+resampy==0.4.0
+retry==0.9.2
+rfc3986==1.5.0
+rsa==4.9
+scikit-learn==1.1.2
+scipy==1.9.0
+segments==2.2.1
+six==1.16.0
+SoundFile==0.10.3.post1
+tabulate==0.8.10
+tensorboard==2.10.0
+tensorboard-data-server==0.6.1
+tensorboard-plugin-wit==1.8.1
+threadpoolctl==3.1.0
+torch==1.12.1+cu113
+torchaudio==0.12.1+cu113
+torchvision==0.13.1+cu113
+tqdm==4.64.0
+typing-extensions==4.3.0
+Unidecode==1.3.4
+uritemplate==4.1.1
+urllib3==1.26.11
+Werkzeug==2.2.2
+zipp==3.8.1
diff --git a/demo/serverFlask.py b/demo/serverFlask.py
new file mode 100755
index 00000000..b722d279
--- /dev/null
+++ b/demo/serverFlask.py
@@ -0,0 +1,136 @@
+from flask import Flask, request, Markup, abort, jsonify
+from flask_cors import CORS
+import logging
+from logging.config import dictConfig
+import sys
+import base64
+
+import torch
+import numpy as np
+from scipy.io.wavfile import write, read
+from datetime import datetime
+
+import traceback
+import struct
+
+sys.path.append("mod")
+sys.path.append("mod/text")
+
+import utils
+from data_utils import TextAudioSpeakerLoader, TextAudioSpeakerCollate
+from models import SynthesizerTrn
+from text.symbols import symbols
+
+dictConfig({
+ 'version': 1,
+ 'formatters': {'default': {
+ 'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
+ }},
+ 'handlers': {'wsgi': {
+ 'class': 'logging.StreamHandler',
+ 'stream': 'ext://flask.logging.wsgi_errors_stream',
+ 'formatter': 'default'
+ }},
+ 'root': {
+ 'level': 'INFO',
+ 'handlers': ['wsgi']
+ }
+})
+
+app = Flask(__name__, static_folder="../frontend/dist", static_url_path='/')
+CORS(app, resources={r"/*": {"origins": "*"}})
+
+class VoiceChanger():
+ def __init__(self, config, model):
+ self.hps =utils.get_hparams_from_file(config)
+ self.net_g = SynthesizerTrn(
+ len(symbols),
+ self.hps.data.filter_length // 2 + 1,
+ self.hps.train.segment_size // self.hps.data.hop_length,
+ n_speakers=self.hps.data.n_speakers,
+ **self.hps.model)
+ self.net_g.eval()
+ self.gpu_num = torch.cuda.device_count()
+ print("GPU_NUM:",self.gpu_num)
+ utils.load_checkpoint( model, self.net_g, None)
+
+
+ def on_request(self, gpu, srcId, dstId, timestamp, wav):
+ if wav==0:
+ samplerate, data=read("dummy.wav")
+ unpackedData = data
+ else:
+ unpackedData = np.array(struct.unpack('<%sh'%(len(wav) // struct.calcsize('
\ No newline at end of file
diff --git a/docs/assets/icons/flect.png b/docs/assets/icons/flect.png
new file mode 100755
index 00000000..eb25e5d0
Binary files /dev/null and b/docs/assets/icons/flect.png differ
diff --git a/docs/assets/icons/github.svg b/docs/assets/icons/github.svg
new file mode 100755
index 00000000..cac76304
--- /dev/null
+++ b/docs/assets/icons/github.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/assets/icons/home.svg b/docs/assets/icons/home.svg
new file mode 100755
index 00000000..7e630021
--- /dev/null
+++ b/docs/assets/icons/home.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/assets/icons/linkedin.svg b/docs/assets/icons/linkedin.svg
new file mode 100755
index 00000000..021adb4d
--- /dev/null
+++ b/docs/assets/icons/linkedin.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/assets/icons/twitter.svg b/docs/assets/icons/twitter.svg
new file mode 100755
index 00000000..640ade90
--- /dev/null
+++ b/docs/assets/icons/twitter.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/assets/images/bg_natural_sougen.jpg b/docs/assets/images/bg_natural_sougen.jpg
new file mode 100755
index 00000000..471cfb36
Binary files /dev/null and b/docs/assets/images/bg_natural_sougen.jpg differ
diff --git a/docs/assets/model_float16_quant.bin33ee0cfa3b13c82ace2a b/docs/assets/model_float16_quant.bin33ee0cfa3b13c82ace2a
new file mode 100755
index 00000000..28165cf2
Binary files /dev/null and b/docs/assets/model_float16_quant.bin33ee0cfa3b13c82ace2a differ
diff --git a/docs/assets/palm_detection_lite.binba92fbef448d5b4334bc b/docs/assets/palm_detection_lite.binba92fbef448d5b4334bc
new file mode 100755
index 00000000..a19339a5
Binary files /dev/null and b/docs/assets/palm_detection_lite.binba92fbef448d5b4334bc differ
diff --git a/docs/assets/pose_detection.bin5f6876fde03ed33ebc9a b/docs/assets/pose_detection.bin5f6876fde03ed33ebc9a
new file mode 100755
index 00000000..4f1c521d
Binary files /dev/null and b/docs/assets/pose_detection.bin5f6876fde03ed33ebc9a differ
diff --git a/docs/assets/pose_landmark_lite.bin80f1d546bddf782578f3 b/docs/assets/pose_landmark_lite.bin80f1d546bddf782578f3
new file mode 100755
index 00000000..280cc722
Binary files /dev/null and b/docs/assets/pose_landmark_lite.bin80f1d546bddf782578f3 differ
diff --git a/docs/assets/setting.json b/docs/assets/setting.json
new file mode 100755
index 00000000..18eba437
--- /dev/null
+++ b/docs/assets/setting.json
@@ -0,0 +1,35 @@
+{
+ "app_title": "voice-changer",
+ "majar_mode": "docker",
+ "voice_changer_server_url": "http://localhost:8080/test",
+ "sample_rate": 48000,
+ "buffer_size": 1024,
+ "prefix_chunk_size": 24,
+ "chunk_size": 24,
+ "speaker_ids": [100, 107, 101, 102, 103],
+ "speaker_names": ["ずんだもん", "user", "そら", "めたん", "つぐみ"],
+ "src_id": 107,
+ "dst_id": 100,
+ "vf_enable": true,
+ "voice_changer_mode": "realtime",
+ "gpu": 0,
+ "available_gpus": [-1, 0, 1, 2, 3, 4],
+ "avatar": {
+ "motion_capture_face": true,
+ "motion_capture_upperbody": true,
+ "lip_overwrite_with_voice": true,
+ "avatar_url": "./assets/vrm/zundamon/zundamon.vrm",
+ "backgournd_image_url": "./assets/images/bg_natural_sougen.jpg",
+ "background_color": "#0000dd",
+ "chroma_key": "#0000dd",
+ "avatar_canvas_size": [1280, 720],
+ "screen_canvas_size": [1280, 720]
+ },
+ "advance": {
+ "avatar_draw_skip_rate": 3,
+ "screen_draw_skip_rate": 3,
+ "visualizer_draw_skip_rate": 3,
+ "cross_fade_lower_value": 0.1,
+ "cross_fade_overlap_rate": 0.03
+ }
+}
diff --git a/docs/assets/tflite-simd.wasm1f6a0e789251efcdaa4d b/docs/assets/tflite-simd.wasm1f6a0e789251efcdaa4d
new file mode 100755
index 00000000..34343721
Binary files /dev/null and b/docs/assets/tflite-simd.wasm1f6a0e789251efcdaa4d differ
diff --git a/docs/assets/vrm/zundamon/ReadMe.txt b/docs/assets/vrm/zundamon/ReadMe.txt
new file mode 100755
index 00000000..f0240050
--- /dev/null
+++ b/docs/assets/vrm/zundamon/ReadMe.txt
@@ -0,0 +1,75 @@
+この度は「ずんだもん(人型)」モデルデータセットをお求めいただき、誠にありがとうございます。
+ずんだもん(人型)モデルデータは、以下のフォーマットを用意しています。
+
+
+・VRChat用データ(PC/Oculus対応)
+ VRChat上で必要なプログラム、マテリアル、PC用ではDynamicBoneを設定済みのUnity用編集データ(.unitypackage)です。
+・MMDデータ
+ 剛体、ジョイント、マテリアル等を設定済みのモデルデータ(.pmx)です。
+・VRMデータ
+ VRMデータ対応の各プラットフォームで使用可能するモデルデータ(.vrm)です。SpringBone、コライダ、マテリアル等を設定済みです。
+・FBXデータ
+ 上記3フォーマット作成に使用したfbxデータです。ゲーム制作等、必要に応じてご使用下さい。
+・blenderデータ
+ FBXデータを作成する際のモデルデータ(.blender)です。必要に応じてご使用下さい。
+・PSDデータ
+ UVマップレイヤーを同梱したPSDファイルです。モデル用テクスチャを改変の際にご使用下さい。
+
+なお、上記モデル用テクスチャデータ(.png)を、各々のモデルデータへ同梱しています。
+
+
+モデルデータ詳細=====================================
+●VRChat用データ(PC/Oculus対応)
+ ・VRChat用データを使用する場合、別途オーサリングソフトウェアである「Unity2019.4.31f1」が必要です。
+ ・Avatar3.0専用です。Avatar2.0ではご使用できません。
+ ・マテリアル・シェーダーでは「ユニティちゃんトゥーンシェーダー2.0.8」を使用しています。
+ 本モデルデータには上記シェーダーは同梱されておりませんので、あらかじめご用意をお願いします。
+ ・PC版ではDynamicBone設定済みですが、DynamicBone本体は同梱されておりません。
+ あらかじめ購入およびご用意をお願いします。
+ ・シェイプキー 口:20種 目:12種 眉:3種 その他:1種を同梱しております。
+ ・PC版、Oculus版共にハンドサインにて表情切替可能です(7種)。
+ ・ハンドサインに登録されていない表情は、Unityエディターで切り替え編集を行って下さい。
+ ・PC版ではフルトラッキング対応です。基本的には腰、両足首にトラッカーを装着して下さい。
+ ・PC版では衣装やアクセサリーは別パーツとなっており、Unity上で脱着が可能です。
+ ・Oculus版では、仕様により衣装やアクセサリーの脱着は行えません。
+ ・VRChatへの詳しい導入方法は別途「VRChatキャラクター導入マニュアル」をご覧下さい。
+
+●MMDデータ
+ ・MMDデータを使用する場合、別途「MikuMikuDance」「MikuMikuMoving」などのMMD対応ソフトウェアが必要です。
+ ・剛体、ジョイント、IK設定済みです。
+ ・準標準ボーン(全ての親、グループ、上半身2、腰、肩キャンセル、腕捩、手捩、親指0、足IK親)が設定済みです。
+ ・衣装やアクセサリーは別パーツとなっており、その他モーフ「脱衣」パラメータを1にすることで脱衣可能です。
+
+●VRMデータ
+ ・VRMデータを使用する場合、VRMモデルを使用できる各アプリケーションが別途必要です。
+ ・VRMSDK ver.0.92を使用してデータを作成しています。
+ ・SpringBoneおよびSpringBoneCollider設定済みです。
+ ・シェーダーはVRM MToonおよびスタンダードシェーダーを使用しています。
+ ・BlendShapeは基本12種(A,I,U,E,O,Blink,Joy,Angly,Sorrow,Fun)から更に8種追加(Wink_L,Wink_R,Star,Hachume,No_HightLight,Aozame,Hauu,Tear)の全20種使用可能です。
+
+●FBXデータ
+ ・FBXデータバージョンは2020となっています。アプリケーションによっては正常に読み込むことができない場合があります。
+ ・FBXデータご使用の際は、必ずテクスチャファイルも同時にインポート願います。
+ ・アプリケーションへインポートの際、座標系の問題が生じるおそれがあります(Z軸が縦方向、Y軸が奥行となります)
+ ・メッシュデータ、ボーンデータ、マテリアル以外のデータ(ライト、カメラ、モーションなど)は同梱されていません。
+
+●Blenderデータ
+ ・Blenderデータバージョンは2.93です。バージョン2.93以前のBlenderでは正常に読み込むことができない場合があります。
+ ・MMD以外のボーン(アーマーチュア)に対応しています。MMDではボーン構造が特殊なため対応していません。
+ ・IKは設定しておりません。必要に応じてIKを設定願います。
+ ・素体、各衣装やアクセサリーを別オブジェクトとなりますので、お好みに合わせて脱着することが可能です。
+
+=====================================
+
+
+●ご利用規約、禁止事項、免責事項は別途「ずんだもん(人型)モデル利用規約.txt」をご覧下さい。
+
+
+●お問合せ先
+不具合、バグ、感想、調整、商用利用などのお問合せなどは、ホームページ(https://zunko.jp)よりご連絡下さい。
+
+
+
+
+●更新履歴
+2021/12/31 初版
diff --git a/docs/assets/vrm/zundamon/zundamon.vrm b/docs/assets/vrm/zundamon/zundamon.vrm
new file mode 100755
index 00000000..b4612b21
Binary files /dev/null and b/docs/assets/vrm/zundamon/zundamon.vrm differ
diff --git a/docs/assets/vrm/zundamon/ずんだもん(人型)モデル利用規約(Terms of Use).txt b/docs/assets/vrm/zundamon/ずんだもん(人型)モデル利用規約(Terms of Use).txt
new file mode 100755
index 00000000..fa10f2c4
--- /dev/null
+++ b/docs/assets/vrm/zundamon/ずんだもん(人型)モデル利用規約(Terms of Use).txt
@@ -0,0 +1,68 @@
+ずんだもん(人型) モデルデータ利用規約
+
+3Dモデリング:絹井けい
+販売元:SSS LLC. (https://zunko.jp)※以下「当社」とします。
+
+・本モデルを利用、もしくは改変した時点で本規約に同意したものとします。
+・本ライセンスの内容は変更する場合があり、最新のものが適用されます。
+・本ライセンスは日本語のものが正本とされ、翻訳と差異がある場合は常に日本語のものが優先されます。
+・本モデルの二次創作物を利用することによって生じた何らかのトラブル・損失に対し、絹井けい、および当社は一切責任を負わないものとします。
+・本モデルを改変した二次創作物の著作権法上の全ての権利は当社に帰属するものとします。
+
+
+●利用規約●
+本モデルでは基礎条項に加え、個別条項を元に以下の行為を許可します。
+
+・二次的著作物の配布の許可
+・成人向け表現(性的表現)の許可
+・成人向け表現(暴力表現)の許可
+・本モデルでの利用を目的とした衣装等を配布・頒布・販売する場合に限り、本モデルが含む以下のデータを流用することを許可します。ただし改変が著しく少ない場合を除きます。
+ 1.本モデルを構成するボーン・ウェイト
+ 2.モデルの素体パーツ「ずんだもん(人型)」メッシュデータ
+・当モデルデータを営利目的で使用する場合、販売元であるSSS LLC.が運営する「東北ずん子」ウェブサイトにて記載されている「版権商用利用の手引き(https://zunko.jp/con_shoushi.html)」に従ってください。
+ ただし以下の場合、事前受諾は不要です。
+ 1.印刷やディスクプレスなど、個人から依頼されたものを複製する場合
+ 2.動画や写真への映り込みなど、本モデルがメインコンテンツと判断されない場合
+
+
+
+●お問合せ先●
+
+ホームページ:https://zunko.jp/
+版権商用利用の手引き:https://zunko.jp/con_shoushi.html
+
+
+
+EN:Zundamon (humanoid) Model Data Terms of Use
+
+3D modeling: Kei Kinui
+Distributed by: SSS LLC. (https://zunko.jp) hereinafter referred to as "the Company".
+
+*By using or modifying this model, you agree to be bound by these terms.
+*The content of this license is subject to change, and the latest version shall apply.
+*The Japanese version of this license shall be the original, and if there are any differences between the Japanese version and the translated version, the Japanese version shall always take precedence.
+*Kei Kinui and the Company shall not be held responsible for any problems or losses that may arise from the use of secondary works of this model.
+*All rights under copyright law for secondary works modified from this model shall belong to the Company.
+
+
+*Terms of Use*
+In addition to the basic terms, this model permits the following actions based on the individual terms.
+
+*Permission to distribute derivative works
+*Permission for adult expression (sexual expression)
+*Permission to use adult-oriented expressions (violent expressions)
+*Permission is granted to use the following data included in this model only for the purpose of distributing or selling costumes, etc. for use in this model. However, this excludes cases where the modifications are extremely small.
+ 1:The bones and weights that make up the model
+ 2:Mesh data of the model's body part "Zundamon (humanoid)
+*If you wish to use this model data for commercial purposes, please follow the "Guide to the Commercial Use of Copyrighted Material (https://zunko.jp/con_shoushi.html)" described on the "Tohoku Zunko" website operated by SSS LLC, the distributor.
+ However, prior consent is not required in the following cases
+ 1:Reproduction of materials commissioned by individuals, such as printing or disc pressing.
+ 2:When this model is not judged to be the main content, such as reflection in videos or photos.
+
+
+
+*contact us*
+
+HomePage(https://zunko.jp)
+
+Guide to the Commercial Use of Copyrighted Material(https://zunko.jp/con_shoushi.html)
\ No newline at end of file
diff --git a/docs/audiolet/index.js b/docs/audiolet/index.js
new file mode 100755
index 00000000..df60d652
--- /dev/null
+++ b/docs/audiolet/index.js
@@ -0,0 +1 @@
+(()=>{"use strict";class e extends AudioWorkletProcessor{initialized=!1;playBuffer=[];deltaChunkSize=24;bufferSize=1024;constructor(){super(),this.initialized=!0,this.port.onmessage=this.handleMessage.bind(this)}prevF32Data=null;handleMessage(e){if(e.data.deltaSize)return void(this.deltaChunkSize=e.data.deltaSize);const t=e.data.data,l=new Int16Array(t),n=new Float32Array(l.length);l.forEach(((e,t)=>{const l=e>=32768?-(65536-e)/32768:e/32767;n[t]=l}));let s=this.prevF32Data?this.prevF32Data.slice(this.prevF32Data.length-this.deltaChunkSize*this.bufferSize/2):null;const h=n.slice(n.length-this.deltaChunkSize*this.bufferSize*2/2,n.length-this.deltaChunkSize*this.bufferSize/2);if(s?.length!==h.length&&(s=null),s)for(let e=0;es.length/3*2)t=1;else{const l=e-s.length/3;t=Math.min(l/(s.length/3),1)}const l=s[e]*(1-t),n=h[e]*t;h[e]=l+n}if(this.playBuffer.length>50)for(console.log("Buffer truncated");this.playBuffer.length>2;)this.playBuffer.shift();let i;for(let e=0;e{const l=e>=32768?-(65536-e)/32768:e/32767;n[t]=l}));let s=this.prevF32Data?this.prevF32Data.slice(this.prevF32Data.length/2):null;const h=n.slice(0,n.length/2);if(s?.length!==h.length&&(s=null),s)for(let e=0;es.length/3*2)t=1;else{const l=e-s.length/3;t=Math.min(l/(s.length/100),1)}const l=s[e]*(1-t),n=h[e]*t;h[e]=l+n}if(this.playBuffer.length>100)for(console.log("Buffer truncated");this.playBuffer.length>2;)this.playBuffer.shift();let i;for(let e=0;evoice recorder
\ No newline at end of file
diff --git a/docs/index.js b/docs/index.js
new file mode 100755
index 00000000..a36c9045
--- /dev/null
+++ b/docs/index.js
@@ -0,0 +1,2 @@
+/*! For license information please see index.js.LICENSE.txt */
+(()=>{var __webpack_modules__={914:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RawSha256=void 0;var i=n(6532),r=function(){function e(){this.state=Int32Array.from(i.INIT),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}return e.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");var t=0,n=e.byteLength;if(this.bytesHashed+=n,8*this.bytesHashed>i.MAX_HASHABLE_LENGTH)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[t++],n--,this.bufferLength===i.BLOCK_SIZE&&(this.hashBuffer(),this.bufferLength=0)},e.prototype.digest=function(){if(!this.finished){var e=8*this.bytesHashed,t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),n=this.bufferLength;if(t.setUint8(this.bufferLength++,128),n%i.BLOCK_SIZE>=i.BLOCK_SIZE-8){for(var r=this.bufferLength;r>>24&255,a[4*r+1]=this.state[r]>>>16&255,a[4*r+2]=this.state[r]>>>8&255,a[4*r+3]=this.state[r]>>>0&255;return a},e.prototype.hashBuffer=function(){for(var e=this.buffer,t=this.state,n=t[0],r=t[1],a=t[2],o=t[3],s=t[4],c=t[5],l=t[6],u=t[7],d=0;d>>17|h<<15)^(h>>>19|h<<13)^h>>>10,p=((h=this.temp[d-15])>>>7|h<<25)^(h>>>18|h<<14)^h>>>3;this.temp[d]=(f+this.temp[d-7]|0)+(p+this.temp[d-16]|0)}var m=(((s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7))+(s&c^~s&l)|0)+(u+(i.KEY[d]+this.temp[d]|0)|0)|0,g=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&r^n&a^r&a)|0;u=l,l=c,c=s,s=o+m|0,o=a,a=r,r=n,n=m+g|0}t[0]+=n,t[1]+=r,t[2]+=a,t[3]+=o,t[4]+=s,t[5]+=c,t[6]+=l,t[7]+=u},e}();t.RawSha256=r},6532:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MAX_HASHABLE_LENGTH=t.INIT=t.KEY=t.DIGEST_LENGTH=t.BLOCK_SIZE=void 0,t.BLOCK_SIZE=64,t.DIGEST_LENGTH=32,t.KEY=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),t.INIT=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],t.MAX_HASHABLE_LENGTH=Math.pow(2,53)-1},1938:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),(0,n(655).__exportStar)(n(5430),t)},5430:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Sha256=void 0;var i=n(655),r=n(6532),a=n(914),o=n(7658),s=function(){function e(e){if(this.hash=new a.RawSha256,e){this.outer=new a.RawSha256;var t=function(e){var t=(0,o.convertToBuffer)(e);if(t.byteLength>r.BLOCK_SIZE){var n=new a.RawSha256;n.update(t),t=n.digest()}var i=new Uint8Array(r.BLOCK_SIZE);return i.set(t),i}(e),n=new Uint8Array(r.BLOCK_SIZE);n.set(t);for(var i=0;i{"use strict";var i=n(8764).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.convertToBuffer=void 0;var r=n(470),a=void 0!==i&&i.from?function(e){return i.from(e,"utf8")}:r.fromUtf8;t.convertToBuffer=function(e){return e instanceof Uint8Array?e:"string"==typeof e?a(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}},7658:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uint32ArrayFrom=t.numToUint8=t.isEmptyData=t.convertToBuffer=void 0;var i=n(1106);Object.defineProperty(t,"convertToBuffer",{enumerable:!0,get:function(){return i.convertToBuffer}});var r=n(4304);Object.defineProperty(t,"isEmptyData",{enumerable:!0,get:function(){return r.isEmptyData}});var a=n(2174);Object.defineProperty(t,"numToUint8",{enumerable:!0,get:function(){return a.numToUint8}});var o=n(1558);Object.defineProperty(t,"uint32ArrayFrom",{enumerable:!0,get:function(){return o.uint32ArrayFrom}})},4304:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEmptyData=void 0,t.isEmptyData=function(e){return"string"==typeof e?0===e.length:0===e.byteLength}},2174:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.numToUint8=void 0,t.numToUint8=function(e){return new Uint8Array([(4278190080&e)>>24,(16711680&e)>>16,(65280&e)>>8,255&e])}},1558:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uint32ArrayFrom=void 0,t.uint32ArrayFrom=function(e){if(!Uint32Array.from){for(var t=new Uint32Array(e.length),n=0;n{"use strict";n.r(t),n.d(t,{fromHex:()=>s,toHex:()=>c});for(var i={},r={},a=0;a<256;a++){var o=a.toString(16).toLowerCase();1===o.length&&(o="0".concat(o)),i[a]=o,r[o]=a}function s(e){if(e.length%2!=0)throw new Error("Hex encoded strings must have an even number length");for(var t=new Uint8Array(e.length/2),n=0;n{"use strict";n.r(t),n.d(t,{fromUtf8:()=>i,toUtf8:()=>r});var i=function(e){return"function"==typeof TextEncoder?function(e){return(new TextEncoder).encode(e)}(e):function(e){for(var t=[],n=0,i=e.length;n>6|192,63&r|128);else if(n+1>18|240,a>>12&63|128,a>>6&63|128,63&a|128)}else t.push(r>>12|224,r>>6&63|128,63&r|128)}return Uint8Array.from(t)}(e)},r=function(e){return"function"==typeof TextDecoder?function(e){return new TextDecoder("utf-8").decode(e)}(e):function(e){for(var t="",n=0,i=e.length;n(()=>{var e={373:function(e,t,n){var i;"undefined"!=typeof self&&self,i=()=>(()=>{var e={252:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BlockingQueue=void 0;var n=function(){function e(){this._resolvers=[],this._promises=[]}return e.prototype._add=function(){var e=this;this._promises.push(new Promise((function(t){e._resolvers.push(t)})))},e.prototype.enqueue=function(e){this._resolvers.length||this._add(),this._resolvers.shift()(e)},e.prototype.dequeue=function(){return this._promises.length||this._add(),this._promises.shift()},e.prototype.isEmpty=function(){return!this._promises.length},e.prototype.isBlocked=function(){return!!this._resolvers.length},Object.defineProperty(e.prototype,"length",{get:function(){return this._promises.length-this._resolvers.length},enumerable:!1,configurable:!0}),e}();t.BlockingQueue=n},289:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getBrowserType=t.BrowserTypes=void 0,t.BrowserTypes={MSIE:"MSIE",EDGE:"EDGE",CHROME:"CHROME",SAFARI:"SAFARI",FIREFOX:"FIREFOX",OPERA:"OPERA",OTHER:"OTHER"},t.getBrowserType=function(){var e=window.navigator.userAgent.toLowerCase();return-1!==e.indexOf("msie")||-1!==e.indexOf("trident")?t.BrowserTypes.MSIE:-1!==e.indexOf("edge")?t.BrowserTypes.EDGE:-1!==e.indexOf("chrome")?t.BrowserTypes.CHROME:-1!==e.indexOf("safari")?t.BrowserTypes.SAFARI:-1!==e.indexOf("firefox")?t.BrowserTypes.FIREFOX:-1!==e.indexOf("opera")?t.BrowserTypes.OPERA:t.BrowserTypes.OTHER}},187:function(e,t,n){"use strict";var i=n(764).lW,r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},a=this&&this.__generator||function(e,t){var n,i,r,a,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,i&&(r=2&a[0]?i.return:a[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,a[1])).done)return r;switch(i=0,r&&(a=[2&a[0],r.value]),a[0]){case 0:case 1:r=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,i=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((r=(r=o.trys).length>0&&r[r.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]100)throw new Error("queue is fulled: ".concat(this.sem.length));return[4,this.lock()];case 1:e=a.sent(),r=new Promise((function(e,r){if(!l.worker)throw new Error("worker is not activated.");l.worker.onmessage=function(t){t.data.message===c.WorkerResponse.PREDICTED?e(t.data.prediction):(console.log("Prediction something wrong..",t.data.message),r(t))},i?n instanceof Uint8ClampedArray?l.worker.postMessage({message:c.WorkerCommand.PREDICT,params:t,data:n},[n.buffer]):l.worker.postMessage({message:c.WorkerCommand.PREDICT,params:t,data:n},[n]):l.worker.postMessage({message:c.WorkerCommand.PREDICT,params:t,data:n})})),a.label=2;case 2:return a.trys.push([2,4,5,6]),[4,r];case 3:return o=a.sent(),[3,6];case 4:return s=a.sent(),console.log("worker prediction error. :",s),[3,6];case 5:return this.unlock(e),[7];case 6:return[2,o]}}))}))},this.useWorker=function(e){return!e.processOnLocal&&(!1!==e.useWorkerForSafari||(0,s.getBrowserType)()!==s.BrowserTypes.SAFARI)},this.fetchData=function(t){return r(e,void 0,void 0,(function(){var e;return a(this,(function(n){switch(n.label){case 0:return t.startsWith("data:")?(e=t.split(",")[1],[2,i.from(e,"base64")]):[4,fetch(t,{method:"GET"})];case 1:return[4,n.sent().arrayBuffer()];case 2:return[2,n.sent()]}}))}))},this.sem.enqueue(0)},t.WorkerDispatcher=function(e){var t=this;this.imageProcessor=null,this.config=null,this.callbacks=null,this.setCallback=function(e){t.callbacks=e},this.dispach=function(e){return r(t,void 0,void 0,(function(){var t,n,i,r;return a(this,(function(a){switch(a.label){case 0:return this.callbacks?e.data.message!==c.WorkerCommand.INITIALIZE?[3,2]:(this.config=e.data.config,t=this,[4,this.callbacks.init(this.config)]):(console.warn("[worker] Dispatcher callbacks is not initialized"),[2]);case 1:return t.imageProcessor=a.sent(),this.context.postMessage({message:c.WorkerResponse.INITIALIZED}),console.log("[worker] Initialized"),[3,4];case 2:return e.data.message!==c.WorkerCommand.PREDICT?[3,4]:this.imageProcessor?this.config?(n=e.data.params,i=e.data.data,[4,this.imageProcessor.predict(this.config,n,i)]):(console.warn("[worker] Dispatcher config is not initialized"),[2]):(console.warn("[worker] ImageProcessor is not initialized"),[2]);case 3:r=a.sent(),this.context.postMessage({message:c.WorkerResponse.PREDICTED,prediction:r}),a.label=4;case 4:return[2]}}))}))},this.context=e}},301:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerResponse=t.WorkerCommand=void 0,t.WorkerCommand={INITIALIZE:"initialize",PREDICT:"predict"},t.WorkerResponse={INITIALIZED:"initialized",PREDICTED:"predicted"}},55:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),r(n(187),t),r(n(289),t)},742:(e,t)=>{"use strict";t.byteLength=function(e){var t=c(e),n=t[0],i=t[1];return 3*(n+i)/4-i},t.toByteArray=function(e){var t,n,a=c(e),o=a[0],s=a[1],l=new r(function(e,t,n){return 3*(t+n)/4-n}(0,o,s)),u=0,d=s>0?o-4:o;for(n=0;n>16&255,l[u++]=t>>8&255,l[u++]=255&t;return 2===s&&(t=i[e.charCodeAt(n)]<<2|i[e.charCodeAt(n+1)]>>4,l[u++]=255&t),1===s&&(t=i[e.charCodeAt(n)]<<10|i[e.charCodeAt(n+1)]<<4|i[e.charCodeAt(n+2)]>>2,l[u++]=t>>8&255,l[u++]=255&t),l},t.fromByteArray=function(e){for(var t,i=e.length,r=i%3,a=[],o=16383,s=0,c=i-r;sc?c:s+o));return 1===r?(t=e[i-1],a.push(n[t>>2]+n[t<<4&63]+"==")):2===r&&(t=(e[i-2]<<8)+e[i-1],a.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"=")),a.join("")};for(var n=[],i=[],r="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,s=a.length;o0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function l(e,t,i){for(var r,a,o=[],s=t;s>18&63]+n[a>>12&63]+n[a>>6&63]+n[63&a]);return o.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},764:(e,t,n)=>{"use strict";const i=n(742),r=n(645),a="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.lW=c,t.h2=50;const o=2147483647;function s(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,c.prototype),t}function c(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return d(e)}return l(e,t,n)}function l(e,t,n){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!c.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|m(e,t);let i=s(n);const r=i.write(e,t);return r!==n&&(i=i.slice(0,r)),i}(e,t);if(ArrayBuffer.isView(e))return function(e){if(J(e,Uint8Array)){const t=new Uint8Array(e);return f(t.buffer,t.byteOffset,t.byteLength)}return h(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(J(e,ArrayBuffer)||e&&J(e.buffer,ArrayBuffer))return f(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(J(e,SharedArrayBuffer)||e&&J(e.buffer,SharedArrayBuffer)))return f(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const i=e.valueOf&&e.valueOf();if(null!=i&&i!==e)return c.from(i,t,n);const r=function(e){if(c.isBuffer(e)){const t=0|p(e.length),n=s(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||$(e.length)?s(0):h(e):"Buffer"===e.type&&Array.isArray(e.data)?h(e.data):void 0}(e);if(r)return r;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return c.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function u(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function d(e){return u(e),s(e<0?0:0|p(e))}function h(e){const t=e.length<0?0:0|p(e.length),n=s(t);for(let i=0;i=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function m(e,t){if(c.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||J(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===n)return 0;let r=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return q(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return X(e).length;default:if(r)return i?-1:q(e).length;t=(""+t).toLowerCase(),r=!0}}function g(e,t,n){let i=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return A(this,t,n);case"utf8":case"utf-8":return L(this,t,n);case"ascii":return T(this,t,n);case"latin1":case"binary":return z(this,t,n);case"base64":return w(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V(this,t,n);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function C(e,t,n){const i=e[t];e[t]=e[n],e[n]=i}function v(e,t,n,i,r){if(0===e.length)return-1;if("string"==typeof n?(i=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),$(n=+n)&&(n=r?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(r)return-1;n=e.length-1}else if(n<0){if(!r)return-1;n=0}if("string"==typeof t&&(t=c.from(t,i)),c.isBuffer(t))return 0===t.length?-1:y(e,t,n,i,r);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,i,r);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,i,r){let a,o=1,s=e.length,c=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;o=2,s/=2,c/=2,n/=2}function l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(r){let i=-1;for(a=n;as&&(n=s-c),a=n;a>=0;a--){let n=!0;for(let i=0;ir&&(i=r):i=r;const a=t.length;let o;for(i>a/2&&(i=a/2),o=0;o>8,r=n%256,a.push(r),a.push(i);return a}(t,e.length-n),e,n,i)}function w(e,t,n){return 0===t&&n===e.length?i.fromByteArray(e):i.fromByteArray(e.slice(t,n))}function L(e,t,n){n=Math.min(e.length,n);const i=[];let r=t;for(;r239?4:t>223?3:t>191?2:1;if(r+o<=n){let n,i,s,c;switch(o){case 1:t<128&&(a=t);break;case 2:n=e[r+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(a=c));break;case 3:n=e[r+1],i=e[r+2],128==(192&n)&&128==(192&i)&&(c=(15&t)<<12|(63&n)<<6|63&i,c>2047&&(c<55296||c>57343)&&(a=c));break;case 4:n=e[r+1],i=e[r+2],s=e[r+3],128==(192&n)&&128==(192&i)&&128==(192&s)&&(c=(15&t)<<18|(63&n)<<12|(63&i)<<6|63&s,c>65535&&c<1114112&&(a=c))}}null===a?(a=65533,o=1):a>65535&&(a-=65536,i.push(a>>>10&1023|55296),a=56320|1023&a),i.push(a),r+=o}return function(e){const t=e.length;if(t<=E)return String.fromCharCode.apply(String,e);let n="",i=0;for(;ii.length?(c.isBuffer(t)||(t=c.from(t)),t.copy(i,r)):Uint8Array.prototype.set.call(i,t,r);else{if(!c.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(i,r)}r+=t.length}return i},c.byteLength=m,c.prototype._isBuffer=!0,c.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;tn&&(e+=" ... "),""},a&&(c.prototype[a]=c.prototype.inspect),c.prototype.compare=function(e,t,n,i,r){if(J(e,Uint8Array)&&(e=c.from(e,e.offset,e.byteLength)),!c.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===i&&(i=0),void 0===r&&(r=this.length),t<0||n>e.length||i<0||r>this.length)throw new RangeError("out of range index");if(i>=r&&t>=n)return 0;if(i>=r)return-1;if(t>=n)return 1;if(this===e)return 0;let a=(r>>>=0)-(i>>>=0),o=(n>>>=0)-(t>>>=0);const s=Math.min(a,o),l=this.slice(i,r),u=e.slice(t,n);for(let e=0;e>>=0,isFinite(n)?(n>>>=0,void 0===i&&(i="utf8")):(i=n,n=void 0)}const r=this.length-t;if((void 0===n||n>r)&&(n=r),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let a=!1;for(;;)switch(i){case"hex":return b(this,e,t,n);case"utf8":case"utf-8":return M(this,e,t,n);case"ascii":case"latin1":case"binary":return x(this,e,t,n);case"base64":return _(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(a)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),a=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const E=4096;function T(e,t,n){let i="";n=Math.min(e.length,n);for(let r=t;ri)&&(n=i);let r="";for(let i=t;in)throw new RangeError("Trying to access beyond buffer length")}function R(e,t,n,i,r,a){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>r||te.length)throw new RangeError("Index out of range")}function P(e,t,n,i,r){U(t,i,r,e,n,7);let a=Number(t&BigInt(4294967295));e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,n}function I(e,t,n,i,r){U(t,i,r,e,n,7);let a=Number(t&BigInt(4294967295));e[n+7]=a,a>>=8,e[n+6]=a,a>>=8,e[n+5]=a,a>>=8,e[n+4]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,o>>=8,e[n+2]=o,o>>=8,e[n+1]=o,o>>=8,e[n]=o,n+8}function k(e,t,n,i,r,a){if(n+i>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function N(e,t,n,i,a){return t=+t,n>>>=0,a||k(e,0,n,4),r.write(e,t,n,i,23,4),n+4}function D(e,t,n,i,a){return t=+t,n>>>=0,a||k(e,0,n,8),r.write(e,t,n,i,52,8),n+8}c.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t>>=0,t>>>=0,n||H(e,t,this.length);let i=this[e],r=1,a=0;for(;++a>>=0,t>>>=0,n||H(e,t,this.length);let i=this[e+--t],r=1;for(;t>0&&(r*=256);)i+=this[e+--t]*r;return i},c.prototype.readUint8=c.prototype.readUInt8=function(e,t){return e>>>=0,t||H(e,1,this.length),this[e]},c.prototype.readUint16LE=c.prototype.readUInt16LE=function(e,t){return e>>>=0,t||H(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUint16BE=c.prototype.readUInt16BE=function(e,t){return e>>>=0,t||H(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUint32LE=c.prototype.readUInt32LE=function(e,t){return e>>>=0,t||H(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUint32BE=c.prototype.readUInt32BE=function(e,t){return e>>>=0,t||H(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readBigUInt64LE=Z((function(e){W(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const i=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,r=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(i)+(BigInt(r)<>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const i=t*2**24+65536*this[++e]+256*this[++e]+this[++e],r=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(i)<>>=0,t>>>=0,n||H(e,t,this.length);let i=this[e],r=1,a=0;for(;++a=r&&(i-=Math.pow(2,8*t)),i},c.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||H(e,t,this.length);let i=t,r=1,a=this[e+--i];for(;i>0&&(r*=256);)a+=this[e+--i]*r;return r*=128,a>=r&&(a-=Math.pow(2,8*t)),a},c.prototype.readInt8=function(e,t){return e>>>=0,t||H(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){e>>>=0,t||H(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt16BE=function(e,t){e>>>=0,t||H(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt32LE=function(e,t){return e>>>=0,t||H(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return e>>>=0,t||H(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readBigInt64LE=Z((function(e){W(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const i=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(i)<>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const i=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(i)<>>=0,t||H(e,4,this.length),r.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return e>>>=0,t||H(e,4,this.length),r.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return e>>>=0,t||H(e,8,this.length),r.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return e>>>=0,t||H(e,8,this.length),r.read(this,e,!1,52,8)},c.prototype.writeUintLE=c.prototype.writeUIntLE=function(e,t,n,i){e=+e,t>>>=0,n>>>=0,i||R(this,e,t,n,Math.pow(2,8*n)-1,0);let r=1,a=0;for(this[t]=255&e;++a>>=0,n>>>=0,i||R(this,e,t,n,Math.pow(2,8*n)-1,0);let r=n-1,a=1;for(this[t+r]=255&e;--r>=0&&(a*=256);)this[t+r]=e/a&255;return t+n},c.prototype.writeUint8=c.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,1,255,0),this[t]=255&e,t+1},c.prototype.writeUint16LE=c.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeUint16BE=c.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeUint32LE=c.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},c.prototype.writeUint32BE=c.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeBigUInt64LE=Z((function(e,t=0){return P(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),c.prototype.writeBigUInt64BE=Z((function(e,t=0){return I(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),c.prototype.writeIntLE=function(e,t,n,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*n-1);R(this,e,t,n,i-1,-i)}let r=0,a=1,o=0;for(this[t]=255&e;++r>0)-o&255;return t+n},c.prototype.writeIntBE=function(e,t,n,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*n-1);R(this,e,t,n,i-1,-i)}let r=n-1,a=1,o=0;for(this[t+r]=255&e;--r>=0&&(a*=256);)e<0&&0===o&&0!==this[t+r+1]&&(o=1),this[t+r]=(e/a>>0)-o&255;return t+n},c.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},c.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeBigInt64LE=Z((function(e,t=0){return P(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),c.prototype.writeBigInt64BE=Z((function(e,t=0){return I(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),c.prototype.writeFloatLE=function(e,t,n){return N(this,e,t,!0,n)},c.prototype.writeFloatBE=function(e,t,n){return N(this,e,t,!1,n)},c.prototype.writeDoubleLE=function(e,t,n){return D(this,e,t,!0,n)},c.prototype.writeDoubleBE=function(e,t,n){return D(this,e,t,!1,n)},c.prototype.copy=function(e,t,n,i){if(!c.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(r=t;r=i+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function U(e,t,n,i,r,a){if(e>n||e3?0===t||t===BigInt(0)?`>= 0${i} and < 2${i} ** ${8*(a+1)}${i}`:`>= -(2${i} ** ${8*(a+1)-1}${i}) and < 2 ** ${8*(a+1)-1}${i}`:`>= ${t}${i} and <= ${n}${i}`,new O.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){W(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||G(t,e.length-(n+1))}(i,r,a)}function W(e,t){if("number"!=typeof e)throw new O.ERR_INVALID_ARG_TYPE(t,"number",e)}function G(e,t,n){if(Math.floor(e)!==e)throw W(e,n),new O.ERR_OUT_OF_RANGE(n||"offset","an integer",e);if(t<0)throw new O.ERR_BUFFER_OUT_OF_BOUNDS;throw new O.ERR_OUT_OF_RANGE(n||"offset",`>= ${n?1:0} and <= ${t}`,e)}B("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),B("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),B("ERR_OUT_OF_RANGE",(function(e,t,n){let i=`The value of "${e}" is out of range.`,r=n;return Number.isInteger(n)&&Math.abs(n)>2**32?r=F(String(n)):"bigint"==typeof n&&(r=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(r=F(r)),r+="n"),i+=` It must be ${t}. Received ${r}`,i}),RangeError);const j=/[^+/0-9A-Za-z-_]/g;function q(e,t){let n;t=t||1/0;const i=e.length;let r=null;const a=[];for(let o=0;o55295&&n<57344){if(!r){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(o+1===i){(t-=3)>-1&&a.push(239,191,189);continue}r=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),r=n;continue}n=65536+(r-55296<<10|n-56320)}else r&&(t-=3)>-1&&a.push(239,191,189);if(r=null,n<128){if((t-=1)<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return a}function X(e){return i.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(j,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Y(e,t,n,i){let r;for(r=0;r=t.length||r>=e.length);++r)t[r+n]=e[r];return r}function J(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function $(e){return e!=e}const K=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const i=16*n;for(let r=0;r<16;++r)t[i+r]=e[n]+e[r]}return t}();function Z(e){return"undefined"==typeof BigInt?Q:e}function Q(){throw new Error("BigInt not supported")}},645:(e,t)=>{t.read=function(e,t,n,i,r){var a,o,s=8*r-i-1,c=(1<>1,u=-7,d=n?r-1:0,h=n?-1:1,f=e[t+d];for(d+=h,a=f&(1<<-u)-1,f>>=-u,u+=s;u>0;a=256*a+e[t+d],d+=h,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=i;u>0;o=256*o+e[t+d],d+=h,u-=8);if(0===a)a=1-l;else{if(a===c)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,i),a-=l}return(f?-1:1)*o*Math.pow(2,a-i)},t.write=function(e,t,n,i,r,a){var o,s,c,l=8*a-r-1,u=(1<>1,h=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,f=i?0:a-1,p=i?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),(t+=o+d>=1?h/c:h*Math.pow(2,1-d))*c>=2&&(o++,c/=2),o+d>=u?(s=0,o=u):o+d>=1?(s=(t*c-1)*Math.pow(2,r),o+=d):(s=t*Math.pow(2,d-1)*Math.pow(2,r),o=0));r>=8;e[n+f]=255&s,f+=p,s/=256,r-=8);for(o=o<0;e[n+f]=255&o,f+=p,o/=256,l-=8);e[n+f-p]|=128*m}},477:e=>{"use strict";e.exports=function(e,t,n,i){var r=self||window;try{try{var a;try{a=new r.Blob([e])}catch(t){(a=new(r.BlobBuilder||r.WebKitBlobBuilder||r.MozBlobBuilder||r.MSBlobBuilder)).append(e),a=a.getBlob()}var o=r.URL||r.webkitURL,s=o.createObjectURL(a),c=new r[t](s,n);return o.revokeObjectURL(s),c}catch(i){return new r[t]("data:application/javascript,".concat(encodeURIComponent(e)),n)}}catch(e){if(!i)throw Error("Inline worker is not supported");return new r[t](i,n)}}},503:(e,t,n)=>{var i,a=n(764).lW,o=(i=(i="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(e){var t,o,s=void 0!==(e=e||{})?e:{},c=Object.assign;s.ready=new Promise((function(e,n){t=e,o=n}));var l,u,d,h,f,p,m=c({},s),g=[],C="./this.program",v=(e,t)=>{throw t},y="object"==typeof window,b="function"==typeof importScripts,M="object"==typeof r&&"object"==typeof r.versions&&"string"==typeof r.versions.node,x="";M?(x=b?n(375).dirname(x)+"/":"//",p=()=>{f||(h=n(384),f=n(375))},l=function(e,t){return p(),e=f.normalize(e),h.readFileSync(e,t?null:"utf8")},d=e=>{var t=l(e,!0);return t.buffer||(t=new Uint8Array(t)),t},u=(e,t,n)=>{p(),e=f.normalize(e),h.readFile(e,(function(e,i){e?n(e):t(i.buffer)}))},r.argv.length>1&&(C=r.argv[1].replace(/\\/g,"/")),g=r.argv.slice(2),r.on("uncaughtException",(function(e){if(!(e instanceof Ae))throw e})),r.on("unhandledRejection",(function(e){throw e})),v=(e,t)=>{if(W())throw r.exitCode=e,t;var n;(n=t)instanceof Ae||w("exiting due to exception: "+n),r.exit(e)},s.inspect=function(){return"[Emscripten Module object]"}):(y||b)&&(b?x=self.location.href:"undefined"!=typeof document&&document.currentScript&&(x=document.currentScript.src),i&&(x=i),x=0!==x.indexOf("blob:")?x.substr(0,x.replace(/[?#].*/,"").lastIndexOf("/")+1):"",l=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},b&&(d=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),u=(e,t,n)=>{var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=()=>{200==i.status||0==i.status&&i.response?t(i.response):n()},i.onerror=n,i.send(null)});var _,S=s.print||console.log.bind(console),w=s.printErr||console.warn.bind(console);c(s,m),m=null,s.arguments&&(g=s.arguments),s.thisProgram&&(C=s.thisProgram),s.quit&&(v=s.quit),s.wasmBinary&&(_=s.wasmBinary);var L,E=s.noExitRuntime||!0;"object"!=typeof WebAssembly&&Q("no native wasm support detected");var T,z,A,V,H=!1,R="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function P(e,t,n){for(var i=t+n,r=t;e[r]&&!(r>=i);)++r;if(r-t>16&&e.subarray&&R)return R.decode(e.subarray(t,r));for(var a="";t>10,56320|1023&l)}}else a+=String.fromCharCode((31&o)<<6|s)}else a+=String.fromCharCode(o)}return a}function I(e,t){return e?P(A,e,t):""}function k(e,t,n,i){if(!(i>0))return 0;for(var r=n,a=n+i-1,o=0;o=55296&&s<=57343&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++o)),s<=127){if(n>=a)break;t[n++]=s}else if(s<=2047){if(n+1>=a)break;t[n++]=192|s>>6,t[n++]=128|63&s}else if(s<=65535){if(n+2>=a)break;t[n++]=224|s>>12,t[n++]=128|s>>6&63,t[n++]=128|63&s}else{if(n+3>=a)break;t[n++]=240|s>>18,t[n++]=128|s>>12&63,t[n++]=128|s>>6&63,t[n++]=128|63&s}}return t[n]=0,n-r}function N(e){for(var t=0,n=0;n=55296&&i<=57343&&(i=65536+((1023&i)<<10)|1023&e.charCodeAt(++n)),i<=127?++t:t+=i<=2047?2:i<=65535?3:4}return t}function D(e){T=e,s.HEAP8=z=new Int8Array(e),s.HEAP16=new Int16Array(e),s.HEAP32=V=new Int32Array(e),s.HEAPU8=A=new Uint8Array(e),s.HEAPU16=new Uint16Array(e),s.HEAPU32=new Uint32Array(e),s.HEAPF32=new Float32Array(e),s.HEAPF64=new Float64Array(e)}s.INITIAL_MEMORY;var O,B=[],F=[],U=[];function W(){return E||!1}var G,j,q,X,Y=0,J=null,$=null;function K(e){Y++,s.monitorRunDependencies&&s.monitorRunDependencies(Y)}function Z(e){if(Y--,s.monitorRunDependencies&&s.monitorRunDependencies(Y),0==Y&&(null!==J&&(clearInterval(J),J=null),$)){var t=$;$=null,t()}}function Q(e){s.onAbort&&s.onAbort(e),w(e="Aborted("+e+")"),H=!0,e+=". Build with -s ASSERTIONS=1 for more info.";var t=new WebAssembly.RuntimeError(e);throw o(t),t}function ee(e){return e.startsWith("data:application/octet-stream;base64,")}function te(e){return e.startsWith("file://")}function ne(e){try{if(e==G&&_)return new Uint8Array(_);if(d)return d(e);throw"both async and sync fetching of the wasm failed"}catch(e){Q(e)}}function ie(e){for(;e.length>0;){var t=e.shift();if("function"!=typeof t){var n=t.func;"number"==typeof n?void 0===t.arg?oe(n)():oe(n)(t.arg):n(void 0===t.arg?null:t.arg)}else t(s)}}s.preloadedImages={},s.preloadedAudios={},ee(G="tflite-simd.wasm")||(j=G,G=s.locateFile?s.locateFile(j,x):x+j);var re,ae=[];function oe(e){var t=ae[e];return t||(e>=ae.length&&(ae.length=e+1),ae[e]=t=O.get(e)),t}function se(e){this.excPtr=e,this.ptr=e-16,this.set_type=function(e){V[this.ptr+4>>2]=e},this.get_type=function(){return V[this.ptr+4>>2]},this.set_destructor=function(e){V[this.ptr+8>>2]=e},this.get_destructor=function(){return V[this.ptr+8>>2]},this.set_refcount=function(e){V[this.ptr>>2]=e},this.set_caught=function(e){e=e?1:0,z[this.ptr+12>>0]=e},this.get_caught=function(){return 0!=z[this.ptr+12>>0]},this.set_rethrown=function(e){e=e?1:0,z[this.ptr+13>>0]=e},this.get_rethrown=function(){return 0!=z[this.ptr+13>>0]},this.init=function(e,t){this.set_type(e),this.set_destructor(t),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var e=V[this.ptr>>2];V[this.ptr>>2]=e+1},this.release_ref=function(){var e=V[this.ptr>>2];return V[this.ptr>>2]=e-1,1===e}}function ce(e){try{return L.grow(e-T.byteLength+65535>>>16),D(L.buffer),1}catch(e){}}re=M?()=>{var e=r.hrtime();return 1e3*e[0]+e[1]/1e6}:()=>performance.now();var le={};function ue(){if(!ue.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:C||"./this.program"};for(var t in le)void 0===le[t]?delete e[t]:e[t]=le[t];var n=[];for(var t in e)n.push(t+"="+e[t]);ue.strings=n}return ue.strings}var de={splitPath:function(e){return/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1)},normalizeArray:function(e,t){for(var n=0,i=e.length-1;i>=0;i--){var r=e[i];"."===r?e.splice(i,1):".."===r?(e.splice(i,1),n++):n&&(e.splice(i,1),n--)}if(t)for(;n;n--)e.unshift("..");return e},normalize:function(e){var t="/"===e.charAt(0),n="/"===e.substr(-1);return(e=de.normalizeArray(e.split("/").filter((function(e){return!!e})),!t).join("/"))||t||(e="."),e&&n&&(e+="/"),(t?"/":"")+e},dirname:function(e){var t=de.splitPath(e),n=t[0],i=t[1];return n||i?(i&&(i=i.substr(0,i.length-1)),n+i):"."},basename:function(e){if("/"===e)return"/";var t=(e=(e=de.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},extname:function(e){return de.splitPath(e)[3]},join:function(){var e=Array.prototype.slice.call(arguments,0);return de.normalize(e.join("/"))},join2:function(e,t){return de.normalize(e+"/"+t)}};function he(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return function(){return crypto.getRandomValues(e),e[0]}}if(M)try{var t=n(782);return function(){return t.randomBytes(1)[0]}}catch(e){}return function(){Q("randomDevice")}}var fe={resolve:function(){for(var e="",t=!1,n=arguments.length-1;n>=-1&&!t;n--){var i=n>=0?arguments[n]:ge.cwd();if("string"!=typeof i)throw new TypeError("Arguments to path.resolve must be strings");if(!i)return"";e=i+"/"+e,t="/"===i.charAt(0)}return(t?"/":"")+(e=de.normalizeArray(e.split("/").filter((function(e){return!!e})),!t).join("/"))||"."},relative:function(e,t){function n(e){for(var t=0;t=0&&""===e[n];n--);return t>n?[]:e.slice(t,n-t+1)}e=fe.resolve(e).substr(1),t=fe.resolve(t).substr(1);for(var i=n(e.split("/")),r=n(t.split("/")),a=Math.min(i.length,r.length),o=a,s=0;s0?n.slice(0,i).toString("utf-8"):null}else"undefined"!=typeof window&&"function"==typeof window.prompt?null!==(t=window.prompt("Input: "))&&(t+="\n"):"function"==typeof readline&&null!==(t=readline())&&(t+="\n");if(!t)return null;e.input=Se(t,!0)}return e.input.shift()},put_char:function(e,t){null===t||10===t?(S(P(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},flush:function(e){e.output&&e.output.length>0&&(S(P(e.output,0)),e.output=[])}},default_tty1_ops:{put_char:function(e,t){null===t||10===t?(w(P(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},flush:function(e){e.output&&e.output.length>0&&(w(P(e.output,0)),e.output=[])}}},me={ops_table:null,mount:function(e){return me.createNode(null,"/",16895,0)},createNode:function(e,t,n,i){if(ge.isBlkdev(n)||ge.isFIFO(n))throw new ge.ErrnoError(63);me.ops_table||(me.ops_table={dir:{node:{getattr:me.node_ops.getattr,setattr:me.node_ops.setattr,lookup:me.node_ops.lookup,mknod:me.node_ops.mknod,rename:me.node_ops.rename,unlink:me.node_ops.unlink,rmdir:me.node_ops.rmdir,readdir:me.node_ops.readdir,symlink:me.node_ops.symlink},stream:{llseek:me.stream_ops.llseek}},file:{node:{getattr:me.node_ops.getattr,setattr:me.node_ops.setattr},stream:{llseek:me.stream_ops.llseek,read:me.stream_ops.read,write:me.stream_ops.write,allocate:me.stream_ops.allocate,mmap:me.stream_ops.mmap,msync:me.stream_ops.msync}},link:{node:{getattr:me.node_ops.getattr,setattr:me.node_ops.setattr,readlink:me.node_ops.readlink},stream:{}},chrdev:{node:{getattr:me.node_ops.getattr,setattr:me.node_ops.setattr},stream:ge.chrdev_stream_ops}});var r=ge.createNode(e,t,n,i);return ge.isDir(r.mode)?(r.node_ops=me.ops_table.dir.node,r.stream_ops=me.ops_table.dir.stream,r.contents={}):ge.isFile(r.mode)?(r.node_ops=me.ops_table.file.node,r.stream_ops=me.ops_table.file.stream,r.usedBytes=0,r.contents=null):ge.isLink(r.mode)?(r.node_ops=me.ops_table.link.node,r.stream_ops=me.ops_table.link.stream):ge.isChrdev(r.mode)&&(r.node_ops=me.ops_table.chrdev.node,r.stream_ops=me.ops_table.chrdev.stream),r.timestamp=Date.now(),e&&(e.contents[t]=r,e.timestamp=r.timestamp),r},getFileDataAsTypedArray:function(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0)},expandFileStorage:function(e,t){var n=e.contents?e.contents.length:0;if(!(n>=t)){t=Math.max(t,n*(n<1048576?2:1.125)>>>0),0!=n&&(t=Math.max(t,256));var i=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(i.subarray(0,e.usedBytes),0)}},resizeFileStorage:function(e,t){if(e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var n=e.contents;e.contents=new Uint8Array(t),n&&e.contents.set(n.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr:function(e){var t={};return t.dev=ge.isChrdev(e.mode)?e.id:1,t.ino=e.id,t.mode=e.mode,t.nlink=1,t.uid=0,t.gid=0,t.rdev=e.rdev,ge.isDir(e.mode)?t.size=4096:ge.isFile(e.mode)?t.size=e.usedBytes:ge.isLink(e.mode)?t.size=e.link.length:t.size=0,t.atime=new Date(e.timestamp),t.mtime=new Date(e.timestamp),t.ctime=new Date(e.timestamp),t.blksize=4096,t.blocks=Math.ceil(t.size/t.blksize),t},setattr:function(e,t){void 0!==t.mode&&(e.mode=t.mode),void 0!==t.timestamp&&(e.timestamp=t.timestamp),void 0!==t.size&&me.resizeFileStorage(e,t.size)},lookup:function(e,t){throw ge.genericErrors[44]},mknod:function(e,t,n,i){return me.createNode(e,t,n,i)},rename:function(e,t,n){if(ge.isDir(e.mode)){var i;try{i=ge.lookupNode(t,n)}catch(e){}if(i)for(var r in i.contents)throw new ge.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=n,t.contents[n]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink:function(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir:function(e,t){var n=ge.lookupNode(e,t);for(var i in n.contents)throw new ge.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir:function(e){var t=[".",".."];for(var n in e.contents)e.contents.hasOwnProperty(n)&&t.push(n);return t},symlink:function(e,t,n){var i=me.createNode(e,t,41471,0);return i.link=n,i},readlink:function(e){if(!ge.isLink(e.mode))throw new ge.ErrnoError(28);return e.link}},stream_ops:{read:function(e,t,n,i,r){var a=e.node.contents;if(r>=e.node.usedBytes)return 0;var o=Math.min(e.node.usedBytes-r,i);if(o>8&&a.subarray)t.set(a.subarray(r,r+o),n);else for(var s=0;s0||i+n{if(!(e=fe.resolve(ge.cwd(),e)))return{path:"",node:null};var n={follow_mount:!0,recurse_count:0};for(var i in n)void 0===t[i]&&(t[i]=n[i]);if(t.recurse_count>8)throw new ge.ErrnoError(32);for(var r=de.normalizeArray(e.split("/").filter((e=>!!e)),!1),a=ge.root,o="/",s=0;s40)throw new ge.ErrnoError(32)}}return{path:o,node:a}},getPath:e=>{for(var t;;){if(ge.isRoot(e)){var n=e.mount.mountpoint;return t?"/"!==n[n.length-1]?n+"/"+t:n+t:n}t=t?e.name+"/"+t:e.name,e=e.parent}},hashName:(e,t)=>{for(var n=0,i=0;i>>0)%ge.nameTable.length},hashAddNode:e=>{var t=ge.hashName(e.parent.id,e.name);e.name_next=ge.nameTable[t],ge.nameTable[t]=e},hashRemoveNode:e=>{var t=ge.hashName(e.parent.id,e.name);if(ge.nameTable[t]===e)ge.nameTable[t]=e.name_next;else for(var n=ge.nameTable[t];n;){if(n.name_next===e){n.name_next=e.name_next;break}n=n.name_next}},lookupNode:(e,t)=>{var n=ge.mayLookup(e);if(n)throw new ge.ErrnoError(n,e);for(var i=ge.hashName(e.id,t),r=ge.nameTable[i];r;r=r.name_next){var a=r.name;if(r.parent.id===e.id&&a===t)return r}return ge.lookup(e,t)},createNode:(e,t,n,i)=>{var r=new ge.FSNode(e,t,n,i);return ge.hashAddNode(r),r},destroyNode:e=>{ge.hashRemoveNode(e)},isRoot:e=>e===e.parent,isMountpoint:e=>!!e.mounted,isFile:e=>32768==(61440&e),isDir:e=>16384==(61440&e),isLink:e=>40960==(61440&e),isChrdev:e=>8192==(61440&e),isBlkdev:e=>24576==(61440&e),isFIFO:e=>4096==(61440&e),isSocket:e=>49152==(49152&e),flagModes:{r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090},modeStringToFlags:e=>{var t=ge.flagModes[e];if(void 0===t)throw new Error("Unknown file open mode: "+e);return t},flagsToPermissionString:e=>{var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},nodePermissions:(e,t)=>ge.ignorePermissions||(!t.includes("r")||292&e.mode)&&(!t.includes("w")||146&e.mode)&&(!t.includes("x")||73&e.mode)?0:2,mayLookup:e=>ge.nodePermissions(e,"x")||(e.node_ops.lookup?0:2),mayCreate:(e,t)=>{try{return ge.lookupNode(e,t),20}catch(e){}return ge.nodePermissions(e,"wx")},mayDelete:(e,t,n)=>{var i;try{i=ge.lookupNode(e,t)}catch(e){return e.errno}var r=ge.nodePermissions(e,"wx");if(r)return r;if(n){if(!ge.isDir(i.mode))return 54;if(ge.isRoot(i)||ge.getPath(i)===ge.cwd())return 10}else if(ge.isDir(i.mode))return 31;return 0},mayOpen:(e,t)=>e?ge.isLink(e.mode)?32:ge.isDir(e.mode)&&("r"!==ge.flagsToPermissionString(t)||512&t)?31:ge.nodePermissions(e,ge.flagsToPermissionString(t)):44,MAX_OPEN_FDS:4096,nextfd:(e=0,t=ge.MAX_OPEN_FDS)=>{for(var n=e;n<=t;n++)if(!ge.streams[n])return n;throw new ge.ErrnoError(33)},getStream:e=>ge.streams[e],createStream:(e,t,n)=>{ge.FSStream||(ge.FSStream=function(){},ge.FSStream.prototype={object:{get:function(){return this.node},set:function(e){this.node=e}},isRead:{get:function(){return 1!=(2097155&this.flags)}},isWrite:{get:function(){return 0!=(2097155&this.flags)}},isAppend:{get:function(){return 1024&this.flags}}});var i=new ge.FSStream;for(var r in e)i[r]=e[r];e=i;var a=ge.nextfd(t,n);return e.fd=a,ge.streams[a]=e,e},closeStream:e=>{ge.streams[e]=null},chrdev_stream_ops:{open:e=>{var t=ge.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek:()=>{throw new ge.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,t)=>e<<8|t,registerDevice:(e,t)=>{ge.devices[e]={stream_ops:t}},getDevice:e=>ge.devices[e],getMounts:e=>{for(var t=[],n=[e];n.length;){var i=n.pop();t.push(i),n.push.apply(n,i.mounts)}return t},syncfs:(e,t)=>{"function"==typeof e&&(t=e,e=!1),ge.syncFSRequests++,ge.syncFSRequests>1&&w("warning: "+ge.syncFSRequests+" FS.syncfs operations in flight at once, probably just doing extra work");var n=ge.getMounts(ge.root.mount),i=0;function r(e){return ge.syncFSRequests--,t(e)}function a(e){if(e)return a.errored?void 0:(a.errored=!0,r(e));++i>=n.length&&r(null)}n.forEach((t=>{if(!t.type.syncfs)return a(null);t.type.syncfs(t,e,a)}))},mount:(e,t,n)=>{var i,r="/"===n,a=!n;if(r&&ge.root)throw new ge.ErrnoError(10);if(!r&&!a){var o=ge.lookupPath(n,{follow_mount:!1});if(n=o.path,i=o.node,ge.isMountpoint(i))throw new ge.ErrnoError(10);if(!ge.isDir(i.mode))throw new ge.ErrnoError(54)}var s={type:e,opts:t,mountpoint:n,mounts:[]},c=e.mount(s);return c.mount=s,s.root=c,r?ge.root=c:i&&(i.mounted=s,i.mount&&i.mount.mounts.push(s)),c},unmount:e=>{var t=ge.lookupPath(e,{follow_mount:!1});if(!ge.isMountpoint(t.node))throw new ge.ErrnoError(28);var n=t.node,i=n.mounted,r=ge.getMounts(i);Object.keys(ge.nameTable).forEach((e=>{for(var t=ge.nameTable[e];t;){var n=t.name_next;r.includes(t.mount)&&ge.destroyNode(t),t=n}})),n.mounted=null;var a=n.mount.mounts.indexOf(i);n.mount.mounts.splice(a,1)},lookup:(e,t)=>e.node_ops.lookup(e,t),mknod:(e,t,n)=>{var i=ge.lookupPath(e,{parent:!0}).node,r=de.basename(e);if(!r||"."===r||".."===r)throw new ge.ErrnoError(28);var a=ge.mayCreate(i,r);if(a)throw new ge.ErrnoError(a);if(!i.node_ops.mknod)throw new ge.ErrnoError(63);return i.node_ops.mknod(i,r,t,n)},create:(e,t)=>(t=void 0!==t?t:438,t&=4095,t|=32768,ge.mknod(e,t,0)),mkdir:(e,t)=>(t=void 0!==t?t:511,t&=1023,t|=16384,ge.mknod(e,t,0)),mkdirTree:(e,t)=>{for(var n=e.split("/"),i="",r=0;r(void 0===n&&(n=t,t=438),t|=8192,ge.mknod(e,t,n)),symlink:(e,t)=>{if(!fe.resolve(e))throw new ge.ErrnoError(44);var n=ge.lookupPath(t,{parent:!0}).node;if(!n)throw new ge.ErrnoError(44);var i=de.basename(t),r=ge.mayCreate(n,i);if(r)throw new ge.ErrnoError(r);if(!n.node_ops.symlink)throw new ge.ErrnoError(63);return n.node_ops.symlink(n,i,e)},rename:(e,t)=>{var n,i,r=de.dirname(e),a=de.dirname(t),o=de.basename(e),s=de.basename(t);if(n=ge.lookupPath(e,{parent:!0}).node,i=ge.lookupPath(t,{parent:!0}).node,!n||!i)throw new ge.ErrnoError(44);if(n.mount!==i.mount)throw new ge.ErrnoError(75);var c,l=ge.lookupNode(n,o),u=fe.relative(e,a);if("."!==u.charAt(0))throw new ge.ErrnoError(28);if("."!==(u=fe.relative(t,r)).charAt(0))throw new ge.ErrnoError(55);try{c=ge.lookupNode(i,s)}catch(e){}if(l!==c){var d=ge.isDir(l.mode),h=ge.mayDelete(n,o,d);if(h)throw new ge.ErrnoError(h);if(h=c?ge.mayDelete(i,s,d):ge.mayCreate(i,s))throw new ge.ErrnoError(h);if(!n.node_ops.rename)throw new ge.ErrnoError(63);if(ge.isMountpoint(l)||c&&ge.isMountpoint(c))throw new ge.ErrnoError(10);if(i!==n&&(h=ge.nodePermissions(n,"w")))throw new ge.ErrnoError(h);ge.hashRemoveNode(l);try{n.node_ops.rename(l,i,s)}catch(e){throw e}finally{ge.hashAddNode(l)}}},rmdir:e=>{var t=ge.lookupPath(e,{parent:!0}).node,n=de.basename(e),i=ge.lookupNode(t,n),r=ge.mayDelete(t,n,!0);if(r)throw new ge.ErrnoError(r);if(!t.node_ops.rmdir)throw new ge.ErrnoError(63);if(ge.isMountpoint(i))throw new ge.ErrnoError(10);t.node_ops.rmdir(t,n),ge.destroyNode(i)},readdir:e=>{var t=ge.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new ge.ErrnoError(54);return t.node_ops.readdir(t)},unlink:e=>{var t=ge.lookupPath(e,{parent:!0}).node;if(!t)throw new ge.ErrnoError(44);var n=de.basename(e),i=ge.lookupNode(t,n),r=ge.mayDelete(t,n,!1);if(r)throw new ge.ErrnoError(r);if(!t.node_ops.unlink)throw new ge.ErrnoError(63);if(ge.isMountpoint(i))throw new ge.ErrnoError(10);t.node_ops.unlink(t,n),ge.destroyNode(i)},readlink:e=>{var t=ge.lookupPath(e).node;if(!t)throw new ge.ErrnoError(44);if(!t.node_ops.readlink)throw new ge.ErrnoError(28);return fe.resolve(ge.getPath(t.parent),t.node_ops.readlink(t))},stat:(e,t)=>{var n=ge.lookupPath(e,{follow:!t}).node;if(!n)throw new ge.ErrnoError(44);if(!n.node_ops.getattr)throw new ge.ErrnoError(63);return n.node_ops.getattr(n)},lstat:e=>ge.stat(e,!0),chmod:(e,t,n)=>{var i;if(!(i="string"==typeof e?ge.lookupPath(e,{follow:!n}).node:e).node_ops.setattr)throw new ge.ErrnoError(63);i.node_ops.setattr(i,{mode:4095&t|-4096&i.mode,timestamp:Date.now()})},lchmod:(e,t)=>{ge.chmod(e,t,!0)},fchmod:(e,t)=>{var n=ge.getStream(e);if(!n)throw new ge.ErrnoError(8);ge.chmod(n.node,t)},chown:(e,t,n,i)=>{var r;if(!(r="string"==typeof e?ge.lookupPath(e,{follow:!i}).node:e).node_ops.setattr)throw new ge.ErrnoError(63);r.node_ops.setattr(r,{timestamp:Date.now()})},lchown:(e,t,n)=>{ge.chown(e,t,n,!0)},fchown:(e,t,n)=>{var i=ge.getStream(e);if(!i)throw new ge.ErrnoError(8);ge.chown(i.node,t,n)},truncate:(e,t)=>{if(t<0)throw new ge.ErrnoError(28);var n;if(!(n="string"==typeof e?ge.lookupPath(e,{follow:!0}).node:e).node_ops.setattr)throw new ge.ErrnoError(63);if(ge.isDir(n.mode))throw new ge.ErrnoError(31);if(!ge.isFile(n.mode))throw new ge.ErrnoError(28);var i=ge.nodePermissions(n,"w");if(i)throw new ge.ErrnoError(i);n.node_ops.setattr(n,{size:t,timestamp:Date.now()})},ftruncate:(e,t)=>{var n=ge.getStream(e);if(!n)throw new ge.ErrnoError(8);if(0==(2097155&n.flags))throw new ge.ErrnoError(28);ge.truncate(n.node,t)},utime:(e,t,n)=>{var i=ge.lookupPath(e,{follow:!0}).node;i.node_ops.setattr(i,{timestamp:Math.max(t,n)})},open:(e,t,n,i,r)=>{if(""===e)throw new ge.ErrnoError(44);var a;if(n=void 0===n?438:n,n=64&(t="string"==typeof t?ge.modeStringToFlags(t):t)?4095&n|32768:0,"object"==typeof e)a=e;else{e=de.normalize(e);try{a=ge.lookupPath(e,{follow:!(131072&t)}).node}catch(e){}}var o=!1;if(64&t)if(a){if(128&t)throw new ge.ErrnoError(20)}else a=ge.mknod(e,n,0),o=!0;if(!a)throw new ge.ErrnoError(44);if(ge.isChrdev(a.mode)&&(t&=-513),65536&t&&!ge.isDir(a.mode))throw new ge.ErrnoError(54);if(!o){var c=ge.mayOpen(a,t);if(c)throw new ge.ErrnoError(c)}512&t&&ge.truncate(a,0),t&=-131713;var l=ge.createStream({node:a,path:ge.getPath(a),flags:t,seekable:!0,position:0,stream_ops:a.stream_ops,ungotten:[],error:!1},i,r);return l.stream_ops.open&&l.stream_ops.open(l),!s.logReadFiles||1&t||(ge.readFiles||(ge.readFiles={}),e in ge.readFiles||(ge.readFiles[e]=1)),l},close:e=>{if(ge.isClosed(e))throw new ge.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(e){throw e}finally{ge.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek:(e,t,n)=>{if(ge.isClosed(e))throw new ge.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new ge.ErrnoError(70);if(0!=n&&1!=n&&2!=n)throw new ge.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,n),e.ungotten=[],e.position},read:(e,t,n,i,r)=>{if(i<0||r<0)throw new ge.ErrnoError(28);if(ge.isClosed(e))throw new ge.ErrnoError(8);if(1==(2097155&e.flags))throw new ge.ErrnoError(8);if(ge.isDir(e.node.mode))throw new ge.ErrnoError(31);if(!e.stream_ops.read)throw new ge.ErrnoError(28);var a=void 0!==r;if(a){if(!e.seekable)throw new ge.ErrnoError(70)}else r=e.position;var o=e.stream_ops.read(e,t,n,i,r);return a||(e.position+=o),o},write:(e,t,n,i,r,a)=>{if(i<0||r<0)throw new ge.ErrnoError(28);if(ge.isClosed(e))throw new ge.ErrnoError(8);if(0==(2097155&e.flags))throw new ge.ErrnoError(8);if(ge.isDir(e.node.mode))throw new ge.ErrnoError(31);if(!e.stream_ops.write)throw new ge.ErrnoError(28);e.seekable&&1024&e.flags&&ge.llseek(e,0,2);var o=void 0!==r;if(o){if(!e.seekable)throw new ge.ErrnoError(70)}else r=e.position;var s=e.stream_ops.write(e,t,n,i,r,a);return o||(e.position+=s),s},allocate:(e,t,n)=>{if(ge.isClosed(e))throw new ge.ErrnoError(8);if(t<0||n<=0)throw new ge.ErrnoError(28);if(0==(2097155&e.flags))throw new ge.ErrnoError(8);if(!ge.isFile(e.node.mode)&&!ge.isDir(e.node.mode))throw new ge.ErrnoError(43);if(!e.stream_ops.allocate)throw new ge.ErrnoError(138);e.stream_ops.allocate(e,t,n)},mmap:(e,t,n,i,r,a)=>{if(0!=(2&r)&&0==(2&a)&&2!=(2097155&e.flags))throw new ge.ErrnoError(2);if(1==(2097155&e.flags))throw new ge.ErrnoError(2);if(!e.stream_ops.mmap)throw new ge.ErrnoError(43);return e.stream_ops.mmap(e,t,n,i,r,a)},msync:(e,t,n,i,r)=>e&&e.stream_ops.msync?e.stream_ops.msync(e,t,n,i,r):0,munmap:e=>0,ioctl:(e,t,n)=>{if(!e.stream_ops.ioctl)throw new ge.ErrnoError(59);return e.stream_ops.ioctl(e,t,n)},readFile:(e,t={})=>{if(t.flags=t.flags||0,t.encoding=t.encoding||"binary","utf8"!==t.encoding&&"binary"!==t.encoding)throw new Error('Invalid encoding type "'+t.encoding+'"');var n,i=ge.open(e,t.flags),r=ge.stat(e).size,a=new Uint8Array(r);return ge.read(i,a,0,r,0),"utf8"===t.encoding?n=P(a,0):"binary"===t.encoding&&(n=a),ge.close(i),n},writeFile:(e,t,n={})=>{n.flags=n.flags||577;var i=ge.open(e,n.flags,n.mode);if("string"==typeof t){var r=new Uint8Array(N(t)+1),a=k(t,r,0,r.length);ge.write(i,r,0,a,void 0,n.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");ge.write(i,t,0,t.byteLength,void 0,n.canOwn)}ge.close(i)},cwd:()=>ge.currentPath,chdir:e=>{var t=ge.lookupPath(e,{follow:!0});if(null===t.node)throw new ge.ErrnoError(44);if(!ge.isDir(t.node.mode))throw new ge.ErrnoError(54);var n=ge.nodePermissions(t.node,"x");if(n)throw new ge.ErrnoError(n);ge.currentPath=t.path},createDefaultDirectories:()=>{ge.mkdir("/tmp"),ge.mkdir("/home"),ge.mkdir("/home/web_user")},createDefaultDevices:()=>{ge.mkdir("/dev"),ge.registerDevice(ge.makedev(1,3),{read:()=>0,write:(e,t,n,i,r)=>i}),ge.mkdev("/dev/null",ge.makedev(1,3)),pe.register(ge.makedev(5,0),pe.default_tty_ops),pe.register(ge.makedev(6,0),pe.default_tty1_ops),ge.mkdev("/dev/tty",ge.makedev(5,0)),ge.mkdev("/dev/tty1",ge.makedev(6,0));var e=he();ge.createDevice("/dev","random",e),ge.createDevice("/dev","urandom",e),ge.mkdir("/dev/shm"),ge.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{ge.mkdir("/proc");var e=ge.mkdir("/proc/self");ge.mkdir("/proc/self/fd"),ge.mount({mount:()=>{var t=ge.createNode(e,"fd",16895,73);return t.node_ops={lookup:(e,t)=>{var n=+t,i=ge.getStream(n);if(!i)throw new ge.ErrnoError(8);var r={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>i.path}};return r.parent=r,r}},t}},{},"/proc/self/fd")},createStandardStreams:()=>{s.stdin?ge.createDevice("/dev","stdin",s.stdin):ge.symlink("/dev/tty","/dev/stdin"),s.stdout?ge.createDevice("/dev","stdout",null,s.stdout):ge.symlink("/dev/tty","/dev/stdout"),s.stderr?ge.createDevice("/dev","stderr",null,s.stderr):ge.symlink("/dev/tty1","/dev/stderr"),ge.open("/dev/stdin",0),ge.open("/dev/stdout",1),ge.open("/dev/stderr",1)},ensureErrnoError:()=>{ge.ErrnoError||(ge.ErrnoError=function(e,t){this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},ge.ErrnoError.prototype=new Error,ge.ErrnoError.prototype.constructor=ge.ErrnoError,[44].forEach((e=>{ge.genericErrors[e]=new ge.ErrnoError(e),ge.genericErrors[e].stack=""})))},staticInit:()=>{ge.ensureErrnoError(),ge.nameTable=new Array(4096),ge.mount(me,{},"/"),ge.createDefaultDirectories(),ge.createDefaultDevices(),ge.createSpecialDirectories(),ge.filesystems={MEMFS:me}},init:(e,t,n)=>{ge.init.initialized=!0,ge.ensureErrnoError(),s.stdin=e||s.stdin,s.stdout=t||s.stdout,s.stderr=n||s.stderr,ge.createStandardStreams()},quit:()=>{ge.init.initialized=!1;for(var e=0;e{var n=0;return e&&(n|=365),t&&(n|=146),n},findObject:(e,t)=>{var n=ge.analyzePath(e,t);return n.exists?n.object:null},analyzePath:(e,t)=>{try{e=(i=ge.lookupPath(e,{follow:!t})).path}catch(e){}var n={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var i=ge.lookupPath(e,{parent:!0});n.parentExists=!0,n.parentPath=i.path,n.parentObject=i.node,n.name=de.basename(e),i=ge.lookupPath(e,{follow:!t}),n.exists=!0,n.path=i.path,n.object=i.node,n.name=i.node.name,n.isRoot="/"===i.path}catch(e){n.error=e.errno}return n},createPath:(e,t,n,i)=>{e="string"==typeof e?e:ge.getPath(e);for(var r=t.split("/").reverse();r.length;){var a=r.pop();if(a){var o=de.join2(e,a);try{ge.mkdir(o)}catch(e){}e=o}}return o},createFile:(e,t,n,i,r)=>{var a=de.join2("string"==typeof e?e:ge.getPath(e),t),o=ge.getMode(i,r);return ge.create(a,o)},createDataFile:(e,t,n,i,r,a)=>{var o=t;e&&(e="string"==typeof e?e:ge.getPath(e),o=t?de.join2(e,t):e);var s=ge.getMode(i,r),c=ge.create(o,s);if(n){if("string"==typeof n){for(var l=new Array(n.length),u=0,d=n.length;u{var r=de.join2("string"==typeof e?e:ge.getPath(e),t),a=ge.getMode(!!n,!!i);ge.createDevice.major||(ge.createDevice.major=64);var o=ge.makedev(ge.createDevice.major++,0);return ge.registerDevice(o,{open:e=>{e.seekable=!1},close:e=>{i&&i.buffer&&i.buffer.length&&i(10)},read:(e,t,i,r,a)=>{for(var o=0,s=0;s{for(var o=0;o{if(e.isDevice||e.isFolder||e.link||e.contents)return!0;if("undefined"!=typeof XMLHttpRequest)throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");if(!l)throw new Error("Cannot load without read() or XMLHttpRequest.");try{e.contents=Se(l(e.url),!0),e.usedBytes=e.contents.length}catch(e){throw new ge.ErrnoError(29)}},createLazyFile:(e,t,n,i,r)=>{function a(){this.lengthKnown=!1,this.chunks=[]}if(a.prototype.get=function(e){if(!(e>this.length-1||e<0)){var t=e%this.chunkSize,n=e/this.chunkSize|0;return this.getter(n)[t]}},a.prototype.setDataGetter=function(e){this.getter=e},a.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",n,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+n+". Status: "+e.status);var t,i=Number(e.getResponseHeader("Content-length")),r=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t,a=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t,o=1048576;r||(o=i);var s=this;s.setDataGetter((e=>{var t=e*o,r=(e+1)*o-1;if(r=Math.min(r,i-1),void 0===s.chunks[e]&&(s.chunks[e]=((e,t)=>{if(e>t)throw new Error("invalid range ("+e+", "+t+") or no bytes requested!");if(t>i-1)throw new Error("only "+i+" bytes available! programmer error!");var r=new XMLHttpRequest;if(r.open("GET",n,!1),i!==o&&r.setRequestHeader("Range","bytes="+e+"-"+t),"undefined"!=typeof Uint8Array&&(r.responseType="arraybuffer"),r.overrideMimeType&&r.overrideMimeType("text/plain; charset=x-user-defined"),r.send(null),!(r.status>=200&&r.status<300||304===r.status))throw new Error("Couldn't load "+n+". Status: "+r.status);return void 0!==r.response?new Uint8Array(r.response||[]):Se(r.responseText||"",!0)})(t,r)),void 0===s.chunks[e])throw new Error("doXHR failed!");return s.chunks[e]})),!a&&i||(o=i=1,i=this.getter(0).length,o=i,S("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=i,this._chunkSize=o,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!b)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var o=new a;Object.defineProperties(o,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var s={isDevice:!1,contents:o}}else s={isDevice:!1,url:n};var c=ge.createFile(e,t,s,i,r);s.contents?c.contents=s.contents:s.url&&(c.contents=null,c.url=s.url),Object.defineProperties(c,{usedBytes:{get:function(){return this.contents.length}}});var l={};return Object.keys(c.stream_ops).forEach((e=>{var t=c.stream_ops[e];l[e]=function(){return ge.forceLoadFile(c),t.apply(null,arguments)}})),l.read=(e,t,n,i,r)=>{ge.forceLoadFile(c);var a=e.node.contents;if(r>=a.length)return 0;var o=Math.min(a.length-r,i);if(a.slice)for(var s=0;s{var d=t?fe.resolve(de.join2(e,t)):e;function h(n){function u(n){l&&l(),s||ge.createDataFile(e,t,n,i,r,c),a&&a(),Z()}Browser.handledByPreloadPlugin(n,d,u,(()=>{o&&o(),Z()}))||u(n)}K(),"string"==typeof n?function(e,t,n,i){var r="al "+e;u(e,(function(t){t||Q('Loading data file "'+e+'" failed (no arrayBuffer).'),(e=>{h(e)})(new Uint8Array(t)),r&&Z()}),(function(t){if(!n)throw'Loading data file "'+e+'" failed.';n()})),r&&K()}(n,0,o):h(n)},indexedDB:()=>window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB,DB_NAME:()=>"EM_FS_"+window.location.pathname,DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:(e,t,n)=>{t=t||(()=>{}),n=n||(()=>{});var i=ge.indexedDB();try{var r=i.open(ge.DB_NAME(),ge.DB_VERSION)}catch(e){return n(e)}r.onupgradeneeded=()=>{S("creating db"),r.result.createObjectStore(ge.DB_STORE_NAME)},r.onsuccess=()=>{var i=r.result.transaction([ge.DB_STORE_NAME],"readwrite"),a=i.objectStore(ge.DB_STORE_NAME),o=0,s=0,c=e.length;function l(){0==s?t():n()}e.forEach((e=>{var t=a.put(ge.analyzePath(e).object.contents,e);t.onsuccess=()=>{++o+s==c&&l()},t.onerror=()=>{s++,o+s==c&&l()}})),i.onerror=n},r.onerror=n},loadFilesFromDB:(e,t,n)=>{t=t||(()=>{}),n=n||(()=>{});var i=ge.indexedDB();try{var r=i.open(ge.DB_NAME(),ge.DB_VERSION)}catch(e){return n(e)}r.onupgradeneeded=n,r.onsuccess=()=>{var i=r.result;try{var a=i.transaction([ge.DB_STORE_NAME],"readonly")}catch(e){return void n(e)}var o=a.objectStore(ge.DB_STORE_NAME),s=0,c=0,l=e.length;function u(){0==c?t():n()}e.forEach((e=>{var t=o.get(e);t.onsuccess=()=>{ge.analyzePath(e).exists&&ge.unlink(e),ge.createDataFile(de.dirname(e),de.basename(e),t.result,!0,!0,!0),++s+c==l&&u()},t.onerror=()=>{c++,s+c==l&&u()}})),a.onerror=n},r.onerror=n}},Ce={mappings:{},DEFAULT_POLLMASK:5,calculateAt:function(e,t,n){if("/"===t[0])return t;var i;if(-100===e)i=ge.cwd();else{var r=ge.getStream(e);if(!r)throw new ge.ErrnoError(8);i=r.path}if(0==t.length){if(!n)throw new ge.ErrnoError(44);return i}return de.join2(i,t)},doStat:function(e,t,n){try{var i=e(t)}catch(e){if(e&&e.node&&de.normalize(t)!==de.normalize(ge.getPath(e.node)))return-54;throw e}return V[n>>2]=i.dev,V[n+4>>2]=0,V[n+8>>2]=i.ino,V[n+12>>2]=i.mode,V[n+16>>2]=i.nlink,V[n+20>>2]=i.uid,V[n+24>>2]=i.gid,V[n+28>>2]=i.rdev,V[n+32>>2]=0,X=[i.size>>>0,(q=i.size,+Math.abs(q)>=1?q>0?(0|Math.min(+Math.floor(q/4294967296),4294967295))>>>0:~~+Math.ceil((q-+(~~q>>>0))/4294967296)>>>0:0)],V[n+40>>2]=X[0],V[n+44>>2]=X[1],V[n+48>>2]=4096,V[n+52>>2]=i.blocks,V[n+56>>2]=i.atime.getTime()/1e3|0,V[n+60>>2]=0,V[n+64>>2]=i.mtime.getTime()/1e3|0,V[n+68>>2]=0,V[n+72>>2]=i.ctime.getTime()/1e3|0,V[n+76>>2]=0,X=[i.ino>>>0,(q=i.ino,+Math.abs(q)>=1?q>0?(0|Math.min(+Math.floor(q/4294967296),4294967295))>>>0:~~+Math.ceil((q-+(~~q>>>0))/4294967296)>>>0:0)],V[n+80>>2]=X[0],V[n+84>>2]=X[1],0},doMsync:function(e,t,n,i,r){var a=A.slice(e,e+n);ge.msync(t,a,r,n,i)},doMkdir:function(e,t){return"/"===(e=de.normalize(e))[e.length-1]&&(e=e.substr(0,e.length-1)),ge.mkdir(e,t,0),0},doMknod:function(e,t,n){switch(61440&t){case 32768:case 8192:case 24576:case 4096:case 49152:break;default:return-28}return ge.mknod(e,t,n),0},doReadlink:function(e,t,n){if(n<=0)return-28;var i=ge.readlink(e),r=Math.min(n,N(i)),a=z[t+r];return k(i,A,t,n+1),z[t+r]=a,r},doAccess:function(e,t){if(-8&t)return-28;var n=ge.lookupPath(e,{follow:!0}).node;if(!n)return-44;var i="";return 4&t&&(i+="r"),2&t&&(i+="w"),1&t&&(i+="x"),i&&ge.nodePermissions(n,i)?-2:0},doDup:function(e,t,n){var i=ge.getStream(n);return i&&ge.close(i),ge.open(e,t,0,n,n).fd},doReadv:function(e,t,n,i){for(var r=0,a=0;a>2],s=V[t+(8*a+4)>>2],c=ge.read(e,z,o,s,i);if(c<0)return-1;if(r+=c,c>2],s=V[t+(8*a+4)>>2],c=ge.write(e,z,o,s,i);if(c<0)return-1;r+=c}return r},varargs:void 0,get:function(){return Ce.varargs+=4,V[Ce.varargs-4>>2]},getStr:function(e){return I(e)},getStreamFromFD:function(e){var t=ge.getStream(e);if(!t)throw new ge.ErrnoError(8);return t},get64:function(e,t){return e}};function ve(e){return e%4==0&&(e%100!=0||e%400==0)}function ye(e,t){for(var n=0,i=0;i<=t;n+=e[i++]);return n}var be=[31,29,31,30,31,30,31,31,30,31,30,31],Me=[31,28,31,30,31,30,31,31,30,31,30,31];function xe(e,t){for(var n=new Date(e.getTime());t>0;){var i=ve(n.getFullYear()),r=n.getMonth(),a=(i?be:Me)[r];if(!(t>a-n.getDate()))return n.setDate(n.getDate()+t),n;t-=a-n.getDate()+1,n.setDate(1),r<11?n.setMonth(r+1):(n.setMonth(0),n.setFullYear(n.getFullYear()+1))}return n}var _e=function(e,t,n,i){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=ge.nextInode++,this.name=t,this.mode=n,this.node_ops={},this.stream_ops={},this.rdev=i};function Se(e,t,n){var i=n>0?n:N(e)+1,r=new Array(i),a=k(e,r,0,r.length);return t&&(r.length=a),r}Object.defineProperties(_e.prototype,{read:{get:function(){return 365==(365&this.mode)},set:function(e){e?this.mode|=365:this.mode&=-366}},write:{get:function(){return 146==(146&this.mode)},set:function(e){e?this.mode|=146:this.mode&=-147}},isFolder:{get:function(){return ge.isDir(this.mode)}},isDevice:{get:function(){return ge.isChrdev(this.mode)}}}),ge.FSNode=_e,ge.staticInit();var we,Le={d:function(e){return Ee(e+16)+16},c:function(e,t,n){throw new se(e).init(t,n),e},f:function(e,t){Q("To use dlopen, you need to use Emscripten's linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking")},i:function(e,t){Q("To use dlopen, you need to use Emscripten's linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking")},a:function(){Q("")},b:function(e,t){var n;if(0===e)n=Date.now();else{if(1!==e&&4!==e)return V[Te()>>2]=28,-1;n=re()}return V[t>>2]=n/1e3|0,V[t+4>>2]=n%1e3*1e3*1e3|0,0},o:function(){return 2147483648},g:re,h:function(e,t,n){A.copyWithin(e,t,t+n)},n:function(e){var t,n=A.length,i=2147483648;if((e>>>=0)>i)return!1;for(var r=1;r<=4;r*=2){var a=n*(1+.2/r);if(a=Math.min(a,e+100663296),ce(Math.min(i,((t=Math.max(e,a))%65536>0&&(t+=65536-t%65536),t))))return!0}return!1},p:function(e,t){var n=0;return ue().forEach((function(i,r){var a=t+n;V[e+4*r>>2]=a,function(e,t,n){for(var i=0;i>0]=e.charCodeAt(i);z[t>>0]=0}(i,a),n+=i.length+1})),0},q:function(e,t){var n=ue();V[e>>2]=n.length;var i=0;return n.forEach((function(e){i+=e.length+1})),V[t>>2]=i,0},s:function(e){!function(e,t){var n;W(),n=e,W()||(s.onExit&&s.onExit(n),H=!0),v(n,new Ae(n))}(e)},j:function(e){try{var t=Ce.getStreamFromFD(e);return ge.close(t),0}catch(e){if(void 0===ge||!(e instanceof ge.ErrnoError))throw e;return e.errno}},r:function(e,t,n,i){try{var r=Ce.getStreamFromFD(e),a=Ce.doReadv(r,t,n);return V[i>>2]=a,0}catch(e){if(void 0===ge||!(e instanceof ge.ErrnoError))throw e;return e.errno}},k:function(e,t,n,i,r){try{var a=Ce.getStreamFromFD(e),o=4294967296*n+(t>>>0),s=9007199254740992;return o<=-s||o>=s?-61:(ge.llseek(a,o,i),X=[a.position>>>0,(q=a.position,+Math.abs(q)>=1?q>0?(0|Math.min(+Math.floor(q/4294967296),4294967295))>>>0:~~+Math.ceil((q-+(~~q>>>0))/4294967296)>>>0:0)],V[r>>2]=X[0],V[r+4>>2]=X[1],a.getdents&&0===o&&0===i&&(a.getdents=null),0)}catch(e){if(void 0===ge||!(e instanceof ge.ErrnoError))throw e;return e.errno}},e:function(e,t,n,i){try{var r=Ce.getStreamFromFD(e),a=Ce.doWritev(r,t,n);return V[i>>2]=a,0}catch(e){if(void 0===ge||!(e instanceof ge.ErrnoError))throw e;return e.errno}},l:function e(t,n){e.randomDevice||(e.randomDevice=he());for(var i=0;i>0]=e.randomDevice();return 0},m:function(e,t,n,i){return function(e,t,n,i){var r=V[i+40>>2],a={tm_sec:V[i>>2],tm_min:V[i+4>>2],tm_hour:V[i+8>>2],tm_mday:V[i+12>>2],tm_mon:V[i+16>>2],tm_year:V[i+20>>2],tm_wday:V[i+24>>2],tm_yday:V[i+28>>2],tm_isdst:V[i+32>>2],tm_gmtoff:V[i+36>>2],tm_zone:r?I(r):""},o=I(n),s={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var c in s)o=o.replace(new RegExp(c,"g"),s[c]);var l=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],u=["January","February","March","April","May","June","July","August","September","October","November","December"];function d(e,t,n){for(var i="number"==typeof e?e.toString():e||"";i.length0?1:0}var i;return 0===(i=n(e.getFullYear()-t.getFullYear()))&&0===(i=n(e.getMonth()-t.getMonth()))&&(i=n(e.getDate()-t.getDate())),i}function p(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function m(e){var t=xe(new Date(e.tm_year+1900,0,1),e.tm_yday),n=new Date(t.getFullYear(),0,4),i=new Date(t.getFullYear()+1,0,4),r=p(n),a=p(i);return f(r,t)<=0?f(a,t)<=0?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var g={"%a":function(e){return l[e.tm_wday].substring(0,3)},"%A":function(e){return l[e.tm_wday]},"%b":function(e){return u[e.tm_mon].substring(0,3)},"%B":function(e){return u[e.tm_mon]},"%C":function(e){return h((e.tm_year+1900)/100|0,2)},"%d":function(e){return h(e.tm_mday,2)},"%e":function(e){return d(e.tm_mday,2," ")},"%g":function(e){return m(e).toString().substring(2)},"%G":function(e){return m(e)},"%H":function(e){return h(e.tm_hour,2)},"%I":function(e){var t=e.tm_hour;return 0==t?t=12:t>12&&(t-=12),h(t,2)},"%j":function(e){return h(e.tm_mday+ye(ve(e.tm_year+1900)?be:Me,e.tm_mon-1),3)},"%m":function(e){return h(e.tm_mon+1,2)},"%M":function(e){return h(e.tm_min,2)},"%n":function(){return"\n"},"%p":function(e){return e.tm_hour>=0&&e.tm_hour<12?"AM":"PM"},"%S":function(e){return h(e.tm_sec,2)},"%t":function(){return"\t"},"%u":function(e){return e.tm_wday||7},"%U":function(e){var t=new Date(e.tm_year+1900,0,1),n=0===t.getDay()?t:xe(t,7-t.getDay()),i=new Date(e.tm_year+1900,e.tm_mon,e.tm_mday);if(f(n,i)<0){var r=ye(ve(i.getFullYear())?be:Me,i.getMonth()-1)-31,a=31-n.getDate()+r+i.getDate();return h(Math.ceil(a/7),2)}return 0===f(n,t)?"01":"00"},"%V":function(e){var t,n=new Date(e.tm_year+1900,0,4),i=new Date(e.tm_year+1901,0,4),r=p(n),a=p(i),o=xe(new Date(e.tm_year+1900,0,1),e.tm_yday);return f(o,r)<0?"53":f(a,o)<=0?"01":(t=r.getFullYear()=0;return t=(t=Math.abs(t)/60)/60*100+t%60,(n?"+":"-")+String("0000"+t).slice(-4)},"%Z":function(e){return e.tm_zone},"%%":function(){return"%"}};for(var c in g)o.includes(c)&&(o=o.replace(new RegExp(c,"g"),g[c](a)));var C=Se(o,!1);return C.length>t?0:(function(e,t){z.set(e,t)}(C,e),C.length-1)}(e,t,n,i)}},Ee=(function(){var e={a:Le};function t(e,t){var n,i=e.exports;s.asm=i,D((L=s.asm.t).buffer),O=s.asm.H,n=s.asm.u,F.unshift(n),Z()}function n(e){t(e.instance)}function i(t){return function(){if(!_&&(y||b)){if("function"==typeof fetch&&!te(G))return fetch(G,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+G+"'";return e.arrayBuffer()})).catch((function(){return ne(G)}));if(u)return new Promise((function(e,t){u(G,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return ne(G)}))}().then((function(t){return WebAssembly.instantiate(t,e)})).then((function(e){return e})).then(t,(function(e){w("failed to asynchronously prepare wasm: "+e),Q(e)}))}if(K(),s.instantiateWasm)try{return s.instantiateWasm(e,t)}catch(e){return w("Module.instantiateWasm callback failed with error: "+e),!1}(_||"function"!=typeof WebAssembly.instantiateStreaming||ee(G)||te(G)||"function"!=typeof fetch?i(n):fetch(G,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,e).then(n,(function(e){return w("wasm streaming compile failed: "+e),w("falling back to ArrayBuffer instantiation"),i(n)}))}))).catch(o)}(),s.___wasm_call_ctors=function(){return(s.___wasm_call_ctors=s.asm.u).apply(null,arguments)},s._initPoseDetectorModelBuffer=function(){return(s._initPoseDetectorModelBuffer=s.asm.v).apply(null,arguments)},s._getPoseDetectorModelBufferAddress=function(){return(s._getPoseDetectorModelBufferAddress=s.asm.w).apply(null,arguments)},s._loadPoseDetectorModel=function(){return(s._loadPoseDetectorModel=s.asm.x).apply(null,arguments)},s._initPoseLandmarkModelBuffer=function(){return(s._initPoseLandmarkModelBuffer=s.asm.y).apply(null,arguments)},s._getPoseLandmarkModelBufferAddress=function(){return(s._getPoseLandmarkModelBufferAddress=s.asm.z).apply(null,arguments)},s._loadPoseLandmarkModel=function(){return(s._loadPoseLandmarkModel=s.asm.A).apply(null,arguments)},s._initPoseInputBuffer=function(){return(s._initPoseInputBuffer=s.asm.B).apply(null,arguments)},s._getPoseInputBufferAddress=function(){return(s._getPoseInputBufferAddress=s.asm.C).apply(null,arguments)},s._getPoseOutputBufferAddress=function(){return(s._getPoseOutputBufferAddress=s.asm.D).apply(null,arguments)},s._getPoseTemporaryBufferAddress=function(){return(s._getPoseTemporaryBufferAddress=s.asm.E).apply(null,arguments)},s._execPose=function(){return(s._execPose=s.asm.F).apply(null,arguments)},s._set_pose_calculate_mode=function(){return(s._set_pose_calculate_mode=s.asm.G).apply(null,arguments)},s._initPalmDetectorModelBuffer=function(){return(s._initPalmDetectorModelBuffer=s.asm.I).apply(null,arguments)},s._getPalmDetectorModelBufferAddress=function(){return(s._getPalmDetectorModelBufferAddress=s.asm.J).apply(null,arguments)},s._loadPalmDetectorModel=function(){return(s._loadPalmDetectorModel=s.asm.K).apply(null,arguments)},s._initHandLandmarkModelBuffer=function(){return(s._initHandLandmarkModelBuffer=s.asm.L).apply(null,arguments)},s._getHandLandmarkModelBufferAddress=function(){return(s._getHandLandmarkModelBufferAddress=s.asm.M).apply(null,arguments)},s._loadHandLandmarkModel=function(){return(s._loadHandLandmarkModel=s.asm.N).apply(null,arguments)},s._initHandInputBuffer=function(){return(s._initHandInputBuffer=s.asm.O).apply(null,arguments)},s._getHandInputBufferAddress=function(){return(s._getHandInputBufferAddress=s.asm.P).apply(null,arguments)},s._getHandOutputBufferAddress=function(){return(s._getHandOutputBufferAddress=s.asm.Q).apply(null,arguments)},s._getHandTemporaryBufferAddress=function(){return(s._getHandTemporaryBufferAddress=s.asm.R).apply(null,arguments)},s._execHand=function(){return(s._execHand=s.asm.S).apply(null,arguments)},s._initFaceDetectorModelBuffer=function(){return(s._initFaceDetectorModelBuffer=s.asm.T).apply(null,arguments)},s._getFaceDetectorModelBufferAddress=function(){return(s._getFaceDetectorModelBufferAddress=s.asm.U).apply(null,arguments)},s._loadFaceDetectorModel=function(){return(s._loadFaceDetectorModel=s.asm.V).apply(null,arguments)},s._initFaceLandmarkModelBuffer=function(){return(s._initFaceLandmarkModelBuffer=s.asm.W).apply(null,arguments)},s._getFaceLandmarkModelBufferAddress=function(){return(s._getFaceLandmarkModelBufferAddress=s.asm.X).apply(null,arguments)},s._loadFaceLandmarkModel=function(){return(s._loadFaceLandmarkModel=s.asm.Y).apply(null,arguments)},s._initFaceInputBuffer=function(){return(s._initFaceInputBuffer=s.asm.Z).apply(null,arguments)},s._getFaceInputBufferAddress=function(){return(s._getFaceInputBufferAddress=s.asm._).apply(null,arguments)},s._getFaceOutputBufferAddress=function(){return(s._getFaceOutputBufferAddress=s.asm.$).apply(null,arguments)},s._getFaceTemporaryBufferAddress=function(){return(s._getFaceTemporaryBufferAddress=s.asm.aa).apply(null,arguments)},s._execFace=function(){return(s._execFace=s.asm.ba).apply(null,arguments)},s._malloc=function(){return(Ee=s._malloc=s.asm.ca).apply(null,arguments)}),Te=s.___errno_location=function(){return(Te=s.___errno_location=s.asm.da).apply(null,arguments)},ze=s._memalign=function(){return(ze=s._memalign=s.asm.ea).apply(null,arguments)};function Ae(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function Ve(e){function n(){we||(we=!0,s.calledRun=!0,H||(s.noFSInit||ge.init.initialized||ge.init(),ge.ignorePermissions=!1,pe.init(),ie(F),t(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),function(){if(s.postRun)for("function"==typeof s.postRun&&(s.postRun=[s.postRun]);s.postRun.length;)e=s.postRun.shift(),U.unshift(e);var e;ie(U)}()))}e=e||g,Y>0||(function(){if(s.preRun)for("function"==typeof s.preRun&&(s.preRun=[s.preRun]);s.preRun.length;)e=s.preRun.shift(),B.unshift(e);var e;ie(B)}(),Y>0||(s.setStatus?(s.setStatus("Running..."),setTimeout((function(){setTimeout((function(){s.setStatus("")}),1),n()}),1)):n()))}if($=function e(){we||Ve(),we||($=e)},s.run=Ve,s.preInit)for("function"==typeof s.preInit&&(s.preInit=[s.preInit]);s.preInit.length>0;)s.preInit.pop()();return Ve(),e.ready});e.exports=o},363:e=>{"use strict";e.exports=n(363)},102:e=>{"use strict";e.exports=n(102)},914:e=>{"use strict";e.exports=n(914)},583:e=>{"use strict";e.exports=n(583)},180:e=>{"use strict";e.exports=n(180)},747:e=>{"use strict";e.exports=n(747)},81:e=>{"use strict";e.exports=n(81)},782:()=>{},384:()=>{},375:()=>{}},t={};function i(n){var r=t[n];if(void 0!==r)return r.exports;var a=t[n]={exports:{}};return e[n].call(a.exports,a,a.exports,i),a.exports}i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var a={};return(()=>{"use strict";i.r(a),i.d(a,{FingerLookupIndices:()=>r,MediapipeMix2WorkerManager:()=>v,NUM_KEYPOINTS:()=>l,OperationType:()=>t,PartsLookupIndices:()=>n,RefinedLeftEyePoints:()=>h,RefinedLeftIrisPoints:()=>p,RefinedLipPoints:()=>d,RefinedPoints:()=>g,RefinedRightEyePoints:()=>f,RefinedRightIrisPoints:()=>m,TRIANGULATION:()=>u});var e=i(55);const t={hand:"hand",face:"face",pose:"pose"},n={leftEye:[0,1,2,3,7],rightEye:[0,4,5,6,8],mouth:[9,10],body:[11,12,24,23,11],leftArm:[11,13,15],leftThum:[15,21],leftIndex:[15,19],leftPinly:[15,17],rightArm:[12,14,16],rightThum:[16,22],rightIndex:[16,20],rightPinly:[16,18],leftLeg:[23,25,27],leftFoot:[27,29,31],rightLeg:[24,26,28],rightFoot:[28,30,32]},r={thumb:[0,1,2,3,4],indexFinger:[0,5,6,7,8],middleFinger:[0,9,10,11,12],ringFinger:[0,13,14,15,16],pinky:[0,17,18,19,20]};var o=i(477),s=i.n(o);function c(){return s()('/*! For license information please see index.worker.js.LICENSE.txt */\n(()=>{var t={252:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.BlockingQueue=void 0;var r=function(){function t(){this._resolvers=[],this._promises=[]}return t.prototype._add=function(){var t=this;this._promises.push(new Promise((function(e){t._resolvers.push(e)})))},t.prototype.enqueue=function(t){this._resolvers.length||this._add(),this._resolvers.shift()(t)},t.prototype.dequeue=function(){return this._promises.length||this._add(),this._promises.shift()},t.prototype.isEmpty=function(){return!this._promises.length},t.prototype.isBlocked=function(){return!!this._resolvers.length},Object.defineProperty(t.prototype,"length",{get:function(){return this._promises.length-this._resolvers.length},enumerable:!1,configurable:!0}),t}();e.BlockingQueue=r},289:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getBrowserType=e.BrowserTypes=void 0,e.BrowserTypes={MSIE:"MSIE",EDGE:"EDGE",CHROME:"CHROME",SAFARI:"SAFARI",FIREFOX:"FIREFOX",OPERA:"OPERA",OTHER:"OTHER"},e.getBrowserType=function(){var t=window.navigator.userAgent.toLowerCase();return-1!==t.indexOf("msie")||-1!==t.indexOf("trident")?e.BrowserTypes.MSIE:-1!==t.indexOf("edge")?e.BrowserTypes.EDGE:-1!==t.indexOf("chrome")?e.BrowserTypes.CHROME:-1!==t.indexOf("safari")?e.BrowserTypes.SAFARI:-1!==t.indexOf("firefox")?e.BrowserTypes.FIREFOX:-1!==t.indexOf("opera")?e.BrowserTypes.OPERA:e.BrowserTypes.OTHER}},187:function(t,e,r){"use strict";var n=r(764).lW,o=this&&this.__awaiter||function(t,e,r,n){return new(r||(r=Promise))((function(o,i){function s(t){try{u(n.next(t))}catch(t){i(t)}}function a(t){try{u(n.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?o(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(s,a)}u((n=n.apply(t,e||[])).next())}))},i=this&&this.__generator||function(t,e){var r,n,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(o=2&i[0]?n.return:i[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,i[1])).done)return o;switch(n=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,n=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!((o=(o=s.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]100)throw new Error("queue is fulled: ".concat(this.sem.length));return[4,this.lock()];case 1:t=i.sent(),o=new Promise((function(t,o){if(!f.worker)throw new Error("worker is not activated.");f.worker.onmessage=function(e){e.data.message===u.WorkerResponse.PREDICTED?t(e.data.prediction):(console.log("Prediction something wrong..",e.data.message),o(e))},n?r instanceof Uint8ClampedArray?f.worker.postMessage({message:u.WorkerCommand.PREDICT,params:e,data:r},[r.buffer]):f.worker.postMessage({message:u.WorkerCommand.PREDICT,params:e,data:r},[r]):f.worker.postMessage({message:u.WorkerCommand.PREDICT,params:e,data:r})})),i.label=2;case 2:return i.trys.push([2,4,5,6]),[4,o];case 3:return s=i.sent(),[3,6];case 4:return a=i.sent(),console.log("worker prediction error. :",a),[3,6];case 5:return this.unlock(t),[7];case 6:return[2,s]}}))}))},this.useWorker=function(t){return!t.processOnLocal&&(!1!==t.useWorkerForSafari||(0,a.getBrowserType)()!==a.BrowserTypes.SAFARI)},this.fetchData=function(e){return o(t,void 0,void 0,(function(){var t;return i(this,(function(r){switch(r.label){case 0:return e.startsWith("data:")?(t=e.split(",")[1],[2,n.from(t,"base64")]):[4,fetch(e,{method:"GET"})];case 1:return[4,r.sent().arrayBuffer()];case 2:return[2,r.sent()]}}))}))},this.sem.enqueue(0)};e.WorkerDispatcher=function(t){var e=this;this.imageProcessor=null,this.config=null,this.callbacks=null,this.setCallback=function(t){e.callbacks=t},this.dispach=function(t){return o(e,void 0,void 0,(function(){var e,r,n,o;return i(this,(function(i){switch(i.label){case 0:return this.callbacks?t.data.message!==u.WorkerCommand.INITIALIZE?[3,2]:(this.config=t.data.config,e=this,[4,this.callbacks.init(this.config)]):(console.warn("[worker] Dispatcher callbacks is not initialized"),[2]);case 1:return e.imageProcessor=i.sent(),this.context.postMessage({message:u.WorkerResponse.INITIALIZED}),console.log("[worker] Initialized"),[3,4];case 2:return t.data.message!==u.WorkerCommand.PREDICT?[3,4]:this.imageProcessor?this.config?(r=t.data.params,n=t.data.data,[4,this.imageProcessor.predict(this.config,r,n)]):(console.warn("[worker] Dispatcher config is not initialized"),[2]):(console.warn("[worker] ImageProcessor is not initialized"),[2]);case 3:o=i.sent(),this.context.postMessage({message:u.WorkerResponse.PREDICTED,prediction:o}),i.label=4;case 4:return[2]}}))}))},this.context=t}},301:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.WorkerResponse=e.WorkerCommand=void 0,e.WorkerCommand={INITIALIZE:"initialize",PREDICT:"predict"},e.WorkerResponse={INITIALIZED:"initialized",PREDICTED:"predicted"}},55:function(t,e,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(t,e,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);o&&!("get"in o?!e.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){void 0===n&&(n=r),t[n]=e[r]}),o=this&&this.__exportStar||function(t,e){for(var r in t)"default"===r||Object.prototype.hasOwnProperty.call(e,r)||n(e,t,r)};Object.defineProperty(e,"__esModule",{value:!0}),o(r(187),e),o(r(289),e)},742:(t,e)=>{"use strict";e.byteLength=function(t){var e=u(t),r=e[0],n=e[1];return 3*(r+n)/4-n},e.toByteArray=function(t){var e,r,i=u(t),s=i[0],a=i[1],f=new o(function(t,e,r){return 3*(e+r)/4-r}(0,s,a)),l=0,c=a>0?s-4:s;for(r=0;r>16&255,f[l++]=e>>8&255,f[l++]=255&e;return 2===a&&(e=n[t.charCodeAt(r)]<<2|n[t.charCodeAt(r+1)]>>4,f[l++]=255&e),1===a&&(e=n[t.charCodeAt(r)]<<10|n[t.charCodeAt(r+1)]<<4|n[t.charCodeAt(r+2)]>>2,f[l++]=e>>8&255,f[l++]=255&e),f},e.fromByteArray=function(t){for(var e,n=t.length,o=n%3,i=[],s=16383,a=0,u=n-o;au?u:a+s));return 1===o?(e=t[n-1],i.push(r[e>>2]+r[e<<4&63]+"==")):2===o&&(e=(t[n-2]<<8)+t[n-1],i.push(r[e>>10]+r[e>>4&63]+r[e<<2&63]+"=")),i.join("")};for(var r=[],n=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,a=i.length;s0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function f(t,e,n){for(var o,i,s=[],a=e;a>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return s.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},764:(t,e,r)=>{"use strict";const n=r(742),o=r(645),i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.lW=u,e.h2=50;const s=2147483647;function a(t){if(t>s)throw new RangeError(\'The value "\'+t+\'" is invalid for option "size"\');const e=new Uint8Array(t);return Object.setPrototypeOf(e,u.prototype),e}function u(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError(\'The "string" argument must be of type string. Received type number\');return c(t)}return f(t,e,r)}function f(t,e,r){if("string"==typeof t)return function(t,e){if("string"==typeof e&&""!==e||(e="utf8"),!u.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const r=0|m(t,e);let n=a(r);const o=n.write(t,e);return o!==r&&(n=n.slice(0,o)),n}(t,e);if(ArrayBuffer.isView(t))return function(t){if(G(t,Uint8Array)){const e=new Uint8Array(t);return h(e.buffer,e.byteOffset,e.byteLength)}return d(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(G(t,ArrayBuffer)||t&&G(t.buffer,ArrayBuffer))return h(t,e,r);if("undefined"!=typeof SharedArrayBuffer&&(G(t,SharedArrayBuffer)||t&&G(t.buffer,SharedArrayBuffer)))return h(t,e,r);if("number"==typeof t)throw new TypeError(\'The "value" argument must not be of type number. Received type number\');const n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return u.from(n,e,r);const o=function(t){if(u.isBuffer(t)){const e=0|p(t.length),r=a(e);return 0===r.length||t.copy(r,0,0,e),r}return void 0!==t.length?"number"!=typeof t.length||V(t.length)?a(0):d(t):"Buffer"===t.type&&Array.isArray(t.data)?d(t.data):void 0}(t);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return u.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function l(t){if("number"!=typeof t)throw new TypeError(\'"size" argument must be of type number\');if(t<0)throw new RangeError(\'The value "\'+t+\'" is invalid for option "size"\')}function c(t){return l(t),a(t<0?0:0|p(t))}function d(t){const e=t.length<0?0:0|p(t.length),r=a(e);for(let n=0;n=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|t}function m(t,e){if(u.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||G(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError(\'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type \'+typeof t);const r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let o=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return X(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return $(t).length;default:if(o)return n?-1:X(t).length;e=(""+e).toLowerCase(),o=!0}}function y(t,e,r){let n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return I(this,e,r);case"utf8":case"utf-8":return B(this,e,r);case"ascii":return M(this,e,r);case"latin1":case"binary":return D(this,e,r);case"base64":return P(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function g(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function w(t,e,r,n,o){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),V(r=+r)&&(r=o?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(o)return-1;r=t.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof e&&(e=u.from(e,n)),u.isBuffer(e))return 0===e.length?-1:E(t,e,r,n,o);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):E(t,[e],r,n,o);throw new TypeError("val must be string, number or Buffer")}function E(t,e,r,n,o){let i,s=1,a=t.length,u=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,a/=2,u/=2,r/=2}function f(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(o){let n=-1;for(i=r;ia&&(r=a-u),i=r;i>=0;i--){let r=!0;for(let n=0;no&&(n=o):n=o;const i=e.length;let s;for(n>i/2&&(n=i/2),s=0;s>8,o=r%256,i.push(o),i.push(n);return i}(e,t.length-r),t,r,n)}function P(t,e,r){return 0===e&&r===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(e,r))}function B(t,e,r){r=Math.min(t.length,r);const n=[];let o=e;for(;o239?4:e>223?3:e>191?2:1;if(o+s<=r){let r,n,a,u;switch(s){case 1:e<128&&(i=e);break;case 2:r=t[o+1],128==(192&r)&&(u=(31&e)<<6|63&r,u>127&&(i=u));break;case 3:r=t[o+1],n=t[o+2],128==(192&r)&&128==(192&n)&&(u=(15&e)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(i=u));break;case 4:r=t[o+1],n=t[o+2],a=t[o+3],128==(192&r)&&128==(192&n)&&128==(192&a)&&(u=(15&e)<<18|(63&r)<<12|(63&n)<<6|63&a,u>65535&&u<1114112&&(i=u))}}null===i?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|1023&i),n.push(i),o+=s}return function(t){const e=t.length;if(e<=F)return String.fromCharCode.apply(String,t);let r="",n=0;for(;nn.length?(u.isBuffer(e)||(e=u.from(e)),e.copy(n,o)):Uint8Array.prototype.set.call(n,e,o);else{if(!u.isBuffer(e))throw new TypeError(\'"list" argument must be an Array of Buffers\');e.copy(n,o)}o+=e.length}return n},u.byteLength=m,u.prototype._isBuffer=!0,u.prototype.swap16=function(){const t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;er&&(t+=" ... "),""},i&&(u.prototype[i]=u.prototype.inspect),u.prototype.compare=function(t,e,r,n,o){if(G(t,Uint8Array)&&(t=u.from(t,t.offset,t.byteLength)),!u.isBuffer(t))throw new TypeError(\'The "target" argument must be one of type Buffer or Uint8Array. Received type \'+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),e<0||r>t.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&e>=r)return 0;if(n>=o)return-1;if(e>=r)return 1;if(this===t)return 0;let i=(o>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0);const a=Math.min(i,s),f=this.slice(n,o),l=t.slice(e,r);for(let t=0;t>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const o=this.length-e;if((void 0===r||r>o)&&(r=o),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let i=!1;for(;;)switch(n){case"hex":return v(this,t,e,r);case"utf8":case"utf-8":return _(this,t,e,r);case"ascii":case"latin1":case"binary":return b(this,t,e,r);case"base64":return A(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,t,e,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const F=4096;function M(t,e,r){let n="";r=Math.min(t.length,r);for(let o=e;on)&&(r=n);let o="";for(let n=e;nr)throw new RangeError("Trying to access beyond buffer length")}function O(t,e,r,n,o,i){if(!u.isBuffer(t))throw new TypeError(\'"buffer" argument must be a Buffer instance\');if(e>o||et.length)throw new RangeError("Index out of range")}function H(t,e,r,n,o){j(e,n,o,t,r,7);let i=Number(e&BigInt(4294967295));t[r++]=i,i>>=8,t[r++]=i,i>>=8,t[r++]=i,i>>=8,t[r++]=i;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,r}function S(t,e,r,n,o){j(e,n,o,t,r,7);let i=Number(e&BigInt(4294967295));t[r+7]=i,i>>=8,t[r+6]=i,i>>=8,t[r+5]=i,i>>=8,t[r+4]=i;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=s,s>>=8,t[r+2]=s,s>>=8,t[r+1]=s,s>>=8,t[r]=s,r+8}function T(t,e,r,n,o,i){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function L(t,e,r,n,i){return e=+e,r>>>=0,i||T(t,0,r,4),o.write(t,e,r,n,23,4),r+4}function U(t,e,r,n,i){return e=+e,r>>>=0,i||T(t,0,r,8),o.write(t,e,r,n,52,8),r+8}u.prototype.slice=function(t,e){const r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||R(t,e,this.length);let n=this[t],o=1,i=0;for(;++i>>=0,e>>>=0,r||R(t,e,this.length);let n=this[t+--e],o=1;for(;e>0&&(o*=256);)n+=this[t+--e]*o;return n},u.prototype.readUint8=u.prototype.readUInt8=function(t,e){return t>>>=0,e||R(t,1,this.length),this[t]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(t,e){return t>>>=0,e||R(t,2,this.length),this[t]|this[t+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(t,e){return t>>>=0,e||R(t,2,this.length),this[t]<<8|this[t+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(t,e){return t>>>=0,e||R(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(t,e){return t>>>=0,e||R(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},u.prototype.readBigUInt64LE=J((function(t){W(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||Y(t,this.length-8);const n=e+256*this[++t]+65536*this[++t]+this[++t]*2**24,o=this[++t]+256*this[++t]+65536*this[++t]+r*2**24;return BigInt(n)+(BigInt(o)<>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||Y(t,this.length-8);const n=e*2**24+65536*this[++t]+256*this[++t]+this[++t],o=this[++t]*2**24+65536*this[++t]+256*this[++t]+r;return(BigInt(n)<>>=0,e>>>=0,r||R(t,e,this.length);let n=this[t],o=1,i=0;for(;++i=o&&(n-=Math.pow(2,8*e)),n},u.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=e,o=1,i=this[t+--n];for(;n>0&&(o*=256);)i+=this[t+--n]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*e)),i},u.prototype.readInt8=function(t,e){return t>>>=0,e||R(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},u.prototype.readInt16LE=function(t,e){t>>>=0,e||R(t,2,this.length);const r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(t,e){t>>>=0,e||R(t,2,this.length);const r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(t,e){return t>>>=0,e||R(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},u.prototype.readInt32BE=function(t,e){return t>>>=0,e||R(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},u.prototype.readBigInt64LE=J((function(t){W(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||Y(t,this.length-8);const n=this[t+4]+256*this[t+5]+65536*this[t+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||Y(t,this.length-8);const n=(e<<24)+65536*this[++t]+256*this[++t]+this[++t];return(BigInt(n)<>>=0,e||R(t,4,this.length),o.read(this,t,!0,23,4)},u.prototype.readFloatBE=function(t,e){return t>>>=0,e||R(t,4,this.length),o.read(this,t,!1,23,4)},u.prototype.readDoubleLE=function(t,e){return t>>>=0,e||R(t,8,this.length),o.read(this,t,!0,52,8)},u.prototype.readDoubleBE=function(t,e){return t>>>=0,e||R(t,8,this.length),o.read(this,t,!1,52,8)},u.prototype.writeUintLE=u.prototype.writeUIntLE=function(t,e,r,n){t=+t,e>>>=0,r>>>=0,n||O(this,t,e,r,Math.pow(2,8*r)-1,0);let o=1,i=0;for(this[e]=255&t;++i>>=0,r>>>=0,n||O(this,t,e,r,Math.pow(2,8*r)-1,0);let o=r-1,i=1;for(this[e+o]=255&t;--o>=0&&(i*=256);)this[e+o]=t/i&255;return e+r},u.prototype.writeUint8=u.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,1,255,0),this[e]=255&t,e+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},u.prototype.writeBigUInt64LE=J((function(t,e=0){return H(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeBigUInt64BE=J((function(t,e=0){return S(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);O(this,t,e,r,n-1,-n)}let o=0,i=1,s=0;for(this[e]=255&t;++o>0)-s&255;return e+r},u.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);O(this,t,e,r,n-1,-n)}let o=r-1,i=1,s=0;for(this[e+o]=255&t;--o>=0&&(i*=256);)t<0&&0===s&&0!==this[e+o+1]&&(s=1),this[e+o]=(t/i>>0)-s&255;return e+r},u.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},u.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},u.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},u.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},u.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},u.prototype.writeBigInt64LE=J((function(t,e=0){return H(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeBigInt64BE=J((function(t,e=0){return S(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeFloatLE=function(t,e,r){return L(this,t,e,!0,r)},u.prototype.writeFloatBE=function(t,e,r){return L(this,t,e,!1,r)},u.prototype.writeDoubleLE=function(t,e,r){return U(this,t,e,!0,r)},u.prototype.writeDoubleBE=function(t,e,r){return U(this,t,e,!1,r)},u.prototype.copy=function(t,e,r,n){if(!u.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(o=e;o=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function j(t,e,r,n,o,i){if(t>r||t3?0===e||e===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`:`>= ${e}${n} and <= ${r}${n}`,new C.ERR_OUT_OF_RANGE("value",o,t)}!function(t,e,r){W(e,"offset"),void 0!==t[e]&&void 0!==t[e+r]||Y(e,t.length-(r+1))}(n,o,i)}function W(t,e){if("number"!=typeof t)throw new C.ERR_INVALID_ARG_TYPE(e,"number",t)}function Y(t,e,r){if(Math.floor(t)!==t)throw W(t,r),new C.ERR_OUT_OF_RANGE(r||"offset","an integer",t);if(e<0)throw new C.ERR_BUFFER_OUT_OF_BOUNDS;throw new C.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${e}`,t)}N("ERR_BUFFER_OUT_OF_BOUNDS",(function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),N("ERR_INVALID_ARG_TYPE",(function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`}),TypeError),N("ERR_OUT_OF_RANGE",(function(t,e,r){let n=`The value of "${t}" is out of range.`,o=r;return Number.isInteger(r)&&Math.abs(r)>2**32?o=z(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=z(o)),o+="n"),n+=` It must be ${e}. Received ${o}`,n}),RangeError);const K=/[^+/0-9A-Za-z-_]/g;function X(t,e){let r;e=e||1/0;const n=t.length;let o=null;const i=[];for(let s=0;s55295&&r<57344){if(!o){if(r>56319){(e-=3)>-1&&i.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(e-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(e-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((e-=1)<0)break;i.push(r)}else if(r<2048){if((e-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function $(t){return n.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(K,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function q(t,e,r,n){let o;for(o=0;o=e.length||o>=t.length);++o)e[o+r]=t[o];return o}function G(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function V(t){return t!=t}const Z=function(){const t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let o=0;o<16;++o)e[n+o]=t[r]+t[o]}return e}();function J(t){return"undefined"==typeof BigInt?Q:t}function Q(){throw new Error("BigInt not supported")}},645:(t,e)=>{e.read=function(t,e,r,n,o){var i,s,a=8*o-n-1,u=(1<>1,l=-7,c=r?o-1:0,d=r?-1:1,h=t[e+c];for(c+=d,i=h&(1<<-l)-1,h>>=-l,l+=a;l>0;i=256*i+t[e+c],c+=d,l-=8);for(s=i&(1<<-l)-1,i>>=-l,l+=n;l>0;s=256*s+t[e+c],c+=d,l-=8);if(0===i)i=1-f;else{if(i===u)return s?NaN:1/0*(h?-1:1);s+=Math.pow(2,n),i-=f}return(h?-1:1)*s*Math.pow(2,i-n)},e.write=function(t,e,r,n,o,i){var s,a,u,f=8*i-o-1,l=(1<>1,d=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:i-1,p=n?1:-1,m=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=l):(s=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-s))<1&&(s--,u*=2),(e+=s+c>=1?d/u:d*Math.pow(2,1-c))*u>=2&&(s++,u/=2),s+c>=l?(a=0,s=l):s+c>=1?(a=(e*u-1)*Math.pow(2,o),s+=c):(a=e*Math.pow(2,c-1)*Math.pow(2,o),s=0));o>=8;t[r+h]=255&a,h+=p,a/=256,o-=8);for(s=s<0;t[r+h]=255&s,h+=p,s/=256,f-=8);t[r+h-p]|=128*m}},503:(t,e,r)=>{var n,o=r(764).lW,i=(n=(n="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){var e,i,s=void 0!==(t=t||{})?t:{},a=Object.assign;s.ready=new Promise((function(t,r){e=t,i=r}));var u,f,l,c,d,h,p=a({},s),m=[],y="./this.program",g=(t,e)=>{throw e},w="object"==typeof window,E="function"==typeof importScripts,v="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,_="";v?(_=E?r(375).dirname(_)+"/":"//",h=()=>{d||(c=r(384),d=r(375))},u=function(t,e){return h(),t=d.normalize(t),c.readFileSync(t,e?null:"utf8")},l=t=>{var e=u(t,!0);return e.buffer||(e=new Uint8Array(e)),e},f=(t,e,r)=>{h(),t=d.normalize(t),c.readFile(t,(function(t,n){t?r(t):e(n.buffer)}))},process.argv.length>1&&(y=process.argv[1].replace(/\\\\/g,"/")),m=process.argv.slice(2),process.on("uncaughtException",(function(t){if(!(t instanceof Dt))throw t})),process.on("unhandledRejection",(function(t){throw t})),g=(t,e)=>{if(j())throw process.exitCode=t,e;var r;(r=e)instanceof Dt||k("exiting due to exception: "+r),process.exit(t)},s.inspect=function(){return"[Emscripten Module object]"}):(w||E)&&(E?_=self.location.href:"undefined"!=typeof document&&document.currentScript&&(_=document.currentScript.src),n&&(_=n),_=0!==_.indexOf("blob:")?_.substr(0,_.replace(/[?#].*/,"").lastIndexOf("/")+1):"",u=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},E&&(l=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),f=(t,e,r)=>{var n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType="arraybuffer",n.onload=()=>{200==n.status||0==n.status&&n.response?e(n.response):r()},n.onerror=r,n.send(null)});var b,A=s.print||console.log.bind(console),k=s.printErr||console.warn.bind(console);a(s,p),p=null,s.arguments&&(m=s.arguments),s.thisProgram&&(y=s.thisProgram),s.quit&&(g=s.quit),s.wasmBinary&&(b=s.wasmBinary);var P,B=s.noExitRuntime||!0;"object"!=typeof WebAssembly&&J("no native wasm support detected");var F,M,D,I,x=!1,R="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function O(t,e,r){for(var n=e+r,o=e;t[o]&&!(o>=n);)++o;if(o-e>16&&t.subarray&&R)return R.decode(t.subarray(e,o));for(var i="";e>10,56320|1023&f)}}else i+=String.fromCharCode((31&s)<<6|a)}else i+=String.fromCharCode(s)}return i}function H(t,e){return t?O(D,t,e):""}function S(t,e,r,n){if(!(n>0))return 0;for(var o=r,i=r+n-1,s=0;s=55296&&a<=57343&&(a=65536+((1023&a)<<10)|1023&t.charCodeAt(++s)),a<=127){if(r>=i)break;e[r++]=a}else if(a<=2047){if(r+1>=i)break;e[r++]=192|a>>6,e[r++]=128|63&a}else if(a<=65535){if(r+2>=i)break;e[r++]=224|a>>12,e[r++]=128|a>>6&63,e[r++]=128|63&a}else{if(r+3>=i)break;e[r++]=240|a>>18,e[r++]=128|a>>12&63,e[r++]=128|a>>6&63,e[r++]=128|63&a}}return e[r]=0,r-o}function T(t){for(var e=0,r=0;r=55296&&n<=57343&&(n=65536+((1023&n)<<10)|1023&t.charCodeAt(++r)),n<=127?++e:e+=n<=2047?2:n<=65535?3:4}return e}function L(t){F=t,s.HEAP8=M=new Int8Array(t),s.HEAP16=new Int16Array(t),s.HEAP32=I=new Int32Array(t),s.HEAPU8=D=new Uint8Array(t),s.HEAPU16=new Uint16Array(t),s.HEAPU32=new Uint32Array(t),s.HEAPF32=new Float32Array(t),s.HEAPF64=new Float64Array(t)}s.INITIAL_MEMORY;var U,C=[],N=[],z=[];function j(){return B||!1}var W,Y,K,X,$=0,q=null,G=null;function V(t){$++,s.monitorRunDependencies&&s.monitorRunDependencies($)}function Z(t){if($--,s.monitorRunDependencies&&s.monitorRunDependencies($),0==$&&(null!==q&&(clearInterval(q),q=null),G)){var e=G;G=null,e()}}function J(t){s.onAbort&&s.onAbort(t),k(t="Aborted("+t+")"),x=!0,t+=". Build with -s ASSERTIONS=1 for more info.";var e=new WebAssembly.RuntimeError(t);throw i(e),e}function Q(t){return t.startsWith("data:application/octet-stream;base64,")}function tt(t){return t.startsWith("file://")}function et(t){try{if(t==W&&b)return new Uint8Array(b);if(l)return l(t);throw"both async and sync fetching of the wasm failed"}catch(t){J(t)}}function rt(t){for(;t.length>0;){var e=t.shift();if("function"!=typeof e){var r=e.func;"number"==typeof r?void 0===e.arg?it(r)():it(r)(e.arg):r(void 0===e.arg?null:e.arg)}else e(s)}}s.preloadedImages={},s.preloadedAudios={},Q(W="tflite-simd.wasm")||(Y=W,W=s.locateFile?s.locateFile(Y,_):_+Y);var nt,ot=[];function it(t){var e=ot[t];return e||(t>=ot.length&&(ot.length=t+1),ot[t]=e=U.get(t)),e}function st(t){this.excPtr=t,this.ptr=t-16,this.set_type=function(t){I[this.ptr+4>>2]=t},this.get_type=function(){return I[this.ptr+4>>2]},this.set_destructor=function(t){I[this.ptr+8>>2]=t},this.get_destructor=function(){return I[this.ptr+8>>2]},this.set_refcount=function(t){I[this.ptr>>2]=t},this.set_caught=function(t){t=t?1:0,M[this.ptr+12>>0]=t},this.get_caught=function(){return 0!=M[this.ptr+12>>0]},this.set_rethrown=function(t){t=t?1:0,M[this.ptr+13>>0]=t},this.get_rethrown=function(){return 0!=M[this.ptr+13>>0]},this.init=function(t,e){this.set_type(t),this.set_destructor(e),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var t=I[this.ptr>>2];I[this.ptr>>2]=t+1},this.release_ref=function(){var t=I[this.ptr>>2];return I[this.ptr>>2]=t-1,1===t}}function at(t){try{return P.grow(t-F.byteLength+65535>>>16),L(P.buffer),1}catch(t){}}nt=v?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:()=>performance.now();var ut={};function ft(){if(!ft.strings){var t={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:y||"./this.program"};for(var e in ut)void 0===ut[e]?delete t[e]:t[e]=ut[e];var r=[];for(var e in t)r.push(e+"="+t[e]);ft.strings=r}return ft.strings}var lt={splitPath:function(t){return/^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))(?:[\\/]*)$/.exec(t).slice(1)},normalizeArray:function(t,e){for(var r=0,n=t.length-1;n>=0;n--){var o=t[n];"."===o?t.splice(n,1):".."===o?(t.splice(n,1),r++):r&&(t.splice(n,1),r--)}if(e)for(;r;r--)t.unshift("..");return t},normalize:function(t){var e="/"===t.charAt(0),r="/"===t.substr(-1);return(t=lt.normalizeArray(t.split("/").filter((function(t){return!!t})),!e).join("/"))||e||(t="."),t&&r&&(t+="/"),(e?"/":"")+t},dirname:function(t){var e=lt.splitPath(t),r=e[0],n=e[1];return r||n?(n&&(n=n.substr(0,n.length-1)),r+n):"."},basename:function(t){if("/"===t)return"/";var e=(t=(t=lt.normalize(t)).replace(/\\/$/,"")).lastIndexOf("/");return-1===e?t:t.substr(e+1)},extname:function(t){return lt.splitPath(t)[3]},join:function(){var t=Array.prototype.slice.call(arguments,0);return lt.normalize(t.join("/"))},join2:function(t,e){return lt.normalize(t+"/"+e)}};function ct(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return function(){return crypto.getRandomValues(t),t[0]}}if(v)try{var e=r(782);return function(){return e.randomBytes(1)[0]}}catch(t){}return function(){J("randomDevice")}}var dt={resolve:function(){for(var t="",e=!1,r=arguments.length-1;r>=-1&&!e;r--){var n=r>=0?arguments[r]:mt.cwd();if("string"!=typeof n)throw new TypeError("Arguments to path.resolve must be strings");if(!n)return"";t=n+"/"+t,e="/"===n.charAt(0)}return(e?"/":"")+(t=lt.normalizeArray(t.split("/").filter((function(t){return!!t})),!e).join("/"))||"."},relative:function(t,e){function r(t){for(var e=0;e=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=dt.resolve(t).substr(1),e=dt.resolve(e).substr(1);for(var n=r(t.split("/")),o=r(e.split("/")),i=Math.min(n.length,o.length),s=i,a=0;a0?r.slice(0,n).toString("utf-8"):null}else"undefined"!=typeof window&&"function"==typeof window.prompt?null!==(e=window.prompt("Input: "))&&(e+="\\n"):"function"==typeof readline&&null!==(e=readline())&&(e+="\\n");if(!e)return null;t.input=At(e,!0)}return t.input.shift()},put_char:function(t,e){null===e||10===e?(A(O(t.output,0)),t.output=[]):0!=e&&t.output.push(e)},flush:function(t){t.output&&t.output.length>0&&(A(O(t.output,0)),t.output=[])}},default_tty1_ops:{put_char:function(t,e){null===e||10===e?(k(O(t.output,0)),t.output=[]):0!=e&&t.output.push(e)},flush:function(t){t.output&&t.output.length>0&&(k(O(t.output,0)),t.output=[])}}};var pt={ops_table:null,mount:function(t){return pt.createNode(null,"/",16895,0)},createNode:function(t,e,r,n){if(mt.isBlkdev(r)||mt.isFIFO(r))throw new mt.ErrnoError(63);pt.ops_table||(pt.ops_table={dir:{node:{getattr:pt.node_ops.getattr,setattr:pt.node_ops.setattr,lookup:pt.node_ops.lookup,mknod:pt.node_ops.mknod,rename:pt.node_ops.rename,unlink:pt.node_ops.unlink,rmdir:pt.node_ops.rmdir,readdir:pt.node_ops.readdir,symlink:pt.node_ops.symlink},stream:{llseek:pt.stream_ops.llseek}},file:{node:{getattr:pt.node_ops.getattr,setattr:pt.node_ops.setattr},stream:{llseek:pt.stream_ops.llseek,read:pt.stream_ops.read,write:pt.stream_ops.write,allocate:pt.stream_ops.allocate,mmap:pt.stream_ops.mmap,msync:pt.stream_ops.msync}},link:{node:{getattr:pt.node_ops.getattr,setattr:pt.node_ops.setattr,readlink:pt.node_ops.readlink},stream:{}},chrdev:{node:{getattr:pt.node_ops.getattr,setattr:pt.node_ops.setattr},stream:mt.chrdev_stream_ops}});var o=mt.createNode(t,e,r,n);return mt.isDir(o.mode)?(o.node_ops=pt.ops_table.dir.node,o.stream_ops=pt.ops_table.dir.stream,o.contents={}):mt.isFile(o.mode)?(o.node_ops=pt.ops_table.file.node,o.stream_ops=pt.ops_table.file.stream,o.usedBytes=0,o.contents=null):mt.isLink(o.mode)?(o.node_ops=pt.ops_table.link.node,o.stream_ops=pt.ops_table.link.stream):mt.isChrdev(o.mode)&&(o.node_ops=pt.ops_table.chrdev.node,o.stream_ops=pt.ops_table.chrdev.stream),o.timestamp=Date.now(),t&&(t.contents[e]=o,t.timestamp=o.timestamp),o},getFileDataAsTypedArray:function(t){return t.contents?t.contents.subarray?t.contents.subarray(0,t.usedBytes):new Uint8Array(t.contents):new Uint8Array(0)},expandFileStorage:function(t,e){var r=t.contents?t.contents.length:0;if(!(r>=e)){e=Math.max(e,r*(r<1048576?2:1.125)>>>0),0!=r&&(e=Math.max(e,256));var n=t.contents;t.contents=new Uint8Array(e),t.usedBytes>0&&t.contents.set(n.subarray(0,t.usedBytes),0)}},resizeFileStorage:function(t,e){if(t.usedBytes!=e)if(0==e)t.contents=null,t.usedBytes=0;else{var r=t.contents;t.contents=new Uint8Array(e),r&&t.contents.set(r.subarray(0,Math.min(e,t.usedBytes))),t.usedBytes=e}},node_ops:{getattr:function(t){var e={};return e.dev=mt.isChrdev(t.mode)?t.id:1,e.ino=t.id,e.mode=t.mode,e.nlink=1,e.uid=0,e.gid=0,e.rdev=t.rdev,mt.isDir(t.mode)?e.size=4096:mt.isFile(t.mode)?e.size=t.usedBytes:mt.isLink(t.mode)?e.size=t.link.length:e.size=0,e.atime=new Date(t.timestamp),e.mtime=new Date(t.timestamp),e.ctime=new Date(t.timestamp),e.blksize=4096,e.blocks=Math.ceil(e.size/e.blksize),e},setattr:function(t,e){void 0!==e.mode&&(t.mode=e.mode),void 0!==e.timestamp&&(t.timestamp=e.timestamp),void 0!==e.size&&pt.resizeFileStorage(t,e.size)},lookup:function(t,e){throw mt.genericErrors[44]},mknod:function(t,e,r,n){return pt.createNode(t,e,r,n)},rename:function(t,e,r){if(mt.isDir(t.mode)){var n;try{n=mt.lookupNode(e,r)}catch(t){}if(n)for(var o in n.contents)throw new mt.ErrnoError(55)}delete t.parent.contents[t.name],t.parent.timestamp=Date.now(),t.name=r,e.contents[r]=t,e.timestamp=t.parent.timestamp,t.parent=e},unlink:function(t,e){delete t.contents[e],t.timestamp=Date.now()},rmdir:function(t,e){var r=mt.lookupNode(t,e);for(var n in r.contents)throw new mt.ErrnoError(55);delete t.contents[e],t.timestamp=Date.now()},readdir:function(t){var e=[".",".."];for(var r in t.contents)t.contents.hasOwnProperty(r)&&e.push(r);return e},symlink:function(t,e,r){var n=pt.createNode(t,e,41471,0);return n.link=r,n},readlink:function(t){if(!mt.isLink(t.mode))throw new mt.ErrnoError(28);return t.link}},stream_ops:{read:function(t,e,r,n,o){var i=t.node.contents;if(o>=t.node.usedBytes)return 0;var s=Math.min(t.node.usedBytes-o,n);if(s>8&&i.subarray)e.set(i.subarray(o,o+s),r);else for(var a=0;a0||n+r{if(!(t=dt.resolve(mt.cwd(),t)))return{path:"",node:null};var r={follow_mount:!0,recurse_count:0};for(var n in r)void 0===e[n]&&(e[n]=r[n]);if(e.recurse_count>8)throw new mt.ErrnoError(32);for(var o=lt.normalizeArray(t.split("/").filter((t=>!!t)),!1),i=mt.root,s="/",a=0;a40)throw new mt.ErrnoError(32)}}return{path:s,node:i}},getPath:t=>{for(var e;;){if(mt.isRoot(t)){var r=t.mount.mountpoint;return e?"/"!==r[r.length-1]?r+"/"+e:r+e:r}e=e?t.name+"/"+e:t.name,t=t.parent}},hashName:(t,e)=>{for(var r=0,n=0;n>>0)%mt.nameTable.length},hashAddNode:t=>{var e=mt.hashName(t.parent.id,t.name);t.name_next=mt.nameTable[e],mt.nameTable[e]=t},hashRemoveNode:t=>{var e=mt.hashName(t.parent.id,t.name);if(mt.nameTable[e]===t)mt.nameTable[e]=t.name_next;else for(var r=mt.nameTable[e];r;){if(r.name_next===t){r.name_next=t.name_next;break}r=r.name_next}},lookupNode:(t,e)=>{var r=mt.mayLookup(t);if(r)throw new mt.ErrnoError(r,t);for(var n=mt.hashName(t.id,e),o=mt.nameTable[n];o;o=o.name_next){var i=o.name;if(o.parent.id===t.id&&i===e)return o}return mt.lookup(t,e)},createNode:(t,e,r,n)=>{var o=new mt.FSNode(t,e,r,n);return mt.hashAddNode(o),o},destroyNode:t=>{mt.hashRemoveNode(t)},isRoot:t=>t===t.parent,isMountpoint:t=>!!t.mounted,isFile:t=>32768==(61440&t),isDir:t=>16384==(61440&t),isLink:t=>40960==(61440&t),isChrdev:t=>8192==(61440&t),isBlkdev:t=>24576==(61440&t),isFIFO:t=>4096==(61440&t),isSocket:t=>49152==(49152&t),flagModes:{r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090},modeStringToFlags:t=>{var e=mt.flagModes[t];if(void 0===e)throw new Error("Unknown file open mode: "+t);return e},flagsToPermissionString:t=>{var e=["r","w","rw"][3&t];return 512&t&&(e+="w"),e},nodePermissions:(t,e)=>mt.ignorePermissions||(!e.includes("r")||292&t.mode)&&(!e.includes("w")||146&t.mode)&&(!e.includes("x")||73&t.mode)?0:2,mayLookup:t=>mt.nodePermissions(t,"x")||(t.node_ops.lookup?0:2),mayCreate:(t,e)=>{try{return mt.lookupNode(t,e),20}catch(t){}return mt.nodePermissions(t,"wx")},mayDelete:(t,e,r)=>{var n;try{n=mt.lookupNode(t,e)}catch(t){return t.errno}var o=mt.nodePermissions(t,"wx");if(o)return o;if(r){if(!mt.isDir(n.mode))return 54;if(mt.isRoot(n)||mt.getPath(n)===mt.cwd())return 10}else if(mt.isDir(n.mode))return 31;return 0},mayOpen:(t,e)=>t?mt.isLink(t.mode)?32:mt.isDir(t.mode)&&("r"!==mt.flagsToPermissionString(e)||512&e)?31:mt.nodePermissions(t,mt.flagsToPermissionString(e)):44,MAX_OPEN_FDS:4096,nextfd:(t=0,e=mt.MAX_OPEN_FDS)=>{for(var r=t;r<=e;r++)if(!mt.streams[r])return r;throw new mt.ErrnoError(33)},getStream:t=>mt.streams[t],createStream:(t,e,r)=>{mt.FSStream||(mt.FSStream=function(){},mt.FSStream.prototype={object:{get:function(){return this.node},set:function(t){this.node=t}},isRead:{get:function(){return 1!=(2097155&this.flags)}},isWrite:{get:function(){return 0!=(2097155&this.flags)}},isAppend:{get:function(){return 1024&this.flags}}});var n=new mt.FSStream;for(var o in t)n[o]=t[o];t=n;var i=mt.nextfd(e,r);return t.fd=i,mt.streams[i]=t,t},closeStream:t=>{mt.streams[t]=null},chrdev_stream_ops:{open:t=>{var e=mt.getDevice(t.node.rdev);t.stream_ops=e.stream_ops,t.stream_ops.open&&t.stream_ops.open(t)},llseek:()=>{throw new mt.ErrnoError(70)}},major:t=>t>>8,minor:t=>255&t,makedev:(t,e)=>t<<8|e,registerDevice:(t,e)=>{mt.devices[t]={stream_ops:e}},getDevice:t=>mt.devices[t],getMounts:t=>{for(var e=[],r=[t];r.length;){var n=r.pop();e.push(n),r.push.apply(r,n.mounts)}return e},syncfs:(t,e)=>{"function"==typeof t&&(e=t,t=!1),mt.syncFSRequests++,mt.syncFSRequests>1&&k("warning: "+mt.syncFSRequests+" FS.syncfs operations in flight at once, probably just doing extra work");var r=mt.getMounts(mt.root.mount),n=0;function o(t){return mt.syncFSRequests--,e(t)}function i(t){if(t)return i.errored?void 0:(i.errored=!0,o(t));++n>=r.length&&o(null)}r.forEach((e=>{if(!e.type.syncfs)return i(null);e.type.syncfs(e,t,i)}))},mount:(t,e,r)=>{var n,o="/"===r,i=!r;if(o&&mt.root)throw new mt.ErrnoError(10);if(!o&&!i){var s=mt.lookupPath(r,{follow_mount:!1});if(r=s.path,n=s.node,mt.isMountpoint(n))throw new mt.ErrnoError(10);if(!mt.isDir(n.mode))throw new mt.ErrnoError(54)}var a={type:t,opts:e,mountpoint:r,mounts:[]},u=t.mount(a);return u.mount=a,a.root=u,o?mt.root=u:n&&(n.mounted=a,n.mount&&n.mount.mounts.push(a)),u},unmount:t=>{var e=mt.lookupPath(t,{follow_mount:!1});if(!mt.isMountpoint(e.node))throw new mt.ErrnoError(28);var r=e.node,n=r.mounted,o=mt.getMounts(n);Object.keys(mt.nameTable).forEach((t=>{for(var e=mt.nameTable[t];e;){var r=e.name_next;o.includes(e.mount)&&mt.destroyNode(e),e=r}})),r.mounted=null;var i=r.mount.mounts.indexOf(n);r.mount.mounts.splice(i,1)},lookup:(t,e)=>t.node_ops.lookup(t,e),mknod:(t,e,r)=>{var n=mt.lookupPath(t,{parent:!0}).node,o=lt.basename(t);if(!o||"."===o||".."===o)throw new mt.ErrnoError(28);var i=mt.mayCreate(n,o);if(i)throw new mt.ErrnoError(i);if(!n.node_ops.mknod)throw new mt.ErrnoError(63);return n.node_ops.mknod(n,o,e,r)},create:(t,e)=>(e=void 0!==e?e:438,e&=4095,e|=32768,mt.mknod(t,e,0)),mkdir:(t,e)=>(e=void 0!==e?e:511,e&=1023,e|=16384,mt.mknod(t,e,0)),mkdirTree:(t,e)=>{for(var r=t.split("/"),n="",o=0;o(void 0===r&&(r=e,e=438),e|=8192,mt.mknod(t,e,r)),symlink:(t,e)=>{if(!dt.resolve(t))throw new mt.ErrnoError(44);var r=mt.lookupPath(e,{parent:!0}).node;if(!r)throw new mt.ErrnoError(44);var n=lt.basename(e),o=mt.mayCreate(r,n);if(o)throw new mt.ErrnoError(o);if(!r.node_ops.symlink)throw new mt.ErrnoError(63);return r.node_ops.symlink(r,n,t)},rename:(t,e)=>{var r,n,o=lt.dirname(t),i=lt.dirname(e),s=lt.basename(t),a=lt.basename(e);if(r=mt.lookupPath(t,{parent:!0}).node,n=mt.lookupPath(e,{parent:!0}).node,!r||!n)throw new mt.ErrnoError(44);if(r.mount!==n.mount)throw new mt.ErrnoError(75);var u,f=mt.lookupNode(r,s),l=dt.relative(t,i);if("."!==l.charAt(0))throw new mt.ErrnoError(28);if("."!==(l=dt.relative(e,o)).charAt(0))throw new mt.ErrnoError(55);try{u=mt.lookupNode(n,a)}catch(t){}if(f!==u){var c=mt.isDir(f.mode),d=mt.mayDelete(r,s,c);if(d)throw new mt.ErrnoError(d);if(d=u?mt.mayDelete(n,a,c):mt.mayCreate(n,a))throw new mt.ErrnoError(d);if(!r.node_ops.rename)throw new mt.ErrnoError(63);if(mt.isMountpoint(f)||u&&mt.isMountpoint(u))throw new mt.ErrnoError(10);if(n!==r&&(d=mt.nodePermissions(r,"w")))throw new mt.ErrnoError(d);mt.hashRemoveNode(f);try{r.node_ops.rename(f,n,a)}catch(t){throw t}finally{mt.hashAddNode(f)}}},rmdir:t=>{var e=mt.lookupPath(t,{parent:!0}).node,r=lt.basename(t),n=mt.lookupNode(e,r),o=mt.mayDelete(e,r,!0);if(o)throw new mt.ErrnoError(o);if(!e.node_ops.rmdir)throw new mt.ErrnoError(63);if(mt.isMountpoint(n))throw new mt.ErrnoError(10);e.node_ops.rmdir(e,r),mt.destroyNode(n)},readdir:t=>{var e=mt.lookupPath(t,{follow:!0}).node;if(!e.node_ops.readdir)throw new mt.ErrnoError(54);return e.node_ops.readdir(e)},unlink:t=>{var e=mt.lookupPath(t,{parent:!0}).node;if(!e)throw new mt.ErrnoError(44);var r=lt.basename(t),n=mt.lookupNode(e,r),o=mt.mayDelete(e,r,!1);if(o)throw new mt.ErrnoError(o);if(!e.node_ops.unlink)throw new mt.ErrnoError(63);if(mt.isMountpoint(n))throw new mt.ErrnoError(10);e.node_ops.unlink(e,r),mt.destroyNode(n)},readlink:t=>{var e=mt.lookupPath(t).node;if(!e)throw new mt.ErrnoError(44);if(!e.node_ops.readlink)throw new mt.ErrnoError(28);return dt.resolve(mt.getPath(e.parent),e.node_ops.readlink(e))},stat:(t,e)=>{var r=mt.lookupPath(t,{follow:!e}).node;if(!r)throw new mt.ErrnoError(44);if(!r.node_ops.getattr)throw new mt.ErrnoError(63);return r.node_ops.getattr(r)},lstat:t=>mt.stat(t,!0),chmod:(t,e,r)=>{var n;if(!(n="string"==typeof t?mt.lookupPath(t,{follow:!r}).node:t).node_ops.setattr)throw new mt.ErrnoError(63);n.node_ops.setattr(n,{mode:4095&e|-4096&n.mode,timestamp:Date.now()})},lchmod:(t,e)=>{mt.chmod(t,e,!0)},fchmod:(t,e)=>{var r=mt.getStream(t);if(!r)throw new mt.ErrnoError(8);mt.chmod(r.node,e)},chown:(t,e,r,n)=>{var o;if(!(o="string"==typeof t?mt.lookupPath(t,{follow:!n}).node:t).node_ops.setattr)throw new mt.ErrnoError(63);o.node_ops.setattr(o,{timestamp:Date.now()})},lchown:(t,e,r)=>{mt.chown(t,e,r,!0)},fchown:(t,e,r)=>{var n=mt.getStream(t);if(!n)throw new mt.ErrnoError(8);mt.chown(n.node,e,r)},truncate:(t,e)=>{if(e<0)throw new mt.ErrnoError(28);var r;if(!(r="string"==typeof t?mt.lookupPath(t,{follow:!0}).node:t).node_ops.setattr)throw new mt.ErrnoError(63);if(mt.isDir(r.mode))throw new mt.ErrnoError(31);if(!mt.isFile(r.mode))throw new mt.ErrnoError(28);var n=mt.nodePermissions(r,"w");if(n)throw new mt.ErrnoError(n);r.node_ops.setattr(r,{size:e,timestamp:Date.now()})},ftruncate:(t,e)=>{var r=mt.getStream(t);if(!r)throw new mt.ErrnoError(8);if(0==(2097155&r.flags))throw new mt.ErrnoError(28);mt.truncate(r.node,e)},utime:(t,e,r)=>{var n=mt.lookupPath(t,{follow:!0}).node;n.node_ops.setattr(n,{timestamp:Math.max(e,r)})},open:(t,e,r,n,o)=>{if(""===t)throw new mt.ErrnoError(44);var i;if(r=void 0===r?438:r,r=64&(e="string"==typeof e?mt.modeStringToFlags(e):e)?4095&r|32768:0,"object"==typeof t)i=t;else{t=lt.normalize(t);try{i=mt.lookupPath(t,{follow:!(131072&e)}).node}catch(t){}}var a=!1;if(64&e)if(i){if(128&e)throw new mt.ErrnoError(20)}else i=mt.mknod(t,r,0),a=!0;if(!i)throw new mt.ErrnoError(44);if(mt.isChrdev(i.mode)&&(e&=-513),65536&e&&!mt.isDir(i.mode))throw new mt.ErrnoError(54);if(!a){var u=mt.mayOpen(i,e);if(u)throw new mt.ErrnoError(u)}512&e&&mt.truncate(i,0),e&=-131713;var f=mt.createStream({node:i,path:mt.getPath(i),flags:e,seekable:!0,position:0,stream_ops:i.stream_ops,ungotten:[],error:!1},n,o);return f.stream_ops.open&&f.stream_ops.open(f),!s.logReadFiles||1&e||(mt.readFiles||(mt.readFiles={}),t in mt.readFiles||(mt.readFiles[t]=1)),f},close:t=>{if(mt.isClosed(t))throw new mt.ErrnoError(8);t.getdents&&(t.getdents=null);try{t.stream_ops.close&&t.stream_ops.close(t)}catch(t){throw t}finally{mt.closeStream(t.fd)}t.fd=null},isClosed:t=>null===t.fd,llseek:(t,e,r)=>{if(mt.isClosed(t))throw new mt.ErrnoError(8);if(!t.seekable||!t.stream_ops.llseek)throw new mt.ErrnoError(70);if(0!=r&&1!=r&&2!=r)throw new mt.ErrnoError(28);return t.position=t.stream_ops.llseek(t,e,r),t.ungotten=[],t.position},read:(t,e,r,n,o)=>{if(n<0||o<0)throw new mt.ErrnoError(28);if(mt.isClosed(t))throw new mt.ErrnoError(8);if(1==(2097155&t.flags))throw new mt.ErrnoError(8);if(mt.isDir(t.node.mode))throw new mt.ErrnoError(31);if(!t.stream_ops.read)throw new mt.ErrnoError(28);var i=void 0!==o;if(i){if(!t.seekable)throw new mt.ErrnoError(70)}else o=t.position;var s=t.stream_ops.read(t,e,r,n,o);return i||(t.position+=s),s},write:(t,e,r,n,o,i)=>{if(n<0||o<0)throw new mt.ErrnoError(28);if(mt.isClosed(t))throw new mt.ErrnoError(8);if(0==(2097155&t.flags))throw new mt.ErrnoError(8);if(mt.isDir(t.node.mode))throw new mt.ErrnoError(31);if(!t.stream_ops.write)throw new mt.ErrnoError(28);t.seekable&&1024&t.flags&&mt.llseek(t,0,2);var s=void 0!==o;if(s){if(!t.seekable)throw new mt.ErrnoError(70)}else o=t.position;var a=t.stream_ops.write(t,e,r,n,o,i);return s||(t.position+=a),a},allocate:(t,e,r)=>{if(mt.isClosed(t))throw new mt.ErrnoError(8);if(e<0||r<=0)throw new mt.ErrnoError(28);if(0==(2097155&t.flags))throw new mt.ErrnoError(8);if(!mt.isFile(t.node.mode)&&!mt.isDir(t.node.mode))throw new mt.ErrnoError(43);if(!t.stream_ops.allocate)throw new mt.ErrnoError(138);t.stream_ops.allocate(t,e,r)},mmap:(t,e,r,n,o,i)=>{if(0!=(2&o)&&0==(2&i)&&2!=(2097155&t.flags))throw new mt.ErrnoError(2);if(1==(2097155&t.flags))throw new mt.ErrnoError(2);if(!t.stream_ops.mmap)throw new mt.ErrnoError(43);return t.stream_ops.mmap(t,e,r,n,o,i)},msync:(t,e,r,n,o)=>t&&t.stream_ops.msync?t.stream_ops.msync(t,e,r,n,o):0,munmap:t=>0,ioctl:(t,e,r)=>{if(!t.stream_ops.ioctl)throw new mt.ErrnoError(59);return t.stream_ops.ioctl(t,e,r)},readFile:(t,e={})=>{if(e.flags=e.flags||0,e.encoding=e.encoding||"binary","utf8"!==e.encoding&&"binary"!==e.encoding)throw new Error(\'Invalid encoding type "\'+e.encoding+\'"\');var r,n=mt.open(t,e.flags),o=mt.stat(t).size,i=new Uint8Array(o);return mt.read(n,i,0,o,0),"utf8"===e.encoding?r=O(i,0):"binary"===e.encoding&&(r=i),mt.close(n),r},writeFile:(t,e,r={})=>{r.flags=r.flags||577;var n=mt.open(t,r.flags,r.mode);if("string"==typeof e){var o=new Uint8Array(T(e)+1),i=S(e,o,0,o.length);mt.write(n,o,0,i,void 0,r.canOwn)}else{if(!ArrayBuffer.isView(e))throw new Error("Unsupported data type");mt.write(n,e,0,e.byteLength,void 0,r.canOwn)}mt.close(n)},cwd:()=>mt.currentPath,chdir:t=>{var e=mt.lookupPath(t,{follow:!0});if(null===e.node)throw new mt.ErrnoError(44);if(!mt.isDir(e.node.mode))throw new mt.ErrnoError(54);var r=mt.nodePermissions(e.node,"x");if(r)throw new mt.ErrnoError(r);mt.currentPath=e.path},createDefaultDirectories:()=>{mt.mkdir("/tmp"),mt.mkdir("/home"),mt.mkdir("/home/web_user")},createDefaultDevices:()=>{mt.mkdir("/dev"),mt.registerDevice(mt.makedev(1,3),{read:()=>0,write:(t,e,r,n,o)=>n}),mt.mkdev("/dev/null",mt.makedev(1,3)),ht.register(mt.makedev(5,0),ht.default_tty_ops),ht.register(mt.makedev(6,0),ht.default_tty1_ops),mt.mkdev("/dev/tty",mt.makedev(5,0)),mt.mkdev("/dev/tty1",mt.makedev(6,0));var t=ct();mt.createDevice("/dev","random",t),mt.createDevice("/dev","urandom",t),mt.mkdir("/dev/shm"),mt.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{mt.mkdir("/proc");var t=mt.mkdir("/proc/self");mt.mkdir("/proc/self/fd"),mt.mount({mount:()=>{var e=mt.createNode(t,"fd",16895,73);return e.node_ops={lookup:(t,e)=>{var r=+e,n=mt.getStream(r);if(!n)throw new mt.ErrnoError(8);var o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>n.path}};return o.parent=o,o}},e}},{},"/proc/self/fd")},createStandardStreams:()=>{s.stdin?mt.createDevice("/dev","stdin",s.stdin):mt.symlink("/dev/tty","/dev/stdin"),s.stdout?mt.createDevice("/dev","stdout",null,s.stdout):mt.symlink("/dev/tty","/dev/stdout"),s.stderr?mt.createDevice("/dev","stderr",null,s.stderr):mt.symlink("/dev/tty1","/dev/stderr"),mt.open("/dev/stdin",0),mt.open("/dev/stdout",1),mt.open("/dev/stderr",1)},ensureErrnoError:()=>{mt.ErrnoError||(mt.ErrnoError=function(t,e){this.node=e,this.setErrno=function(t){this.errno=t},this.setErrno(t),this.message="FS error"},mt.ErrnoError.prototype=new Error,mt.ErrnoError.prototype.constructor=mt.ErrnoError,[44].forEach((t=>{mt.genericErrors[t]=new mt.ErrnoError(t),mt.genericErrors[t].stack=""})))},staticInit:()=>{mt.ensureErrnoError(),mt.nameTable=new Array(4096),mt.mount(pt,{},"/"),mt.createDefaultDirectories(),mt.createDefaultDevices(),mt.createSpecialDirectories(),mt.filesystems={MEMFS:pt}},init:(t,e,r)=>{mt.init.initialized=!0,mt.ensureErrnoError(),s.stdin=t||s.stdin,s.stdout=e||s.stdout,s.stderr=r||s.stderr,mt.createStandardStreams()},quit:()=>{mt.init.initialized=!1;for(var t=0;t{var r=0;return t&&(r|=365),e&&(r|=146),r},findObject:(t,e)=>{var r=mt.analyzePath(t,e);return r.exists?r.object:null},analyzePath:(t,e)=>{try{t=(n=mt.lookupPath(t,{follow:!e})).path}catch(t){}var r={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var n=mt.lookupPath(t,{parent:!0});r.parentExists=!0,r.parentPath=n.path,r.parentObject=n.node,r.name=lt.basename(t),n=mt.lookupPath(t,{follow:!e}),r.exists=!0,r.path=n.path,r.object=n.node,r.name=n.node.name,r.isRoot="/"===n.path}catch(t){r.error=t.errno}return r},createPath:(t,e,r,n)=>{t="string"==typeof t?t:mt.getPath(t);for(var o=e.split("/").reverse();o.length;){var i=o.pop();if(i){var s=lt.join2(t,i);try{mt.mkdir(s)}catch(t){}t=s}}return s},createFile:(t,e,r,n,o)=>{var i=lt.join2("string"==typeof t?t:mt.getPath(t),e),s=mt.getMode(n,o);return mt.create(i,s)},createDataFile:(t,e,r,n,o,i)=>{var s=e;t&&(t="string"==typeof t?t:mt.getPath(t),s=e?lt.join2(t,e):t);var a=mt.getMode(n,o),u=mt.create(s,a);if(r){if("string"==typeof r){for(var f=new Array(r.length),l=0,c=r.length;l{var o=lt.join2("string"==typeof t?t:mt.getPath(t),e),i=mt.getMode(!!r,!!n);mt.createDevice.major||(mt.createDevice.major=64);var s=mt.makedev(mt.createDevice.major++,0);return mt.registerDevice(s,{open:t=>{t.seekable=!1},close:t=>{n&&n.buffer&&n.buffer.length&&n(10)},read:(t,e,n,o,i)=>{for(var s=0,a=0;a{for(var s=0;s{if(t.isDevice||t.isFolder||t.link||t.contents)return!0;if("undefined"!=typeof XMLHttpRequest)throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");if(!u)throw new Error("Cannot load without read() or XMLHttpRequest.");try{t.contents=At(u(t.url),!0),t.usedBytes=t.contents.length}catch(t){throw new mt.ErrnoError(29)}},createLazyFile:(t,e,r,n,o)=>{function i(){this.lengthKnown=!1,this.chunks=[]}if(i.prototype.get=function(t){if(!(t>this.length-1||t<0)){var e=t%this.chunkSize,r=t/this.chunkSize|0;return this.getter(r)[e]}},i.prototype.setDataGetter=function(t){this.getter=t},i.prototype.cacheLength=function(){var t=new XMLHttpRequest;if(t.open("HEAD",r,!1),t.send(null),!(t.status>=200&&t.status<300||304===t.status))throw new Error("Couldn\'t load "+r+". Status: "+t.status);var e,n=Number(t.getResponseHeader("Content-length")),o=(e=t.getResponseHeader("Accept-Ranges"))&&"bytes"===e,i=(e=t.getResponseHeader("Content-Encoding"))&&"gzip"===e,s=1048576;o||(s=n);var a=this;a.setDataGetter((t=>{var e=t*s,o=(t+1)*s-1;if(o=Math.min(o,n-1),void 0===a.chunks[t]&&(a.chunks[t]=((t,e)=>{if(t>e)throw new Error("invalid range ("+t+", "+e+") or no bytes requested!");if(e>n-1)throw new Error("only "+n+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",r,!1),n!==s&&o.setRequestHeader("Range","bytes="+t+"-"+e),"undefined"!=typeof Uint8Array&&(o.responseType="arraybuffer"),o.overrideMimeType&&o.overrideMimeType("text/plain; charset=x-user-defined"),o.send(null),!(o.status>=200&&o.status<300||304===o.status))throw new Error("Couldn\'t load "+r+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):At(o.responseText||"",!0)})(e,o)),void 0===a.chunks[t])throw new Error("doXHR failed!");return a.chunks[t]})),!i&&n||(s=n=1,n=this.getter(0).length,s=n,A("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=n,this._chunkSize=s,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!E)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var s=new i;Object.defineProperties(s,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var a={isDevice:!1,contents:s}}else a={isDevice:!1,url:r};var u=mt.createFile(t,e,a,n,o);a.contents?u.contents=a.contents:a.url&&(u.contents=null,u.url=a.url),Object.defineProperties(u,{usedBytes:{get:function(){return this.contents.length}}});var f={};return Object.keys(u.stream_ops).forEach((t=>{var e=u.stream_ops[t];f[t]=function(){return mt.forceLoadFile(u),e.apply(null,arguments)}})),f.read=(t,e,r,n,o)=>{mt.forceLoadFile(u);var i=t.node.contents;if(o>=i.length)return 0;var s=Math.min(i.length-o,n);if(i.slice)for(var a=0;a{var c=e?dt.resolve(lt.join2(t,e)):t;function d(r){function f(r){l&&l(),a||mt.createDataFile(t,e,r,n,o,u),i&&i(),Z()}Browser.handledByPreloadPlugin(r,c,f,(()=>{s&&s(),Z()}))||f(r)}V(),"string"==typeof r?function(t,e,r,n){var o=n?"":"al "+t;f(t,(function(r){r||J(\'Loading data file "\'+t+\'" failed (no arrayBuffer).\'),e(new Uint8Array(r)),o&&Z()}),(function(e){if(!r)throw\'Loading data file "\'+t+\'" failed.\';r()})),o&&V()}(r,(t=>d(t)),s):d(r)},indexedDB:()=>window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB,DB_NAME:()=>"EM_FS_"+window.location.pathname,DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:(t,e,r)=>{e=e||(()=>{}),r=r||(()=>{});var n=mt.indexedDB();try{var o=n.open(mt.DB_NAME(),mt.DB_VERSION)}catch(t){return r(t)}o.onupgradeneeded=()=>{A("creating db"),o.result.createObjectStore(mt.DB_STORE_NAME)},o.onsuccess=()=>{var n=o.result.transaction([mt.DB_STORE_NAME],"readwrite"),i=n.objectStore(mt.DB_STORE_NAME),s=0,a=0,u=t.length;function f(){0==a?e():r()}t.forEach((t=>{var e=i.put(mt.analyzePath(t).object.contents,t);e.onsuccess=()=>{++s+a==u&&f()},e.onerror=()=>{a++,s+a==u&&f()}})),n.onerror=r},o.onerror=r},loadFilesFromDB:(t,e,r)=>{e=e||(()=>{}),r=r||(()=>{});var n=mt.indexedDB();try{var o=n.open(mt.DB_NAME(),mt.DB_VERSION)}catch(t){return r(t)}o.onupgradeneeded=r,o.onsuccess=()=>{var n=o.result;try{var i=n.transaction([mt.DB_STORE_NAME],"readonly")}catch(t){return void r(t)}var s=i.objectStore(mt.DB_STORE_NAME),a=0,u=0,f=t.length;function l(){0==u?e():r()}t.forEach((t=>{var e=s.get(t);e.onsuccess=()=>{mt.analyzePath(t).exists&&mt.unlink(t),mt.createDataFile(lt.dirname(t),lt.basename(t),e.result,!0,!0,!0),++a+u==f&&l()},e.onerror=()=>{u++,a+u==f&&l()}})),i.onerror=r},o.onerror=r}},yt={mappings:{},DEFAULT_POLLMASK:5,calculateAt:function(t,e,r){if("/"===e[0])return e;var n;if(-100===t)n=mt.cwd();else{var o=mt.getStream(t);if(!o)throw new mt.ErrnoError(8);n=o.path}if(0==e.length){if(!r)throw new mt.ErrnoError(44);return n}return lt.join2(n,e)},doStat:function(t,e,r){try{var n=t(e)}catch(t){if(t&&t.node&<.normalize(e)!==lt.normalize(mt.getPath(t.node)))return-54;throw t}return I[r>>2]=n.dev,I[r+4>>2]=0,I[r+8>>2]=n.ino,I[r+12>>2]=n.mode,I[r+16>>2]=n.nlink,I[r+20>>2]=n.uid,I[r+24>>2]=n.gid,I[r+28>>2]=n.rdev,I[r+32>>2]=0,X=[n.size>>>0,(K=n.size,+Math.abs(K)>=1?K>0?(0|Math.min(+Math.floor(K/4294967296),4294967295))>>>0:~~+Math.ceil((K-+(~~K>>>0))/4294967296)>>>0:0)],I[r+40>>2]=X[0],I[r+44>>2]=X[1],I[r+48>>2]=4096,I[r+52>>2]=n.blocks,I[r+56>>2]=n.atime.getTime()/1e3|0,I[r+60>>2]=0,I[r+64>>2]=n.mtime.getTime()/1e3|0,I[r+68>>2]=0,I[r+72>>2]=n.ctime.getTime()/1e3|0,I[r+76>>2]=0,X=[n.ino>>>0,(K=n.ino,+Math.abs(K)>=1?K>0?(0|Math.min(+Math.floor(K/4294967296),4294967295))>>>0:~~+Math.ceil((K-+(~~K>>>0))/4294967296)>>>0:0)],I[r+80>>2]=X[0],I[r+84>>2]=X[1],0},doMsync:function(t,e,r,n,o){var i=D.slice(t,t+r);mt.msync(e,i,o,r,n)},doMkdir:function(t,e){return"/"===(t=lt.normalize(t))[t.length-1]&&(t=t.substr(0,t.length-1)),mt.mkdir(t,e,0),0},doMknod:function(t,e,r){switch(61440&e){case 32768:case 8192:case 24576:case 4096:case 49152:break;default:return-28}return mt.mknod(t,e,r),0},doReadlink:function(t,e,r){if(r<=0)return-28;var n=mt.readlink(t),o=Math.min(r,T(n)),i=M[e+o];return S(n,D,e,r+1),M[e+o]=i,o},doAccess:function(t,e){if(-8&e)return-28;var r=mt.lookupPath(t,{follow:!0}).node;if(!r)return-44;var n="";return 4&e&&(n+="r"),2&e&&(n+="w"),1&e&&(n+="x"),n&&mt.nodePermissions(r,n)?-2:0},doDup:function(t,e,r){var n=mt.getStream(r);return n&&mt.close(n),mt.open(t,e,0,r,r).fd},doReadv:function(t,e,r,n){for(var o=0,i=0;i>2],a=I[e+(8*i+4)>>2],u=mt.read(t,M,s,a,n);if(u<0)return-1;if(o+=u,u>2],a=I[e+(8*i+4)>>2],u=mt.write(t,M,s,a,n);if(u<0)return-1;o+=u}return o},varargs:void 0,get:function(){return yt.varargs+=4,I[yt.varargs-4>>2]},getStr:function(t){return H(t)},getStreamFromFD:function(t){var e=mt.getStream(t);if(!e)throw new mt.ErrnoError(8);return e},get64:function(t,e){return t}};function gt(t){return t%4==0&&(t%100!=0||t%400==0)}function wt(t,e){for(var r=0,n=0;n<=e;r+=t[n++]);return r}var Et=[31,29,31,30,31,30,31,31,30,31,30,31],vt=[31,28,31,30,31,30,31,31,30,31,30,31];function _t(t,e){for(var r=new Date(t.getTime());e>0;){var n=gt(r.getFullYear()),o=r.getMonth(),i=(n?Et:vt)[o];if(!(e>i-r.getDate()))return r.setDate(r.getDate()+e),r;e-=i-r.getDate()+1,r.setDate(1),o<11?r.setMonth(o+1):(r.setMonth(0),r.setFullYear(r.getFullYear()+1))}return r}var bt=function(t,e,r,n){t||(t=this),this.parent=t,this.mount=t.mount,this.mounted=null,this.id=mt.nextInode++,this.name=e,this.mode=r,this.node_ops={},this.stream_ops={},this.rdev=n};function At(t,e,r){var n=r>0?r:T(t)+1,o=new Array(n),i=S(t,o,0,o.length);return e&&(o.length=i),o}Object.defineProperties(bt.prototype,{read:{get:function(){return 365==(365&this.mode)},set:function(t){t?this.mode|=365:this.mode&=-366}},write:{get:function(){return 146==(146&this.mode)},set:function(t){t?this.mode|=146:this.mode&=-147}},isFolder:{get:function(){return mt.isDir(this.mode)}},isDevice:{get:function(){return mt.isChrdev(this.mode)}}}),mt.FSNode=bt,mt.staticInit();var kt,Pt={d:function(t){return Bt(t+16)+16},c:function(t,e,r){throw new st(t).init(e,r),t},f:function(t,e){J("To use dlopen, you need to use Emscripten\'s linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking")},i:function(t,e){J("To use dlopen, you need to use Emscripten\'s linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking")},a:function(){J("")},b:function(t,e){var r;if(0===t)r=Date.now();else{if(1!==t&&4!==t)return 28,I[Ft()>>2]=28,-1;r=nt()}return I[e>>2]=r/1e3|0,I[e+4>>2]=r%1e3*1e3*1e3|0,0},o:function(){return 2147483648},g:nt,h:function(t,e,r){D.copyWithin(t,e,e+r)},n:function(t){var e,r=D.length,n=2147483648;if((t>>>=0)>n)return!1;for(var o=1;o<=4;o*=2){var i=r*(1+.2/o);if(i=Math.min(i,t+100663296),at(Math.min(n,((e=Math.max(t,i))%65536>0&&(e+=65536-e%65536),e))))return!0}return!1},p:function(t,e){var r=0;return ft().forEach((function(n,o){var i=e+r;I[t+4*o>>2]=i,function(t,e,r){for(var n=0;n>0]=t.charCodeAt(n);M[e>>0]=0}(n,i),r+=n.length+1})),0},q:function(t,e){var r=ft();I[t>>2]=r.length;var n=0;return r.forEach((function(t){n+=t.length+1})),I[e>>2]=n,0},s:function(t){!function(t,e){var r;j(),r=t,j()||(s.onExit&&s.onExit(r),x=!0),g(r,new Dt(r))}(t)},j:function(t){try{var e=yt.getStreamFromFD(t);return mt.close(e),0}catch(t){if(void 0===mt||!(t instanceof mt.ErrnoError))throw t;return t.errno}},r:function(t,e,r,n){try{var o=yt.getStreamFromFD(t),i=yt.doReadv(o,e,r);return I[n>>2]=i,0}catch(t){if(void 0===mt||!(t instanceof mt.ErrnoError))throw t;return t.errno}},k:function(t,e,r,n,o){try{var i=yt.getStreamFromFD(t),s=4294967296*r+(e>>>0),a=9007199254740992;return s<=-a||s>=a?-61:(mt.llseek(i,s,n),X=[i.position>>>0,(K=i.position,+Math.abs(K)>=1?K>0?(0|Math.min(+Math.floor(K/4294967296),4294967295))>>>0:~~+Math.ceil((K-+(~~K>>>0))/4294967296)>>>0:0)],I[o>>2]=X[0],I[o+4>>2]=X[1],i.getdents&&0===s&&0===n&&(i.getdents=null),0)}catch(t){if(void 0===mt||!(t instanceof mt.ErrnoError))throw t;return t.errno}},e:function(t,e,r,n){try{var o=yt.getStreamFromFD(t),i=yt.doWritev(o,e,r);return I[n>>2]=i,0}catch(t){if(void 0===mt||!(t instanceof mt.ErrnoError))throw t;return t.errno}},l:function t(e,r){t.randomDevice||(t.randomDevice=ct());for(var n=0;n>0]=t.randomDevice();return 0},m:function(t,e,r,n){return function(t,e,r,n){var o=I[n+40>>2],i={tm_sec:I[n>>2],tm_min:I[n+4>>2],tm_hour:I[n+8>>2],tm_mday:I[n+12>>2],tm_mon:I[n+16>>2],tm_year:I[n+20>>2],tm_wday:I[n+24>>2],tm_yday:I[n+28>>2],tm_isdst:I[n+32>>2],tm_gmtoff:I[n+36>>2],tm_zone:o?H(o):""},s=H(r),a={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var u in a)s=s.replace(new RegExp(u,"g"),a[u]);var f=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],l=["January","February","March","April","May","June","July","August","September","October","November","December"];function c(t,e,r){for(var n="number"==typeof t?t.toString():t||"";n.length0?1:0}var n;return 0===(n=r(t.getFullYear()-e.getFullYear()))&&0===(n=r(t.getMonth()-e.getMonth()))&&(n=r(t.getDate()-e.getDate())),n}function p(t){switch(t.getDay()){case 0:return new Date(t.getFullYear()-1,11,29);case 1:return t;case 2:return new Date(t.getFullYear(),0,3);case 3:return new Date(t.getFullYear(),0,2);case 4:return new Date(t.getFullYear(),0,1);case 5:return new Date(t.getFullYear()-1,11,31);case 6:return new Date(t.getFullYear()-1,11,30)}}function m(t){var e=_t(new Date(t.tm_year+1900,0,1),t.tm_yday),r=new Date(e.getFullYear(),0,4),n=new Date(e.getFullYear()+1,0,4),o=p(r),i=p(n);return h(o,e)<=0?h(i,e)<=0?e.getFullYear()+1:e.getFullYear():e.getFullYear()-1}var y={"%a":function(t){return f[t.tm_wday].substring(0,3)},"%A":function(t){return f[t.tm_wday]},"%b":function(t){return l[t.tm_mon].substring(0,3)},"%B":function(t){return l[t.tm_mon]},"%C":function(t){return d((t.tm_year+1900)/100|0,2)},"%d":function(t){return d(t.tm_mday,2)},"%e":function(t){return c(t.tm_mday,2," ")},"%g":function(t){return m(t).toString().substring(2)},"%G":function(t){return m(t)},"%H":function(t){return d(t.tm_hour,2)},"%I":function(t){var e=t.tm_hour;return 0==e?e=12:e>12&&(e-=12),d(e,2)},"%j":function(t){return d(t.tm_mday+wt(gt(t.tm_year+1900)?Et:vt,t.tm_mon-1),3)},"%m":function(t){return d(t.tm_mon+1,2)},"%M":function(t){return d(t.tm_min,2)},"%n":function(){return"\\n"},"%p":function(t){return t.tm_hour>=0&&t.tm_hour<12?"AM":"PM"},"%S":function(t){return d(t.tm_sec,2)},"%t":function(){return"\\t"},"%u":function(t){return t.tm_wday||7},"%U":function(t){var e=new Date(t.tm_year+1900,0,1),r=0===e.getDay()?e:_t(e,7-e.getDay()),n=new Date(t.tm_year+1900,t.tm_mon,t.tm_mday);if(h(r,n)<0){var o=wt(gt(n.getFullYear())?Et:vt,n.getMonth()-1)-31,i=31-r.getDate()+o+n.getDate();return d(Math.ceil(i/7),2)}return 0===h(r,e)?"01":"00"},"%V":function(t){var e,r=new Date(t.tm_year+1900,0,4),n=new Date(t.tm_year+1901,0,4),o=p(r),i=p(n),s=_t(new Date(t.tm_year+1900,0,1),t.tm_yday);return h(s,o)<0?"53":h(i,s)<=0?"01":(e=o.getFullYear()=0;return e=(e=Math.abs(e)/60)/60*100+e%60,(r?"+":"-")+String("0000"+e).slice(-4)},"%Z":function(t){return t.tm_zone},"%%":function(){return"%"}};for(var u in y)s.includes(u)&&(s=s.replace(new RegExp(u,"g"),y[u](i)));var g=At(s,!1);return g.length>e?0:(function(t,e){M.set(t,e)}(g,t),g.length-1)}(t,e,r,n)}},Bt=(function(){var t={a:Pt};function e(t,e){var r,n=t.exports;s.asm=n,L((P=s.asm.t).buffer),U=s.asm.H,r=s.asm.u,N.unshift(r),Z()}function r(t){e(t.instance)}function n(e){return function(){if(!b&&(w||E)){if("function"==typeof fetch&&!tt(W))return fetch(W,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+W+"\'";return t.arrayBuffer()})).catch((function(){return et(W)}));if(f)return new Promise((function(t,e){f(W,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return et(W)}))}().then((function(e){return WebAssembly.instantiate(e,t)})).then((function(t){return t})).then(e,(function(t){k("failed to asynchronously prepare wasm: "+t),J(t)}))}if(V(),s.instantiateWasm)try{return s.instantiateWasm(t,e)}catch(t){return k("Module.instantiateWasm callback failed with error: "+t),!1}(b||"function"!=typeof WebAssembly.instantiateStreaming||Q(W)||tt(W)||"function"!=typeof fetch?n(r):fetch(W,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,t).then(r,(function(t){return k("wasm streaming compile failed: "+t),k("falling back to ArrayBuffer instantiation"),n(r)}))}))).catch(i)}(),s.___wasm_call_ctors=function(){return(s.___wasm_call_ctors=s.asm.u).apply(null,arguments)},s._initPoseDetectorModelBuffer=function(){return(s._initPoseDetectorModelBuffer=s.asm.v).apply(null,arguments)},s._getPoseDetectorModelBufferAddress=function(){return(s._getPoseDetectorModelBufferAddress=s.asm.w).apply(null,arguments)},s._loadPoseDetectorModel=function(){return(s._loadPoseDetectorModel=s.asm.x).apply(null,arguments)},s._initPoseLandmarkModelBuffer=function(){return(s._initPoseLandmarkModelBuffer=s.asm.y).apply(null,arguments)},s._getPoseLandmarkModelBufferAddress=function(){return(s._getPoseLandmarkModelBufferAddress=s.asm.z).apply(null,arguments)},s._loadPoseLandmarkModel=function(){return(s._loadPoseLandmarkModel=s.asm.A).apply(null,arguments)},s._initPoseInputBuffer=function(){return(s._initPoseInputBuffer=s.asm.B).apply(null,arguments)},s._getPoseInputBufferAddress=function(){return(s._getPoseInputBufferAddress=s.asm.C).apply(null,arguments)},s._getPoseOutputBufferAddress=function(){return(s._getPoseOutputBufferAddress=s.asm.D).apply(null,arguments)},s._getPoseTemporaryBufferAddress=function(){return(s._getPoseTemporaryBufferAddress=s.asm.E).apply(null,arguments)},s._execPose=function(){return(s._execPose=s.asm.F).apply(null,arguments)},s._set_pose_calculate_mode=function(){return(s._set_pose_calculate_mode=s.asm.G).apply(null,arguments)},s._initPalmDetectorModelBuffer=function(){return(s._initPalmDetectorModelBuffer=s.asm.I).apply(null,arguments)},s._getPalmDetectorModelBufferAddress=function(){return(s._getPalmDetectorModelBufferAddress=s.asm.J).apply(null,arguments)},s._loadPalmDetectorModel=function(){return(s._loadPalmDetectorModel=s.asm.K).apply(null,arguments)},s._initHandLandmarkModelBuffer=function(){return(s._initHandLandmarkModelBuffer=s.asm.L).apply(null,arguments)},s._getHandLandmarkModelBufferAddress=function(){return(s._getHandLandmarkModelBufferAddress=s.asm.M).apply(null,arguments)},s._loadHandLandmarkModel=function(){return(s._loadHandLandmarkModel=s.asm.N).apply(null,arguments)},s._initHandInputBuffer=function(){return(s._initHandInputBuffer=s.asm.O).apply(null,arguments)},s._getHandInputBufferAddress=function(){return(s._getHandInputBufferAddress=s.asm.P).apply(null,arguments)},s._getHandOutputBufferAddress=function(){return(s._getHandOutputBufferAddress=s.asm.Q).apply(null,arguments)},s._getHandTemporaryBufferAddress=function(){return(s._getHandTemporaryBufferAddress=s.asm.R).apply(null,arguments)},s._execHand=function(){return(s._execHand=s.asm.S).apply(null,arguments)},s._initFaceDetectorModelBuffer=function(){return(s._initFaceDetectorModelBuffer=s.asm.T).apply(null,arguments)},s._getFaceDetectorModelBufferAddress=function(){return(s._getFaceDetectorModelBufferAddress=s.asm.U).apply(null,arguments)},s._loadFaceDetectorModel=function(){return(s._loadFaceDetectorModel=s.asm.V).apply(null,arguments)},s._initFaceLandmarkModelBuffer=function(){return(s._initFaceLandmarkModelBuffer=s.asm.W).apply(null,arguments)},s._getFaceLandmarkModelBufferAddress=function(){return(s._getFaceLandmarkModelBufferAddress=s.asm.X).apply(null,arguments)},s._loadFaceLandmarkModel=function(){return(s._loadFaceLandmarkModel=s.asm.Y).apply(null,arguments)},s._initFaceInputBuffer=function(){return(s._initFaceInputBuffer=s.asm.Z).apply(null,arguments)},s._getFaceInputBufferAddress=function(){return(s._getFaceInputBufferAddress=s.asm._).apply(null,arguments)},s._getFaceOutputBufferAddress=function(){return(s._getFaceOutputBufferAddress=s.asm.$).apply(null,arguments)},s._getFaceTemporaryBufferAddress=function(){return(s._getFaceTemporaryBufferAddress=s.asm.aa).apply(null,arguments)},s._execFace=function(){return(s._execFace=s.asm.ba).apply(null,arguments)},s._malloc=function(){return(Bt=s._malloc=s.asm.ca).apply(null,arguments)}),Ft=s.___errno_location=function(){return(Ft=s.___errno_location=s.asm.da).apply(null,arguments)},Mt=s._memalign=function(){return(Mt=s._memalign=s.asm.ea).apply(null,arguments)};function Dt(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function It(t){function r(){kt||(kt=!0,s.calledRun=!0,x||(s.noFSInit||mt.init.initialized||mt.init(),mt.ignorePermissions=!1,ht.init(),rt(N),e(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),function(){if(s.postRun)for("function"==typeof s.postRun&&(s.postRun=[s.postRun]);s.postRun.length;)t=s.postRun.shift(),z.unshift(t);var t;rt(z)}()))}t=t||m,$>0||(function(){if(s.preRun)for("function"==typeof s.preRun&&(s.preRun=[s.preRun]);s.preRun.length;)t=s.preRun.shift(),C.unshift(t);var t;rt(C)}(),$>0||(s.setStatus?(s.setStatus("Running..."),setTimeout((function(){setTimeout((function(){s.setStatus("")}),1),r()}),1)):r()))}if(G=function t(){kt||It(),kt||(G=t)},s.run=It,s.preInit)for("function"==typeof s.preInit&&(s.preInit=[s.preInit]);s.preInit.length>0;)s.preInit.pop()();return It(),t.ready});t.exports=i},782:()=>{},384:()=>{},375:()=>{}},e={};function r(n){var o=e[n];if(void 0!==o)return o.exports;var i=e[n]={exports:{}};return t[n].call(i.exports,i,i.exports,r),i.exports}(()=>{"use strict";var t=r(55);const e={lips:[61,146,91,181,84,17,314,405,321,375,291,185,40,39,37,0,267,269,270,409,78,95,88,178,87,14,317,402,318,324,308,191,80,81,82,13,312,311,310,415,76,77,90,180,85,16,315,404,320,307,306,184,74,73,72,11,302,303,304,408,62,96,89,179,86,15,316,403,319,325,292,183,42,41,38,12,268,271,272,407],leftEye:[33,7,163,144,145,153,154,155,133,246,161,160,159,158,157,173,130,25,110,24,23,22,26,112,243,247,30,29,27,28,56,190,226,31,228,229,230,231,232,233,244,113,225,224,223,222,221,189,35,124,46,53,52,65,143,111,117,118,119,120,121,128,245,156,70,63,105,66,107,55,193],rightEye:[263,249,390,373,374,380,381,382,362,466,388,387,386,385,384,398,359,255,339,254,253,252,256,341,463,467,260,259,257,258,286,414,446,261,448,449,450,451,452,453,464,342,445,444,443,442,441,413,265,353,276,283,282,295,372,340,346,347,348,349,350,357,465,383,300,293,334,296,336,285,417],leftIris:[468,469,470,471,472],rightIris:[473,474,475,476,477]};class n extends t.ImageProcessor{constructor(){super(...arguments),this.tflite=null,this.tfliteHandInputAddress=0,this.tfliteHandOutputAddress=0,this.tfliteFaceInputAddress=0,this.tfliteFaceOutputAddress=0,this.tflitePoseInputAddress=0,this.tflitePoseOutputAddress=0,this.init=async e=>{if(e.browserType!==t.BrowserTypes.SAFARI){const t=r(503);this.tflite=await t({wasmBinary:e.wasmBin})}else console.error("This module use wasm-simd. Safari is not supported.");const n=e.palmDetectorModelTFLites[e.handModelKey];this.tflite._initPalmDetectorModelBuffer(n.byteLength);const o=this.tflite._getPalmDetectorModelBufferAddress();this.tflite.HEAPU8.set(new Uint8Array(n),o),this.tflite._loadPalmDetectorModel(n.byteLength);const i=e.handLandmarkModelTFLites[e.handModelKey];this.tflite._initHandLandmarkModelBuffer(i.byteLength);const s=this.tflite._getHandLandmarkModelBufferAddress();this.tflite.HEAPU8.set(new Uint8Array(i),s),this.tflite._loadHandLandmarkModel(i.byteLength),this.tflite._initHandInputBuffer(e.maxProcessWidth,e.maxProcessHeight,4),this.tfliteHandInputAddress=this.tflite._getHandInputBufferAddress(),this.tfliteHandOutputAddress=this.tflite._getHandOutputBufferAddress(),console.log("Hand model is loaded successfully.",e);const a=e.faceDetectorModelTFLites[e.faceModelKey];this.tflite._initFaceDetectorModelBuffer(a.byteLength);const u=this.tflite._getFaceDetectorModelBufferAddress();this.tflite.HEAPU8.set(new Uint8Array(a),u),this.tflite._loadFaceDetectorModel(a.byteLength);const f=e.faceLandmarkModelTFLites[e.faceModelKey];this.tflite._initFaceLandmarkModelBuffer(f.byteLength);const l=this.tflite._getFaceLandmarkModelBufferAddress();this.tflite.HEAPU8.set(new Uint8Array(f),l),this.tflite._loadFaceLandmarkModel(f.byteLength),this.tflite._initFaceInputBuffer(e.maxProcessWidth,e.maxProcessHeight,4),this.tfliteFaceInputAddress=this.tflite._getFaceInputBufferAddress(),this.tfliteFaceOutputAddress=this.tflite._getFaceOutputBufferAddress(),console.log("Face model is loaded successfully.",e);const c=e.poseDetectorModelTFLites[e.poseModelKey];this.tflite._initPoseDetectorModelBuffer(c.byteLength);const d=this.tflite._getPoseDetectorModelBufferAddress();this.tflite.HEAPU8.set(new Uint8Array(c),d),this.tflite._loadPoseDetectorModel(c.byteLength);const h=e.poseLandmarkModelTFLites[e.poseModelKey];this.tflite._initPoseLandmarkModelBuffer(h.byteLength);const p=this.tflite._getPoseLandmarkModelBufferAddress();this.tflite.HEAPU8.set(new Uint8Array(h),p),this.tflite._loadPoseLandmarkModel(h.byteLength),this.tflite._initPoseInputBuffer(e.maxProcessWidth,e.maxProcessHeight,4),this.tflitePoseInputAddress=this.tflite._getPoseInputBufferAddress(),this.tflitePoseOutputAddress=this.tflite._getPoseOutputBufferAddress(),console.log("Pose model is loaded successfully.",e)},this.predict=async(t,e,r)=>"hand"===e.operationType?this.predictHand(t,e,r):"face"===e.operationType?this.predictFace(t,e,r):"pose"===e.operationType?this.predictPose(t,e,r):null,this.predictHand=async(t,e,r)=>{const n=new ImageData(r,e.handProcessWidth,e.handProcessHeight);this.tflite.HEAPU8.set(n.data,this.tfliteHandInputAddress),this.tflite._execHand(e.handProcessWidth,e.handProcessHeight,e.handMaxHands,e.handAffineResizedFactor);const o=this.tflite.HEAPF32[this.tfliteHandOutputAddress/4],i=[];for(let t=0;t({keypoints:[...t.landmarkKeypoints],handedness:t.handedness<.5?"Left":"Right",score:t.score})))},this.predictFace=async(t,r,n)=>{const o=new ImageData(n,r.faceProcessWidth,r.faceProcessHeight);this.tflite.HEAPU8.set(o.data,this.tfliteFaceInputAddress),this.tflite._execFace(r.faceProcessWidth,r.faceProcessHeight,r.faceMaxFaces);const i=this.tflite.HEAPF32[this.tfliteFaceOutputAddress/4],s=[];for(let t=0;t.5&&r.landmarkScore>.5&&s.push(r)}return s.map((t=>{const r={keypoints:[...t.landmarkKeypoints],box:{xMin:t.face.minX,yMin:t.face.minY,xMax:t.face.maxX,yMax:t.face.maxY,width:t.face.maxX-t.face.minX,height:t.face.maxY-t.face.maxY}};return e.lips.forEach(((e,n)=>{r.keypoints[e].x=t.landmarkLipsKeypoints[n].x,r.keypoints[e].y=t.landmarkLipsKeypoints[n].y})),e.leftEye.forEach(((e,n)=>{r.keypoints[e].x=t.landmarkLeftEyeKeypoints[n].x,r.keypoints[e].y=t.landmarkLeftEyeKeypoints[n].y})),e.rightEye.forEach(((e,n)=>{r.keypoints[e].x=t.landmarkRightEyeKeypoints[n].x,r.keypoints[e].y=t.landmarkRightEyeKeypoints[n].y})),e.leftIris.forEach(((e,n)=>{r.keypoints[e]=t.landmarkLeftIrisKeypoints[n]})),e.rightIris.forEach(((e,n)=>{r.keypoints[e]=t.landmarkRightIrisKeypoints[n]})),r}))},this.predictPose=async(t,e,r)=>{const n=new ImageData(r,e.poseProcessWidth,e.poseProcessHeight);this.tflite.HEAPU8.set(n.data,this.tflitePoseInputAddress),this.tflite._set_pose_calculate_mode(e.poseCalculateMode),this.tflite._execPose(e.poseProcessWidth,e.poseProcessHeight,e.poseMaxPoses,e.poseAffineResizedFactor,e.poseCropExt);const o=this.tflite.HEAPF32[this.tflitePoseOutputAddress/4],i=[];for(let t=0;t.1&&r.landmarkScore>0&&i.push(r)}return i.map((t=>({keypoints:[...t.landmarkKeypoints],keypoints3D:[...t.landmarkKeypoints3D],box:{xMin:t.pose.minX,yMin:t.pose.minY,xMax:t.pose.maxX,yMax:t.pose.maxY,width:t.pose.maxX-t.pose.minX,height:t.pose.maxY-t.pose.maxY}})))}}}const o=self,i=new t.WorkerDispatcher(o),s={init:async t=>{const e=new n;return await e.init(t),e}};i.setCallback(s),onmessage=i.dispach})()})();',"Worker",void 0,void 0)}const l=468,u=[127,34,139,11,0,37,232,231,120,72,37,39,128,121,47,232,121,128,104,69,67,175,171,148,157,154,155,118,50,101,73,39,40,9,151,108,48,115,131,194,204,211,74,40,185,80,42,183,40,92,186,230,229,118,202,212,214,83,18,17,76,61,146,160,29,30,56,157,173,106,204,194,135,214,192,203,165,98,21,71,68,51,45,4,144,24,23,77,146,91,205,50,187,201,200,18,91,106,182,90,91,181,85,84,17,206,203,36,148,171,140,92,40,39,193,189,244,159,158,28,247,246,161,236,3,196,54,68,104,193,168,8,117,228,31,189,193,55,98,97,99,126,47,100,166,79,218,155,154,26,209,49,131,135,136,150,47,126,217,223,52,53,45,51,134,211,170,140,67,69,108,43,106,91,230,119,120,226,130,247,63,53,52,238,20,242,46,70,156,78,62,96,46,53,63,143,34,227,173,155,133,123,117,111,44,125,19,236,134,51,216,206,205,154,153,22,39,37,167,200,201,208,36,142,100,57,212,202,20,60,99,28,158,157,35,226,113,160,159,27,204,202,210,113,225,46,43,202,204,62,76,77,137,123,116,41,38,72,203,129,142,64,98,240,49,102,64,41,73,74,212,216,207,42,74,184,169,170,211,170,149,176,105,66,69,122,6,168,123,147,187,96,77,90,65,55,107,89,90,180,101,100,120,63,105,104,93,137,227,15,86,85,129,102,49,14,87,86,55,8,9,100,47,121,145,23,22,88,89,179,6,122,196,88,95,96,138,172,136,215,58,172,115,48,219,42,80,81,195,3,51,43,146,61,171,175,199,81,82,38,53,46,225,144,163,110,246,33,7,52,65,66,229,228,117,34,127,234,107,108,69,109,108,151,48,64,235,62,78,191,129,209,126,111,35,143,163,161,246,117,123,50,222,65,52,19,125,141,221,55,65,3,195,197,25,7,33,220,237,44,70,71,139,122,193,245,247,130,33,71,21,162,153,158,159,170,169,150,188,174,196,216,186,92,144,160,161,2,97,167,141,125,241,164,167,37,72,38,12,145,159,160,38,82,13,63,68,71,226,35,111,158,153,154,101,50,205,206,92,165,209,198,217,165,167,97,220,115,218,133,112,243,239,238,241,214,135,169,190,173,133,171,208,32,125,44,237,86,87,178,85,86,179,84,85,180,83,84,181,201,83,182,137,93,132,76,62,183,61,76,184,57,61,185,212,57,186,214,207,187,34,143,156,79,239,237,123,137,177,44,1,4,201,194,32,64,102,129,213,215,138,59,166,219,242,99,97,2,94,141,75,59,235,24,110,228,25,130,226,23,24,229,22,23,230,26,22,231,112,26,232,189,190,243,221,56,190,28,56,221,27,28,222,29,27,223,30,29,224,247,30,225,238,79,20,166,59,75,60,75,240,147,177,215,20,79,166,187,147,213,112,233,244,233,128,245,128,114,188,114,217,174,131,115,220,217,198,236,198,131,134,177,132,58,143,35,124,110,163,7,228,110,25,356,389,368,11,302,267,452,350,349,302,303,269,357,343,277,452,453,357,333,332,297,175,152,377,384,398,382,347,348,330,303,304,270,9,336,337,278,279,360,418,262,431,304,408,409,310,415,407,270,409,410,450,348,347,422,430,434,313,314,17,306,307,375,387,388,260,286,414,398,335,406,418,364,367,416,423,358,327,251,284,298,281,5,4,373,374,253,307,320,321,425,427,411,421,313,18,321,405,406,320,404,405,315,16,17,426,425,266,377,400,369,322,391,269,417,465,464,386,257,258,466,260,388,456,399,419,284,332,333,417,285,8,346,340,261,413,441,285,327,460,328,355,371,329,392,439,438,382,341,256,429,420,360,364,394,379,277,343,437,443,444,283,275,440,363,431,262,369,297,338,337,273,375,321,450,451,349,446,342,467,293,334,282,458,461,462,276,353,383,308,324,325,276,300,293,372,345,447,382,398,362,352,345,340,274,1,19,456,248,281,436,427,425,381,256,252,269,391,393,200,199,428,266,330,329,287,273,422,250,462,328,258,286,384,265,353,342,387,259,257,424,431,430,342,353,276,273,335,424,292,325,307,366,447,345,271,303,302,423,266,371,294,455,460,279,278,294,271,272,304,432,434,427,272,407,408,394,430,431,395,369,400,334,333,299,351,417,168,352,280,411,325,319,320,295,296,336,319,403,404,330,348,349,293,298,333,323,454,447,15,16,315,358,429,279,14,15,316,285,336,9,329,349,350,374,380,252,318,402,403,6,197,419,318,319,325,367,364,365,435,367,397,344,438,439,272,271,311,195,5,281,273,287,291,396,428,199,311,271,268,283,444,445,373,254,339,263,466,249,282,334,296,449,347,346,264,447,454,336,296,299,338,10,151,278,439,455,292,407,415,358,371,355,340,345,372,390,249,466,346,347,280,442,443,282,19,94,370,441,442,295,248,419,197,263,255,359,440,275,274,300,383,368,351,412,465,263,467,466,301,368,389,380,374,386,395,378,379,412,351,419,436,426,322,373,390,388,2,164,393,370,462,461,164,0,267,302,11,12,374,373,387,268,12,13,293,300,301,446,261,340,385,384,381,330,266,425,426,423,391,429,355,437,391,327,326,440,457,438,341,382,362,459,457,461,434,430,394,414,463,362,396,369,262,354,461,457,316,403,402,315,404,403,314,405,404,313,406,405,421,418,406,366,401,361,306,408,407,291,409,408,287,410,409,432,436,410,434,416,411,264,368,383,309,438,457,352,376,401,274,275,4,421,428,262,294,327,358,433,416,367,289,455,439,462,370,326,2,326,370,305,460,455,254,449,448,255,261,446,253,450,449,252,451,450,256,452,451,341,453,452,413,464,463,441,413,414,258,442,441,257,443,442,259,444,443,260,445,444,467,342,445,459,458,250,289,392,290,290,328,460,376,433,435,250,290,392,411,416,433,341,463,464,453,464,465,357,465,412,343,412,399,360,363,440,437,399,456,420,456,363,401,435,288,372,383,353,339,255,249,448,261,255,133,243,190,133,155,112,33,246,247,33,130,25,398,384,286,362,398,414,362,463,341,263,359,467,263,249,255,466,467,260,75,60,166,238,239,79,162,127,139,72,11,37,121,232,120,73,72,39,114,128,47,233,232,128,103,104,67,152,175,148,173,157,155,119,118,101,74,73,40,107,9,108,49,48,131,32,194,211,184,74,185,191,80,183,185,40,186,119,230,118,210,202,214,84,83,17,77,76,146,161,160,30,190,56,173,182,106,194,138,135,192,129,203,98,54,21,68,5,51,4,145,144,23,90,77,91,207,205,187,83,201,18,181,91,182,180,90,181,16,85,17,205,206,36,176,148,140,165,92,39,245,193,244,27,159,28,30,247,161,174,236,196,103,54,104,55,193,8,111,117,31,221,189,55,240,98,99,142,126,100,219,166,218,112,155,26,198,209,131,169,135,150,114,47,217,224,223,53,220,45,134,32,211,140,109,67,108,146,43,91,231,230,120,113,226,247,105,63,52,241,238,242,124,46,156,95,78,96,70,46,63,116,143,227,116,123,111,1,44,19,3,236,51,207,216,205,26,154,22,165,39,167,199,200,208,101,36,100,43,57,202,242,20,99,56,28,157,124,35,113,29,160,27,211,204,210,124,113,46,106,43,204,96,62,77,227,137,116,73,41,72,36,203,142,235,64,240,48,49,64,42,41,74,214,212,207,183,42,184,210,169,211,140,170,176,104,105,69,193,122,168,50,123,187,89,96,90,66,65,107,179,89,180,119,101,120,68,63,104,234,93,227,16,15,85,209,129,49,15,14,86,107,55,9,120,100,121,153,145,22,178,88,179,197,6,196,89,88,96,135,138,136,138,215,172,218,115,219,41,42,81,5,195,51,57,43,61,208,171,199,41,81,38,224,53,225,24,144,110,105,52,66,118,229,117,227,34,234,66,107,69,10,109,151,219,48,235,183,62,191,142,129,126,116,111,143,7,163,246,118,117,50,223,222,52,94,19,141,222,221,65,196,3,197,45,220,44,156,70,139,188,122,245,139,71,162,145,153,159,149,170,150,122,188,196,206,216,92,163,144,161,164,2,167,242,141,241,0,164,37,11,72,12,144,145,160,12,38,13,70,63,71,31,226,111,157,158,154,36,101,205,203,206,165,126,209,217,98,165,97,237,220,218,237,239,241,210,214,169,140,171,32,241,125,237,179,86,178,180,85,179,181,84,180,182,83,181,194,201,182,177,137,132,184,76,183,185,61,184,186,57,185,216,212,186,192,214,187,139,34,156,218,79,237,147,123,177,45,44,4,208,201,32,98,64,129,192,213,138,235,59,219,141,242,97,97,2,141,240,75,235,229,24,228,31,25,226,230,23,229,231,22,230,232,26,231,233,112,232,244,189,243,189,221,190,222,28,221,223,27,222,224,29,223,225,30,224,113,247,225,99,60,240,213,147,215,60,20,166,192,187,213,243,112,244,244,233,245,245,128,188,188,114,174,134,131,220,174,217,236,236,198,134,215,177,58,156,143,124,25,110,7,31,228,25,264,356,368,0,11,267,451,452,349,267,302,269,350,357,277,350,452,357,299,333,297,396,175,377,381,384,382,280,347,330,269,303,270,151,9,337,344,278,360,424,418,431,270,304,409,272,310,407,322,270,410,449,450,347,432,422,434,18,313,17,291,306,375,259,387,260,424,335,418,434,364,416,391,423,327,301,251,298,275,281,4,254,373,253,375,307,321,280,425,411,200,421,18,335,321,406,321,320,405,314,315,17,423,426,266,396,377,369,270,322,269,413,417,464,385,386,258,248,456,419,298,284,333,168,417,8,448,346,261,417,413,285,326,327,328,277,355,329,309,392,438,381,382,256,279,429,360,365,364,379,355,277,437,282,443,283,281,275,363,395,431,369,299,297,337,335,273,321,348,450,349,359,446,467,283,293,282,250,458,462,300,276,383,292,308,325,283,276,293,264,372,447,346,352,340,354,274,19,363,456,281,426,436,425,380,381,252,267,269,393,421,200,428,371,266,329,432,287,422,290,250,328,385,258,384,446,265,342,386,387,257,422,424,430,445,342,276,422,273,424,306,292,307,352,366,345,268,271,302,358,423,371,327,294,460,331,279,294,303,271,304,436,432,427,304,272,408,395,394,431,378,395,400,296,334,299,6,351,168,376,352,411,307,325,320,285,295,336,320,319,404,329,330,349,334,293,333,366,323,447,316,15,315,331,358,279,317,14,316,8,285,9,277,329,350,253,374,252,319,318,403,351,6,419,324,318,325,397,367,365,288,435,397,278,344,439,310,272,311,248,195,281,375,273,291,175,396,199,312,311,268,276,283,445,390,373,339,295,282,296,448,449,346,356,264,454,337,336,299,337,338,151,294,278,455,308,292,415,429,358,355,265,340,372,388,390,466,352,346,280,295,442,282,354,19,370,285,441,295,195,248,197,457,440,274,301,300,368,417,351,465,251,301,389,385,380,386,394,395,379,399,412,419,410,436,322,387,373,388,326,2,393,354,370,461,393,164,267,268,302,12,386,374,387,312,268,13,298,293,301,265,446,340,380,385,381,280,330,425,322,426,391,420,429,437,393,391,326,344,440,438,458,459,461,364,434,394,428,396,262,274,354,457,317,316,402,316,315,403,315,314,404,314,313,405,313,421,406,323,366,361,292,306,407,306,291,408,291,287,409,287,432,410,427,434,411,372,264,383,459,309,457,366,352,401,1,274,4,418,421,262,331,294,358,435,433,367,392,289,439,328,462,326,94,2,370,289,305,455,339,254,448,359,255,446,254,253,449,253,252,450,252,256,451,256,341,452,414,413,463,286,441,414,286,258,441,258,257,442,257,259,443,259,260,444,260,467,445,309,459,250,305,289,290,305,290,460,401,376,435,309,250,392,376,411,433,453,341,464,357,453,465,343,357,412,437,343,399,344,360,440,420,437,456,360,420,363,361,401,288,265,372,353,390,339,249,339,448,255],d=[61,146,91,181,84,17,314,405,321,375,291,185,40,39,37,0,267,269,270,409,78,95,88,178,87,14,317,402,318,324,308,191,80,81,82,13,312,311,310,415,76,77,90,180,85,16,315,404,320,307,306,184,74,73,72,11,302,303,304,408,62,96,89,179,86,15,316,403,319,325,292,183,42,41,38,12,268,271,272,407],h=[33,7,163,144,145,153,154,155,133,246,161,160,159,158,157,173,130,25,110,24,23,22,26,112,243,247,30,29,27,28,56,190,226,31,228,229,230,231,232,233,244,113,225,224,223,222,221,189,35,124,46,53,52,65,143,111,117,118,119,120,121,128,245,156,70,63,105,66,107,55,193],f=[263,249,390,373,374,380,381,382,362,466,388,387,386,385,384,398,359,255,339,254,253,252,256,341,463,467,260,259,257,258,286,414,446,261,448,449,450,451,452,453,464,342,445,444,443,442,441,413,265,353,276,283,282,295,372,340,346,347,348,349,350,357,465,383,300,293,334,296,336,285,417],p=[468,469,470,471,472],m=[473,474,475,476,477],g={lips:d,leftEye:h,rightEye:f,leftIris:p,rightIris:m};class C extends e.ImageProcessor{constructor(){super(...arguments),this.tflite=null,this.tfliteHandInputAddress=0,this.tfliteHandOutputAddress=0,this.tfliteFaceInputAddress=0,this.tfliteFaceOutputAddress=0,this.tflitePoseInputAddress=0,this.tflitePoseOutputAddress=0,this.init=async t=>{if(t.browserType!==e.BrowserTypes.SAFARI){const e=i(503);this.tflite=await e({wasmBinary:t.wasmBin})}else console.error("This module use wasm-simd. Safari is not supported.");const n=t.palmDetectorModelTFLites[t.handModelKey];this.tflite._initPalmDetectorModelBuffer(n.byteLength);const r=this.tflite._getPalmDetectorModelBufferAddress();this.tflite.HEAPU8.set(new Uint8Array(n),r),this.tflite._loadPalmDetectorModel(n.byteLength);const a=t.handLandmarkModelTFLites[t.handModelKey];this.tflite._initHandLandmarkModelBuffer(a.byteLength);const o=this.tflite._getHandLandmarkModelBufferAddress();this.tflite.HEAPU8.set(new Uint8Array(a),o),this.tflite._loadHandLandmarkModel(a.byteLength),this.tflite._initHandInputBuffer(t.maxProcessWidth,t.maxProcessHeight,4),this.tfliteHandInputAddress=this.tflite._getHandInputBufferAddress(),this.tfliteHandOutputAddress=this.tflite._getHandOutputBufferAddress(),console.log("Hand model is loaded successfully.",t);const s=t.faceDetectorModelTFLites[t.faceModelKey];this.tflite._initFaceDetectorModelBuffer(s.byteLength);const c=this.tflite._getFaceDetectorModelBufferAddress();this.tflite.HEAPU8.set(new Uint8Array(s),c),this.tflite._loadFaceDetectorModel(s.byteLength);const l=t.faceLandmarkModelTFLites[t.faceModelKey];this.tflite._initFaceLandmarkModelBuffer(l.byteLength);const u=this.tflite._getFaceLandmarkModelBufferAddress();this.tflite.HEAPU8.set(new Uint8Array(l),u),this.tflite._loadFaceLandmarkModel(l.byteLength),this.tflite._initFaceInputBuffer(t.maxProcessWidth,t.maxProcessHeight,4),this.tfliteFaceInputAddress=this.tflite._getFaceInputBufferAddress(),this.tfliteFaceOutputAddress=this.tflite._getFaceOutputBufferAddress(),console.log("Face model is loaded successfully.",t);const d=t.poseDetectorModelTFLites[t.poseModelKey];this.tflite._initPoseDetectorModelBuffer(d.byteLength);const h=this.tflite._getPoseDetectorModelBufferAddress();this.tflite.HEAPU8.set(new Uint8Array(d),h),this.tflite._loadPoseDetectorModel(d.byteLength);const f=t.poseLandmarkModelTFLites[t.poseModelKey];this.tflite._initPoseLandmarkModelBuffer(f.byteLength);const p=this.tflite._getPoseLandmarkModelBufferAddress();this.tflite.HEAPU8.set(new Uint8Array(f),p),this.tflite._loadPoseLandmarkModel(f.byteLength),this.tflite._initPoseInputBuffer(t.maxProcessWidth,t.maxProcessHeight,4),this.tflitePoseInputAddress=this.tflite._getPoseInputBufferAddress(),this.tflitePoseOutputAddress=this.tflite._getPoseOutputBufferAddress(),console.log("Pose model is loaded successfully.",t)},this.predict=async(e,n,i)=>n.operationType===t.hand?this.predictHand(e,n,i):n.operationType===t.face?this.predictFace(e,n,i):n.operationType===t.pose?this.predictPose(e,n,i):null,this.predictHand=async(e,t,n)=>{const i=new ImageData(n,t.handProcessWidth,t.handProcessHeight);this.tflite.HEAPU8.set(i.data,this.tfliteHandInputAddress),this.tflite._execHand(t.handProcessWidth,t.handProcessHeight,t.handMaxHands,t.handAffineResizedFactor);const r=this.tflite.HEAPF32[this.tfliteHandOutputAddress/4],a=[];for(let e=0;e({keypoints:[...e.landmarkKeypoints],handedness:e.handedness<.5?"Left":"Right",score:e.score})))},this.predictFace=async(e,t,n)=>{const i=new ImageData(n,t.faceProcessWidth,t.faceProcessHeight);this.tflite.HEAPU8.set(i.data,this.tfliteFaceInputAddress),this.tflite._execFace(t.faceProcessWidth,t.faceProcessHeight,t.faceMaxFaces);const r=this.tflite.HEAPF32[this.tfliteFaceOutputAddress/4],a=[];for(let e=0;e.5&&n.landmarkScore>.5&&a.push(n)}return a.map((e=>{const t={keypoints:[...e.landmarkKeypoints],box:{xMin:e.face.minX,yMin:e.face.minY,xMax:e.face.maxX,yMax:e.face.maxY,width:e.face.maxX-e.face.minX,height:e.face.maxY-e.face.maxY}};return g.lips.forEach(((n,i)=>{t.keypoints[n].x=e.landmarkLipsKeypoints[i].x,t.keypoints[n].y=e.landmarkLipsKeypoints[i].y})),g.leftEye.forEach(((n,i)=>{t.keypoints[n].x=e.landmarkLeftEyeKeypoints[i].x,t.keypoints[n].y=e.landmarkLeftEyeKeypoints[i].y})),g.rightEye.forEach(((n,i)=>{t.keypoints[n].x=e.landmarkRightEyeKeypoints[i].x,t.keypoints[n].y=e.landmarkRightEyeKeypoints[i].y})),g.leftIris.forEach(((n,i)=>{t.keypoints[n]=e.landmarkLeftIrisKeypoints[i]})),g.rightIris.forEach(((n,i)=>{t.keypoints[n]=e.landmarkRightIrisKeypoints[i]})),t}))},this.predictPose=async(e,t,n)=>{const i=new ImageData(n,t.poseProcessWidth,t.poseProcessHeight);this.tflite.HEAPU8.set(i.data,this.tflitePoseInputAddress),this.tflite._set_pose_calculate_mode(t.poseCalculateMode),this.tflite._execPose(t.poseProcessWidth,t.poseProcessHeight,t.poseMaxPoses,t.poseAffineResizedFactor,t.poseCropExt);const r=this.tflite.HEAPF32[this.tflitePoseOutputAddress/4],a=[];for(let e=0;e.1&&n.landmarkScore>0&&a.push(n)}return a.map((e=>({keypoints:[...e.landmarkKeypoints],keypoints3D:[...e.landmarkKeypoints3D],box:{xMin:e.pose.minX,yMin:e.pose.minY,xMax:e.pose.maxX,yMax:e.pose.maxY,width:e.pose.maxX-e.pose.minX,height:e.pose.maxY-e.pose.maxY}})))}}}class v extends e.WorkerManagerBase{constructor(){super(...arguments),this.imageProcessor=new C,this.config=null,this.generateDefaultConfig=async t=>{const n=t?.wasmUrl||i(81),r=this.fetchData(n),a=t?.palmDetectorModelTFLiteUrl||i(102),o=this.fetchData(a),s=t?.handLandmarkLiteTFLiteUrl||i(583),c=this.fetchData(s),l=t?.faceDetectorModelTFLiteUrl||i(363),u=this.fetchData(l),d=t?.faceLandmarkModelTFLiteUrl||i(180),h=this.fetchData(d),f=t?.poseDetectorModelTFLiteUrl||i(914),p=this.fetchData(f),m=t?.poseLandmarkModelTFLiteUrl||i(747),g=this.fetchData(m),[C,v,y,b,M,x,_]=await Promise.all([r,o,c,u,h,p,g]);return{browserType:(0,e.getBrowserType)(),processOnLocal:!0,pageUrl:window.location.href,wasmBin:C,palmDetectorModelTFLites:{lite:v},handLandmarkModelTFLites:{lite:y},handModelKey:"lite",faceDetectorModelTFLites:{lite:b},faceLandmarkModelTFLites:{lite:M},faceModelKey:"lite",poseDetectorModelTFLites:{lite:x},poseLandmarkModelTFLites:{lite:_},poseModelKey:"lite",maxProcessWidth:1024,maxProcessHeight:1024}},this.generateDefaultMediapipeMixParams=()=>({operationType:t.face,handProcessWidth:512,handProcessHeight:512,handMaxHands:2,handAffineResizedFactor:2,faceProcessWidth:512,faceProcessHeight:512,faceMaxFaces:1,faceMovingAverageWindow:5,poseProcessWidth:512,poseProcessHeight:512,poseMaxPoses:1,poseMovingAverageWindow:5,poseAffineResizedFactor:2,poseCropExt:1.3,poseCalculateMode:0}),this.init=async e=>{this.config=e||await this.generateDefaultConfig(),await this.initCommon({useWorkerForSafari:!0,processOnLocal:this.config.processOnLocal,workerJs:()=>new c},this.config),console.log("[manager] tflite worker initilizied.")},this.predict=async(e,n)=>{if(!this.config)return console.warn("config is not initialized."),null;const i={...e},r=((n,i)=>e.operationType===t.hand?this.generateTargetCanvas(i,n.handProcessWidth,n.handProcessHeight):e.operationType===t.face?this.generateTargetCanvas(i,n.faceProcessWidth,n.faceProcessHeight):this.generateTargetCanvas(i,n.poseProcessWidth,n.poseProcessHeight))(i,n);if(!this.worker){const e=r.getContext("2d").getImageData(0,0,r.width,r.height),n=await this.imageProcessor.predict(this.config,i,e.data);return i.operationType===t.hand?this.generateHandPredictionEx(this.config,i,n):i.operationType===t.face?this.generateFacePredictionEx(this.config,i,n):this.generatePosePredictionEx(this.config,i,n)}const a=r.getContext("2d").getImageData(0,0,r.width,r.height),o=await this.sendToWorker(i,a.data);return i.operationType===t.hand?this.generateHandPredictionEx(this.config,i,o):i.operationType===t.face?this.generateFacePredictionEx(this.config,i,o):this.generatePosePredictionEx(this.config,i,o)},this.generateHandPredictionEx=(e,n,i)=>{const r=i;return{operationType:t.hand,rowPrediction:r}},this.facesMV=[],this.generateFacePredictionEx=(e,n,i)=>{const r=i,a={operationType:t.face,rowPrediction:r};if(n.faceMovingAverageWindow>0){if(r)for(;this.facesMV.length>n.faceMovingAverageWindow;)this.facesMV.shift();r&&r[0]&&r[0].keypoints&&this.facesMV.push(r);const e=this.facesMV.map((e=>e[0].keypoints)).reduce(((e,t)=>{for(let n=0;ne[0].box)).reduce(((e,t)=>e.width?(e.width=e.width+t.width,e.xMax=e.xMax+t.xMax,e.xMin=e.xMin+t.xMin,e.height=e.height+t.height,e.yMax=e.yMax+t.yMax,e.yMin=e.yMin+t.yMin,e):{width:t.width,xMax:t.xMax,xMin:t.xMin,height:t.height,yMax:t.yMax,yMin:t.yMin}),{});console.log(),t.width/=this.facesMV.length,t.xMax/=this.facesMV.length,t.xMin/=this.facesMV.length,t.height/=this.facesMV.length,t.yMax/=this.facesMV.length,t.yMin/=this.facesMV.length,a.singlePersonBoxMovingAverage=t}return a},this.posesMV=[],this.generatePosePredictionEx=(e,n,i)=>{const r=i,a={operationType:t.pose,rowPrediction:r};if(n.poseMovingAverageWindow>0){if(r)for(;this.posesMV.length>n.poseMovingAverageWindow;)this.posesMV.shift();r&&r[0]&&r[0].keypoints&&this.posesMV.push(r);const e=this.posesMV.map((e=>e[0].keypoints)).reduce(((e,t)=>{for(let n=0;ne[0].keypoints3D)).reduce(((e,t)=>{for(let n=0;ne[0].box)).reduce(((e,t)=>e.width?(e.width=e.width+t.width,e.xMax=e.xMax+t.xMax,e.xMin=e.xMin+t.xMin,e.height=e.height+t.height,e.yMax=e.yMax+t.yMax,e.yMin=e.yMin+t.yMin,e):{width:t.width,xMax:t.xMax,xMin:t.xMin,height:t.height,yMax:t.yMax,yMin:t.yMin}),{});console.log(),i.width/=this.posesMV.length,i.xMax/=this.posesMV.length,i.xMin/=this.posesMV.length,i.height/=this.posesMV.length,i.yMax/=this.posesMV.length,i.yMin/=this.posesMV.length,a.singlePersonBoxMovingAverage=i}return a},this.fitCroppedArea=(e,t,n,i,r,a,o,s,c,l,u)=>{if(!e.singlePersonBoxMovingAverage)return{xmin:0,ymin:0,width:0,height:0};const d=t/i,h=n/r,f=e.singlePersonBoxMovingAverage.xMin*d,p=e.singlePersonBoxMovingAverage.xMax*d,m=e.singlePersonBoxMovingAverage.yMin*h,g=e.singlePersonBoxMovingAverage.yMax*h,C=(p+f)/2,v=(g+m)/2,y=p-C,b=g-v;let M=C-y*(1+l);M=M<0?0:M;let x=C+y*(1+u);x=x>t?t:x;let _=v-b*(1+s);_=_<0?0:_;let S=v+b*(1+c);S=S>n?n:S;const w=x-M,L=S-_,E=(x+M)/2,T=(S+_)/2,z=o/a;let A,V,H,R;return w*z>L?(A=w,V=w*z):(A=L/z,V=L),H=E-A/2<0?0:E+A/2>t?t-A:E-A/2,R=T-V/2<0?0:T+V/2>n?n-V:T-V/2,{xmin:H,ymin:R,width:A,height:V}}}}})(),a})(),e.exports=i()},698:(e,t,n)=>{"use strict";n.r(t),n.d(t,{MToonMaterial:()=>El,MToonMaterialCullMode:()=>Ml,MToonMaterialDebugMode:()=>xl,MToonMaterialOutlineColorMode:()=>_l,MToonMaterialOutlineWidthMode:()=>Sl,MToonMaterialRenderMode:()=>wl,VRM:()=>Yl,VRMBlendShapeGroup:()=>Nc,VRMBlendShapeImporter:()=>qc,VRMBlendShapeProxy:()=>jc,VRMCurveMapper:()=>al,VRMDebug:()=>du,VRMFirstPerson:()=>Kc,VRMFirstPersonImporter:()=>Zc,VRMHumanBone:()=>Qc,VRMHumanoid:()=>il,VRMHumanoidImporter:()=>rl,VRMImporter:()=>Xl,VRMLookAtApplyer:()=>ol,VRMLookAtBlendShapeApplyer:()=>sl,VRMLookAtBoneApplyer:()=>ml,VRMLookAtHead:()=>fl,VRMLookAtImporter:()=>Cl,VRMMaterialImporter:()=>zl,VRMMetaImporter:()=>Al,VRMRendererFirstPersonFlags:()=>$c,VRMSchema:()=>Dc,VRMSpringBone:()=>Ul,VRMSpringBoneDebug:()=>su,VRMSpringBoneImporter:()=>ql,VRMSpringBoneImporterDebug:()=>cu,VRMSpringBoneManager:()=>Wl,VRMUnlitMaterial:()=>Tl,VRMUnlitMaterialRenderType:()=>Ll,VRMUtils:()=>eu,VRM_GIZMO_RENDER_ORDER:()=>uu});const i="137",r=100,a=301,o=302,s=306,c=1e3,l=1001,u=1002,d=1003,h=1006,f=1008,p=1009,m=1012,g=1014,C=1015,v=1016,y=1020,b=1023,M=1026,x=1027,_=33776,S=33777,w=33778,L=33779,E=2300,T=2301,z=2302,A=2400,V=2401,H=2402,R=3e3,P=3001,I=7680,k=35044,N=35048,D="300 es",O=1035;class B{addEventListener(e,t){void 0===this._listeners&&(this._listeners={});const n=this._listeners;void 0===n[e]&&(n[e]=[]),-1===n[e].indexOf(t)&&n[e].push(t)}hasEventListener(e,t){if(void 0===this._listeners)return!1;const n=this._listeners;return void 0!==n[e]&&-1!==n[e].indexOf(t)}removeEventListener(e,t){if(void 0===this._listeners)return;const n=this._listeners[e];if(void 0!==n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}dispatchEvent(e){if(void 0===this._listeners)return;const t=this._listeners[e.type];if(void 0!==t){e.target=this;const n=t.slice(0);for(let t=0,i=n.length;t>8&255]+F[e>>16&255]+F[e>>24&255]+"-"+F[255&t]+F[t>>8&255]+"-"+F[t>>16&15|64]+F[t>>24&255]+"-"+F[63&n|128]+F[n>>8&255]+"-"+F[n>>16&255]+F[n>>24&255]+F[255&i]+F[i>>8&255]+F[i>>16&255]+F[i>>24&255]).toUpperCase()}function j(e,t,n){return Math.max(t,Math.min(n,e))}function q(e,t,n){return(1-n)*e+n*t}function X(e){return 0==(e&e-1)&&0!==e}function Y(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))}class J{constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e,t){return void 0!==t?(console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(e,t)):(this.x+=e.x,this.y+=e.y,this)}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e,t){return void 0!==t?(console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(e,t)):(this.x-=e.x,this.y-=e.y,this)}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6],this.y=i[1]*t+i[4]*n+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(e,Math.min(t,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t,n){return void 0!==n&&console.warn("THREE.Vector2: offset has been removed from .fromBufferAttribute()."),this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const n=Math.cos(t),i=Math.sin(t),r=this.x-e.x,a=this.y-e.y;return this.x=r*n-a*i+e.x,this.y=r*i+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}J.prototype.isVector2=!0;class ${constructor(){this.elements=[1,0,0,0,1,0,0,0,1],arguments.length>0&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}set(e,t,n,i,r,a,o,s,c){const l=this.elements;return l[0]=e,l[1]=i,l[2]=o,l[3]=t,l[4]=r,l[5]=s,l[6]=n,l[7]=a,l[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,i=t.elements,r=this.elements,a=n[0],o=n[3],s=n[6],c=n[1],l=n[4],u=n[7],d=n[2],h=n[5],f=n[8],p=i[0],m=i[3],g=i[6],C=i[1],v=i[4],y=i[7],b=i[2],M=i[5],x=i[8];return r[0]=a*p+o*C+s*b,r[3]=a*m+o*v+s*M,r[6]=a*g+o*y+s*x,r[1]=c*p+l*C+u*b,r[4]=c*m+l*v+u*M,r[7]=c*g+l*y+u*x,r[2]=d*p+h*C+f*b,r[5]=d*m+h*v+f*M,r[8]=d*g+h*y+f*x,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*a*l-t*o*c-n*r*l+n*o*s+i*r*c-i*a*s}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=l*a-o*c,d=o*s-l*r,h=c*r-a*s,f=t*u+n*d+i*h;if(0===f)return this.set(0,0,0,0,0,0,0,0,0);const p=1/f;return e[0]=u*p,e[1]=(i*c-l*n)*p,e[2]=(o*n-i*a)*p,e[3]=d*p,e[4]=(l*t-i*s)*p,e[5]=(i*r-o*t)*p,e[6]=h*p,e[7]=(n*s-c*t)*p,e[8]=(a*t-n*r)*p,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,i,r,a,o){const s=Math.cos(r),c=Math.sin(r);return this.set(n*s,n*c,-n*(s*a+c*o)+a+e,-i*c,i*s,-i*(-c*a+s*o)+o+t,0,0,1),this}scale(e,t){const n=this.elements;return n[0]*=e,n[3]*=e,n[6]*=e,n[1]*=t,n[4]*=t,n[7]*=t,this}rotate(e){const t=Math.cos(e),n=Math.sin(e),i=this.elements,r=i[0],a=i[3],o=i[6],s=i[1],c=i[4],l=i[7];return i[0]=t*r+n*s,i[3]=t*a+n*c,i[6]=t*o+n*l,i[1]=-n*r+t*s,i[4]=-n*a+t*c,i[7]=-n*o+t*l,this}translate(e,t){const n=this.elements;return n[0]+=e*n[2],n[3]+=e*n[5],n[6]+=e*n[8],n[1]+=t*n[2],n[4]+=t*n[5],n[7]+=t*n[8],this}equals(e){const t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return(new this.constructor).fromArray(this.elements)}}function K(e){for(let t=e.length-1;t>=0;--t)if(e[t]>65535)return!0;return!1}function Z(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}$.prototype.isMatrix3=!0,Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array;const Q={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},ee={h:0,s:0,l:0},te={h:0,s:0,l:0};function ne(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+6*(t-e)*(2/3-n):e}function ie(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function re(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}class ae{constructor(e,t,n){return void 0===t&&void 0===n?this.set(e):this.setRGB(e,t,n)}set(e){return e&&e.isColor?this.copy(e):"number"==typeof e?this.setHex(e):"string"==typeof e&&this.setStyle(e),this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,this}setRGB(e,t,n){return this.r=e,this.g=t,this.b=n,this}setHSL(e,t,n){if(e=function(e,t){return(e%1+1)%1}(e),t=j(t,0,1),n=j(n,0,1),0===t)this.r=this.g=this.b=n;else{const i=n<=.5?n*(1+t):n+t-n*t,r=2*n-i;this.r=ne(r,i,e+1/3),this.g=ne(r,i,e),this.b=ne(r,i,e-1/3)}return this}setStyle(e){function t(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let n;if(n=/^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(e)){let e;const i=n[1],r=n[2];switch(i){case"rgb":case"rgba":if(e=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return this.r=Math.min(255,parseInt(e[1],10))/255,this.g=Math.min(255,parseInt(e[2],10))/255,this.b=Math.min(255,parseInt(e[3],10))/255,t(e[4]),this;if(e=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return this.r=Math.min(100,parseInt(e[1],10))/100,this.g=Math.min(100,parseInt(e[2],10))/100,this.b=Math.min(100,parseInt(e[3],10))/100,t(e[4]),this;break;case"hsl":case"hsla":if(e=/^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r)){const n=parseFloat(e[1])/360,i=parseInt(e[2],10)/100,r=parseInt(e[3],10)/100;return t(e[4]),this.setHSL(n,i,r)}}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(e)){const e=n[1],t=e.length;if(3===t)return this.r=parseInt(e.charAt(0)+e.charAt(0),16)/255,this.g=parseInt(e.charAt(1)+e.charAt(1),16)/255,this.b=parseInt(e.charAt(2)+e.charAt(2),16)/255,this;if(6===t)return this.r=parseInt(e.charAt(0)+e.charAt(1),16)/255,this.g=parseInt(e.charAt(2)+e.charAt(3),16)/255,this.b=parseInt(e.charAt(4)+e.charAt(5),16)/255,this}return e&&e.length>0?this.setColorName(e):this}setColorName(e){const t=Q[e.toLowerCase()];return void 0!==t?this.setHex(t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=ie(e.r),this.g=ie(e.g),this.b=ie(e.b),this}copyLinearToSRGB(e){return this.r=re(e.r),this.g=re(e.g),this.b=re(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0}getHexString(){return("000000"+this.getHex().toString(16)).slice(-6)}getHSL(e){const t=this.r,n=this.g,i=this.b,r=Math.max(t,n,i),a=Math.min(t,n,i);let o,s;const c=(a+r)/2;if(a===r)o=0,s=0;else{const e=r-a;switch(s=c<=.5?e/(r+a):e/(2-r-a),r){case t:o=(n-i)/e+(n2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=Z("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const i=n.getImageData(0,0,e.width,e.height),r=i.data;for(let e=0;e1)switch(this.wrapS){case c:e.x=e.x-Math.floor(e.x);break;case l:e.x=e.x<0?0:1;break;case u:1===Math.abs(Math.floor(e.x)%2)?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case c:e.y=e.y-Math.floor(e.y);break;case l:e.y=e.y<0?0:1;break;case u:1===Math.abs(Math.floor(e.y)%2)?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){!0===e&&this.version++}}function ue(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?se.getDataURL(e):e.data?{data:Array.prototype.slice.call(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}le.DEFAULT_IMAGE=void 0,le.DEFAULT_MAPPING=300,le.prototype.isTexture=!0;class de{constructor(e=0,t=0,n=0,i=1){this.x=e,this.y=t,this.z=n,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,i){return this.x=e,this.y=t,this.z=n,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=void 0!==e.w?e.w:1,this}add(e,t){return void 0!==t?(console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(e,t)):(this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this)}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e,t){return void 0!==t?(console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(e,t)):(this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this)}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,n=this.y,i=this.z,r=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*i+a[12]*r,this.y=a[1]*t+a[5]*n+a[9]*i+a[13]*r,this.z=a[2]*t+a[6]*n+a[10]*i+a[14]*r,this.w=a[3]*t+a[7]*n+a[11]*i+a[15]*r,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,i,r;const a=.01,o=.1,s=e.elements,c=s[0],l=s[4],u=s[8],d=s[1],h=s[5],f=s[9],p=s[2],m=s[6],g=s[10];if(Math.abs(l-d)s&&e>C?eC?s=0?1:-1,i=1-t*t;if(i>Number.EPSILON){const r=Math.sqrt(i),a=Math.atan2(r,t*n);e=Math.sin(e*a)/r,o=Math.sin(o*a)/r}const r=o*n;if(s=s*e+d*r,c=c*e+h*r,l=l*e+f*r,u=u*e+p*r,e===1-o){const e=1/Math.sqrt(s*s+c*c+l*l+u*u);s*=e,c*=e,l*=e,u*=e}}e[t]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,i,r,a){const o=n[i],s=n[i+1],c=n[i+2],l=n[i+3],u=r[a],d=r[a+1],h=r[a+2],f=r[a+3];return e[t]=o*f+l*u+s*h-c*d,e[t+1]=s*f+l*d+c*u-o*h,e[t+2]=c*f+l*h+o*d-s*u,e[t+3]=l*f-o*u-s*d-c*h,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,i){return this._x=e,this._y=t,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t){if(!e||!e.isEuler)throw new Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");const n=e._x,i=e._y,r=e._z,a=e._order,o=Math.cos,s=Math.sin,c=o(n/2),l=o(i/2),u=o(r/2),d=s(n/2),h=s(i/2),f=s(r/2);switch(a){case"XYZ":this._x=d*l*u+c*h*f,this._y=c*h*u-d*l*f,this._z=c*l*f+d*h*u,this._w=c*l*u-d*h*f;break;case"YXZ":this._x=d*l*u+c*h*f,this._y=c*h*u-d*l*f,this._z=c*l*f-d*h*u,this._w=c*l*u+d*h*f;break;case"ZXY":this._x=d*l*u-c*h*f,this._y=c*h*u+d*l*f,this._z=c*l*f+d*h*u,this._w=c*l*u-d*h*f;break;case"ZYX":this._x=d*l*u-c*h*f,this._y=c*h*u+d*l*f,this._z=c*l*f-d*h*u,this._w=c*l*u+d*h*f;break;case"YZX":this._x=d*l*u+c*h*f,this._y=c*h*u+d*l*f,this._z=c*l*f-d*h*u,this._w=c*l*u-d*h*f;break;case"XZY":this._x=d*l*u-c*h*f,this._y=c*h*u-d*l*f,this._z=c*l*f+d*h*u,this._w=c*l*u+d*h*f;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+a)}return!1!==t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,i=Math.sin(n);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],i=t[4],r=t[8],a=t[1],o=t[5],s=t[9],c=t[2],l=t[6],u=t[10],d=n+o+u;if(d>0){const e=.5/Math.sqrt(d+1);this._w=.25/e,this._x=(l-s)*e,this._y=(r-c)*e,this._z=(a-i)*e}else if(n>o&&n>u){const e=2*Math.sqrt(1+n-o-u);this._w=(l-s)/e,this._x=.25*e,this._y=(i+a)/e,this._z=(r+c)/e}else if(o>u){const e=2*Math.sqrt(1+o-n-u);this._w=(r-c)/e,this._x=(i+a)/e,this._y=.25*e,this._z=(s+l)/e}else{const e=2*Math.sqrt(1+u-n-o);this._w=(a-i)/e,this._x=(r+c)/e,this._y=(s+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return nMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(j(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(0===n)return this;const i=Math.min(1,t/n);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return 0===e?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e,t){return void 0!==t?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(e,t)):this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const n=e._x,i=e._y,r=e._z,a=e._w,o=t._x,s=t._y,c=t._z,l=t._w;return this._x=n*l+a*o+i*c-r*s,this._y=i*l+a*s+r*o-n*c,this._z=r*l+a*c+n*s-i*o,this._w=a*l-n*o-i*s-r*c,this._onChangeCallback(),this}slerp(e,t){if(0===t)return this;if(1===t)return this.copy(e);const n=this._x,i=this._y,r=this._z,a=this._w;let o=a*e._w+n*e._x+i*e._y+r*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=a,this._x=n,this._y=i,this._z=r,this;const s=1-o*o;if(s<=Number.EPSILON){const e=1-t;return this._w=e*a+t*this._w,this._x=e*n+t*this._x,this._y=e*i+t*this._y,this._z=e*r+t*this._z,this.normalize(),this._onChangeCallback(),this}const c=Math.sqrt(s),l=Math.atan2(c,o),u=Math.sin((1-t)*l)/c,d=Math.sin(t*l)/c;return this._w=a*u+this._w*d,this._x=n*u+this._x*d,this._y=i*u+this._y*d,this._z=r*u+this._z*d,this._onChangeCallback(),this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=Math.random(),t=Math.sqrt(1-e),n=Math.sqrt(e),i=2*Math.PI*Math.random(),r=2*Math.PI*Math.random();return this.set(t*Math.cos(i),n*Math.sin(r),n*Math.cos(r),t*Math.sin(i))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}}pe.prototype.isQuaternion=!0;class me{constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}set(e,t,n){return void 0===n&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e,t){return void 0!==t?(console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(e,t)):(this.x+=e.x,this.y+=e.y,this.z+=e.z,this)}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e,t){return void 0!==t?(console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(e,t)):(this.x-=e.x,this.y-=e.y,this.z-=e.z,this)}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e,t){return void 0!==t?(console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(e,t)):(this.x*=e.x,this.y*=e.y,this.z*=e.z,this)}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return e&&e.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),this.applyQuaternion(Ce.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Ce.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*i,this.y=r[1]*t+r[4]*n+r[7]*i,this.z=r[2]*t+r[5]*n+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,i=this.z,r=e.elements,a=1/(r[3]*t+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*i+r[12])*a,this.y=(r[1]*t+r[5]*n+r[9]*i+r[13])*a,this.z=(r[2]*t+r[6]*n+r[10]*i+r[14])*a,this}applyQuaternion(e){const t=this.x,n=this.y,i=this.z,r=e.x,a=e.y,o=e.z,s=e.w,c=s*t+a*i-o*n,l=s*n+o*t-r*i,u=s*i+r*n-a*t,d=-r*t-a*n-o*i;return this.x=c*s+d*-r+l*-o-u*-a,this.y=l*s+d*-a+u*-r-c*-o,this.z=u*s+d*-o+c*-a-l*-r,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*i,this.y=r[1]*t+r[5]*n+r[9]*i,this.z=r[2]*t+r[6]*n+r[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(e,Math.min(t,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e,t){return void 0!==t?(console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(e,t)):this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,i=e.y,r=e.z,a=t.x,o=t.y,s=t.z;return this.x=i*s-r*o,this.y=r*a-n*s,this.z=n*o-i*a,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return ge.copy(this).projectOnVector(e),this.sub(ge)}reflect(e){return this.sub(ge.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(j(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,i=this.z-e.z;return t*t+n*n+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const i=Math.sin(t)*e;return this.x=i*Math.sin(n),this.y=Math.cos(t)*e,this.z=i*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t,n){return void 0!==n&&console.warn("THREE.Vector3: offset has been removed from .fromBufferAttribute()."),this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=2*(Math.random()-.5),t=Math.random()*Math.PI*2,n=Math.sqrt(1-e**2);return this.x=n*Math.cos(t),this.y=n*Math.sin(t),this.z=e,this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}me.prototype.isVector3=!0;const ge=new me,Ce=new pe;class ve{constructor(e=new me(1/0,1/0,1/0),t=new me(-1/0,-1/0,-1/0)){this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){let t=1/0,n=1/0,i=1/0,r=-1/0,a=-1/0,o=-1/0;for(let s=0,c=e.length;sr&&(r=c),l>a&&(a=l),u>o&&(o=u)}return this.min.set(t,n,i),this.max.set(r,a,o),this}setFromBufferAttribute(e){let t=1/0,n=1/0,i=1/0,r=-1/0,a=-1/0,o=-1/0;for(let s=0,c=e.count;sr&&(r=c),l>a&&(a=l),u>o&&(o=u)}return this.min.set(t,n,i),this.max.set(r,a,o),this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;tthis.max.x||e.ythis.max.y||e.zthis.max.z)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return!(e.max.xthis.max.x||e.max.ythis.max.y||e.max.zthis.max.z)}intersectsSphere(e){return this.clampPoint(e.center,be),be.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Te),ze.subVectors(this.max,Te),xe.subVectors(e.a,Te),_e.subVectors(e.b,Te),Se.subVectors(e.c,Te),we.subVectors(_e,xe),Le.subVectors(Se,_e),Ee.subVectors(xe,Se);let t=[0,-we.z,we.y,0,-Le.z,Le.y,0,-Ee.z,Ee.y,we.z,0,-we.x,Le.z,0,-Le.x,Ee.z,0,-Ee.x,-we.y,we.x,0,-Le.y,Le.x,0,-Ee.y,Ee.x,0];return!!He(t,xe,_e,Se,ze)&&(t=[1,0,0,0,1,0,0,0,1],!!He(t,xe,_e,Se,ze)&&(Ae.crossVectors(we,Le),t=[Ae.x,Ae.y,Ae.z],He(t,xe,_e,Se,ze)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return be.copy(e).clamp(this.min,this.max).sub(e).length()}getBoundingSphere(e){return this.getCenter(e.center),e.radius=.5*this.getSize(be).length(),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()||(ye[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),ye[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),ye[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),ye[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),ye[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),ye[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),ye[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),ye[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(ye)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}ve.prototype.isBox3=!0;const ye=[new me,new me,new me,new me,new me,new me,new me,new me],be=new me,Me=new ve,xe=new me,_e=new me,Se=new me,we=new me,Le=new me,Ee=new me,Te=new me,ze=new me,Ae=new me,Ve=new me;function He(e,t,n,i,r){for(let a=0,o=e.length-3;a<=o;a+=3){Ve.fromArray(e,a);const o=r.x*Math.abs(Ve.x)+r.y*Math.abs(Ve.y)+r.z*Math.abs(Ve.z),s=t.dot(Ve),c=n.dot(Ve),l=i.dot(Ve);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}const Re=new ve,Pe=new me,Ie=new me,ke=new me;class Ne{constructor(e=new me,t=-1){this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;void 0!==t?n.copy(t):Re.setFromPoints(e).getCenter(n);let i=0;for(let t=0,r=e.length;tthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){ke.subVectors(e,this.center);const t=ke.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),n=.5*(e-this.radius);this.center.add(ke.multiplyScalar(n/e)),this.radius+=n}return this}union(e){return!0===this.center.equals(e.center)?Ie.set(0,0,1).multiplyScalar(e.radius):Ie.subVectors(e.center,this.center).normalize().multiplyScalar(e.radius),this.expandByPoint(Pe.copy(e.center).add(Ie)),this.expandByPoint(Pe.copy(e.center).sub(Ie)),this}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const De=new me,Oe=new me,Be=new me,Fe=new me,Ue=new me,We=new me,Ge=new me;class je{constructor(e=new me,t=new me(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.direction).multiplyScalar(e).add(this.origin)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,De)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.direction).multiplyScalar(n).add(this.origin)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=De.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(De.copy(this.direction).multiplyScalar(t).add(this.origin),De.distanceToSquared(e))}distanceSqToSegment(e,t,n,i){Oe.copy(e).add(t).multiplyScalar(.5),Be.copy(t).sub(e).normalize(),Fe.copy(this.origin).sub(Oe);const r=.5*e.distanceTo(t),a=-this.direction.dot(Be),o=Fe.dot(this.direction),s=-Fe.dot(Be),c=Fe.lengthSq(),l=Math.abs(1-a*a);let u,d,h,f;if(l>0)if(u=a*s-o,d=a*o-s,f=r*l,u>=0)if(d>=-f)if(d<=f){const e=1/l;u*=e,d*=e,h=u*(u+a*d+2*o)+d*(a*u+d+2*s)+c}else d=r,u=Math.max(0,-(a*d+o)),h=-u*u+d*(d+2*s)+c;else d=-r,u=Math.max(0,-(a*d+o)),h=-u*u+d*(d+2*s)+c;else d<=-f?(u=Math.max(0,-(-a*r+o)),d=u>0?-r:Math.min(Math.max(-r,-s),r),h=-u*u+d*(d+2*s)+c):d<=f?(u=0,d=Math.min(Math.max(-r,-s),r),h=d*(d+2*s)+c):(u=Math.max(0,-(a*r+o)),d=u>0?r:Math.min(Math.max(-r,-s),r),h=-u*u+d*(d+2*s)+c);else d=a>0?-r:r,u=Math.max(0,-(a*d+o)),h=-u*u+d*(d+2*s)+c;return n&&n.copy(this.direction).multiplyScalar(u).add(this.origin),i&&i.copy(Be).multiplyScalar(d).add(Oe),h}intersectSphere(e,t){De.subVectors(e.center,this.origin);const n=De.dot(this.direction),i=De.dot(De)-n*n,r=e.radius*e.radius;if(i>r)return null;const a=Math.sqrt(r-i),o=n-a,s=n+a;return o<0&&s<0?null:o<0?this.at(s,t):this.at(o,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(0===t)return 0===e.distanceToPoint(this.origin)?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return null===n?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return 0===t||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,i,r,a,o,s;const c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,i=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,i=(e.min.x-d.x)*c),l>=0?(r=(e.min.y-d.y)*l,a=(e.max.y-d.y)*l):(r=(e.max.y-d.y)*l,a=(e.min.y-d.y)*l),n>a||r>i?null:((r>n||n!=n)&&(n=r),(a=0?(o=(e.min.z-d.z)*u,s=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,s=(e.min.z-d.z)*u),n>s||o>i?null:((o>n||n!=n)&&(n=o),(s=0?n:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,De)}intersectTriangle(e,t,n,i,r){Ue.subVectors(t,e),We.subVectors(n,e),Ge.crossVectors(Ue,We);let a,o=this.direction.dot(Ge);if(o>0){if(i)return null;a=1}else{if(!(o<0))return null;a=-1,o=-o}Fe.subVectors(this.origin,e);const s=a*this.direction.dot(We.crossVectors(Fe,We));if(s<0)return null;const c=a*this.direction.dot(Ue.cross(Fe));if(c<0)return null;if(s+c>o)return null;const l=-a*Fe.dot(Ge);return l<0?null:this.at(l/o,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class qe{constructor(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],arguments.length>0&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}set(e,t,n,i,r,a,o,s,c,l,u,d,h,f,p,m){const g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=i,g[1]=r,g[5]=a,g[9]=o,g[13]=s,g[2]=c,g[6]=l,g[10]=u,g[14]=d,g[3]=h,g[7]=f,g[11]=p,g[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new qe).fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,n=e.elements,i=1/Xe.setFromMatrixColumn(e,0).length(),r=1/Xe.setFromMatrixColumn(e,1).length(),a=1/Xe.setFromMatrixColumn(e,2).length();return t[0]=n[0]*i,t[1]=n[1]*i,t[2]=n[2]*i,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){e&&e.isEuler||console.error("THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");const t=this.elements,n=e.x,i=e.y,r=e.z,a=Math.cos(n),o=Math.sin(n),s=Math.cos(i),c=Math.sin(i),l=Math.cos(r),u=Math.sin(r);if("XYZ"===e.order){const e=a*l,n=a*u,i=o*l,r=o*u;t[0]=s*l,t[4]=-s*u,t[8]=c,t[1]=n+i*c,t[5]=e-r*c,t[9]=-o*s,t[2]=r-e*c,t[6]=i+n*c,t[10]=a*s}else if("YXZ"===e.order){const e=s*l,n=s*u,i=c*l,r=c*u;t[0]=e+r*o,t[4]=i*o-n,t[8]=a*c,t[1]=a*u,t[5]=a*l,t[9]=-o,t[2]=n*o-i,t[6]=r+e*o,t[10]=a*s}else if("ZXY"===e.order){const e=s*l,n=s*u,i=c*l,r=c*u;t[0]=e-r*o,t[4]=-a*u,t[8]=i+n*o,t[1]=n+i*o,t[5]=a*l,t[9]=r-e*o,t[2]=-a*c,t[6]=o,t[10]=a*s}else if("ZYX"===e.order){const e=a*l,n=a*u,i=o*l,r=o*u;t[0]=s*l,t[4]=i*c-n,t[8]=e*c+r,t[1]=s*u,t[5]=r*c+e,t[9]=n*c-i,t[2]=-c,t[6]=o*s,t[10]=a*s}else if("YZX"===e.order){const e=a*s,n=a*c,i=o*s,r=o*c;t[0]=s*l,t[4]=r-e*u,t[8]=i*u+n,t[1]=u,t[5]=a*l,t[9]=-o*l,t[2]=-c*l,t[6]=n*u+i,t[10]=e-r*u}else if("XZY"===e.order){const e=a*s,n=a*c,i=o*s,r=o*c;t[0]=s*l,t[4]=-u,t[8]=c*l,t[1]=e*u+r,t[5]=a*l,t[9]=n*u-i,t[2]=i*u-n,t[6]=o*l,t[10]=r*u+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Je,e,$e)}lookAt(e,t,n){const i=this.elements;return Qe.subVectors(e,t),0===Qe.lengthSq()&&(Qe.z=1),Qe.normalize(),Ke.crossVectors(n,Qe),0===Ke.lengthSq()&&(1===Math.abs(n.z)?Qe.x+=1e-4:Qe.z+=1e-4,Qe.normalize(),Ke.crossVectors(n,Qe)),Ke.normalize(),Ze.crossVectors(Qe,Ke),i[0]=Ke.x,i[4]=Ze.x,i[8]=Qe.x,i[1]=Ke.y,i[5]=Ze.y,i[9]=Qe.y,i[2]=Ke.z,i[6]=Ze.z,i[10]=Qe.z,this}multiply(e,t){return void 0!==t?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(e,t)):this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,i=t.elements,r=this.elements,a=n[0],o=n[4],s=n[8],c=n[12],l=n[1],u=n[5],d=n[9],h=n[13],f=n[2],p=n[6],m=n[10],g=n[14],C=n[3],v=n[7],y=n[11],b=n[15],M=i[0],x=i[4],_=i[8],S=i[12],w=i[1],L=i[5],E=i[9],T=i[13],z=i[2],A=i[6],V=i[10],H=i[14],R=i[3],P=i[7],I=i[11],k=i[15];return r[0]=a*M+o*w+s*z+c*R,r[4]=a*x+o*L+s*A+c*P,r[8]=a*_+o*E+s*V+c*I,r[12]=a*S+o*T+s*H+c*k,r[1]=l*M+u*w+d*z+h*R,r[5]=l*x+u*L+d*A+h*P,r[9]=l*_+u*E+d*V+h*I,r[13]=l*S+u*T+d*H+h*k,r[2]=f*M+p*w+m*z+g*R,r[6]=f*x+p*L+m*A+g*P,r[10]=f*_+p*E+m*V+g*I,r[14]=f*S+p*T+m*H+g*k,r[3]=C*M+v*w+y*z+b*R,r[7]=C*x+v*L+y*A+b*P,r[11]=C*_+v*E+y*V+b*I,r[15]=C*S+v*T+y*H+b*k,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],i=e[8],r=e[12],a=e[1],o=e[5],s=e[9],c=e[13],l=e[2],u=e[6],d=e[10],h=e[14];return e[3]*(+r*s*u-i*c*u-r*o*d+n*c*d+i*o*h-n*s*h)+e[7]*(+t*s*h-t*c*d+r*a*d-i*a*h+i*c*l-r*s*l)+e[11]*(+t*c*u-t*o*h-r*a*u+n*a*h+r*o*l-n*c*l)+e[15]*(-i*o*l-t*s*u+t*o*d+i*a*u-n*a*d+n*s*l)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],h=e[11],f=e[12],p=e[13],m=e[14],g=e[15],C=u*m*c-p*d*c+p*s*h-o*m*h-u*s*g+o*d*g,v=f*d*c-l*m*c-f*s*h+a*m*h+l*s*g-a*d*g,y=l*p*c-f*u*c+f*o*h-a*p*h-l*o*g+a*u*g,b=f*u*s-l*p*s-f*o*d+a*p*d+l*o*m-a*u*m,M=t*C+n*v+i*y+r*b;if(0===M)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const x=1/M;return e[0]=C*x,e[1]=(p*d*r-u*m*r-p*i*h+n*m*h+u*i*g-n*d*g)*x,e[2]=(o*m*r-p*s*r+p*i*c-n*m*c-o*i*g+n*s*g)*x,e[3]=(u*s*r-o*d*r-u*i*c+n*d*c+o*i*h-n*s*h)*x,e[4]=v*x,e[5]=(l*m*r-f*d*r+f*i*h-t*m*h-l*i*g+t*d*g)*x,e[6]=(f*s*r-a*m*r-f*i*c+t*m*c+a*i*g-t*s*g)*x,e[7]=(a*d*r-l*s*r+l*i*c-t*d*c-a*i*h+t*s*h)*x,e[8]=y*x,e[9]=(f*u*r-l*p*r-f*n*h+t*p*h+l*n*g-t*u*g)*x,e[10]=(a*p*r-f*o*r+f*n*c-t*p*c-a*n*g+t*o*g)*x,e[11]=(l*o*r-a*u*r-l*n*c+t*u*c+a*n*h-t*o*h)*x,e[12]=b*x,e[13]=(l*p*i-f*u*i+f*n*d-t*p*d-l*n*m+t*u*m)*x,e[14]=(f*o*i-a*p*i-f*n*s+t*p*s+a*n*m-t*o*m)*x,e[15]=(a*u*i-l*o*i+l*n*s-t*u*s-a*n*d+t*o*d)*x,this}scale(e){const t=this.elements,n=e.x,i=e.y,r=e.z;return t[0]*=n,t[4]*=i,t[8]*=r,t[1]*=n,t[5]*=i,t[9]*=r,t[2]*=n,t[6]*=i,t[10]*=r,t[3]*=n,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,i))}makeTranslation(e,t,n){return this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),i=Math.sin(t),r=1-n,a=e.x,o=e.y,s=e.z,c=r*a,l=r*o;return this.set(c*a+n,c*o-i*s,c*s+i*o,0,c*o+i*s,l*o+n,l*s-i*a,0,c*s-i*o,l*s+i*a,r*s*s+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,i,r,a){return this.set(1,n,r,0,e,1,a,0,t,i,1,0,0,0,0,1),this}compose(e,t,n){const i=this.elements,r=t._x,a=t._y,o=t._z,s=t._w,c=r+r,l=a+a,u=o+o,d=r*c,h=r*l,f=r*u,p=a*l,m=a*u,g=o*u,C=s*c,v=s*l,y=s*u,b=n.x,M=n.y,x=n.z;return i[0]=(1-(p+g))*b,i[1]=(h+y)*b,i[2]=(f-v)*b,i[3]=0,i[4]=(h-y)*M,i[5]=(1-(d+g))*M,i[6]=(m+C)*M,i[7]=0,i[8]=(f+v)*x,i[9]=(m-C)*x,i[10]=(1-(d+p))*x,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,n){const i=this.elements;let r=Xe.set(i[0],i[1],i[2]).length();const a=Xe.set(i[4],i[5],i[6]).length(),o=Xe.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),e.x=i[12],e.y=i[13],e.z=i[14],Ye.copy(this);const s=1/r,c=1/a,l=1/o;return Ye.elements[0]*=s,Ye.elements[1]*=s,Ye.elements[2]*=s,Ye.elements[4]*=c,Ye.elements[5]*=c,Ye.elements[6]*=c,Ye.elements[8]*=l,Ye.elements[9]*=l,Ye.elements[10]*=l,t.setFromRotationMatrix(Ye),n.x=r,n.y=a,n.z=o,this}makePerspective(e,t,n,i,r,a){void 0===a&&console.warn("THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.");const o=this.elements,s=2*r/(t-e),c=2*r/(n-i),l=(t+e)/(t-e),u=(n+i)/(n-i),d=-(a+r)/(a-r),h=-2*a*r/(a-r);return o[0]=s,o[4]=0,o[8]=l,o[12]=0,o[1]=0,o[5]=c,o[9]=u,o[13]=0,o[2]=0,o[6]=0,o[10]=d,o[14]=h,o[3]=0,o[7]=0,o[11]=-1,o[15]=0,this}makeOrthographic(e,t,n,i,r,a){const o=this.elements,s=1/(t-e),c=1/(n-i),l=1/(a-r),u=(t+e)*s,d=(n+i)*c,h=(a+r)*l;return o[0]=2*s,o[4]=0,o[8]=0,o[12]=-u,o[1]=0,o[5]=2*c,o[9]=0,o[13]=-d,o[2]=0,o[6]=0,o[10]=-2*l,o[14]=-h,o[3]=0,o[7]=0,o[11]=0,o[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}qe.prototype.isMatrix4=!0;const Xe=new me,Ye=new qe,Je=new me(0,0,0),$e=new me(1,1,1),Ke=new me,Ze=new me,Qe=new me,et=new qe,tt=new pe;class nt{constructor(e=0,t=0,n=0,i=nt.DefaultOrder){this._x=e,this._y=t,this._z=n,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,i=this._order){return this._x=e,this._y=t,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const i=e.elements,r=i[0],a=i[4],o=i[8],s=i[1],c=i[5],l=i[9],u=i[2],d=i[6],h=i[10];switch(t){case"XYZ":this._y=Math.asin(j(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,h),this._z=Math.atan2(-a,r)):(this._x=Math.atan2(d,c),this._z=0);break;case"YXZ":this._x=Math.asin(-j(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,h),this._z=Math.atan2(s,c)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(j(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,h),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(s,r));break;case"ZYX":this._y=Math.asin(-j(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,h),this._z=Math.atan2(s,r)):(this._x=0,this._z=Math.atan2(-a,c));break;case"YZX":this._z=Math.asin(j(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(-l,c),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(o,h));break;case"XZY":this._z=Math.asin(-j(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,r)):(this._x=Math.atan2(-l,h),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===n&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return et.makeRotationFromQuaternion(e),this.setFromRotationMatrix(et,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return tt.setFromEuler(this),this.setFromQuaternion(tt,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],void 0!==e[3]&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}toVector3(e){return e?e.set(this._x,this._y,this._z):new me(this._x,this._y,this._z)}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}}nt.prototype.isEuler=!0,nt.DefaultOrder="XYZ",nt.RotationOrders=["XYZ","YZX","ZXY","XZY","YXZ","ZYX"];class it{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let e=0;e1){for(let e=0;e0){i.children=[];for(let t=0;t0){i.animations=[];for(let t=0;t0&&(n.geometries=t),i.length>0&&(n.materials=i),r.length>0&&(n.textures=r),o.length>0&&(n.images=o),s.length>0&&(n.shapes=s),c.length>0&&(n.skeletons=c),l.length>0&&(n.animations=l)}return n.object=i,n;function a(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}}clone(e){return(new this.constructor).copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;t0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,n,i,r){vt.subVectors(i,t),yt.subVectors(n,t),bt.subVectors(e,t);const a=vt.dot(vt),o=vt.dot(yt),s=vt.dot(bt),c=yt.dot(yt),l=yt.dot(bt),u=a*c-o*o;if(0===u)return r.set(-2,-1,-1);const d=1/u,h=(c*s-o*l)*d,f=(a*l-o*s)*d;return r.set(1-h-f,f,h)}static containsPoint(e,t,n,i){return this.getBarycoord(e,t,n,i,Mt),Mt.x>=0&&Mt.y>=0&&Mt.x+Mt.y<=1}static getUV(e,t,n,i,r,a,o,s){return this.getBarycoord(e,t,n,i,Mt),s.set(0,0),s.addScaledVector(r,Mt.x),s.addScaledVector(a,Mt.y),s.addScaledVector(o,Mt.z),s}static isFrontFacing(e,t,n,i){return vt.subVectors(n,t),yt.subVectors(e,t),vt.cross(yt).dot(i)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,i){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,n,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,i),this}clone(){return(new this.constructor).copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return vt.subVectors(this.c,this.b),yt.subVectors(this.a,this.b),.5*vt.cross(yt).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Tt.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Tt.getBarycoord(e,this.a,this.b,this.c,t)}getUV(e,t,n,i,r){return Tt.getUV(e,this.a,this.b,this.c,t,n,i,r)}containsPoint(e){return Tt.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Tt.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,i=this.b,r=this.c;let a,o;xt.subVectors(i,n),_t.subVectors(r,n),wt.subVectors(e,n);const s=xt.dot(wt),c=_t.dot(wt);if(s<=0&&c<=0)return t.copy(n);Lt.subVectors(e,i);const l=xt.dot(Lt),u=_t.dot(Lt);if(l>=0&&u<=l)return t.copy(i);const d=s*u-l*c;if(d<=0&&s>=0&&l<=0)return a=s/(s-l),t.copy(n).addScaledVector(xt,a);Et.subVectors(e,r);const h=xt.dot(Et),f=_t.dot(Et);if(f>=0&&h<=f)return t.copy(r);const p=h*c-s*f;if(p<=0&&c>=0&&f<=0)return o=c/(c-f),t.copy(n).addScaledVector(_t,o);const m=l*f-h*u;if(m<=0&&u-l>=0&&h-f>=0)return St.subVectors(r,i),o=(u-l)/(u-l+(h-f)),t.copy(i).addScaledVector(St,o);const g=1/(m+p+d);return a=p*g,o=d*g,t.copy(n).addScaledVector(xt,a).addScaledVector(_t,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}let zt=0;class At extends B{constructor(){super(),Object.defineProperty(this,"id",{value:zt++}),this.uuid=G(),this.name="",this.type="Material",this.fog=!0,this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=r,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=I,this.stencilZFail=I,this.stencilZPass=I,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(void 0!==e)for(const t in e){const n=e[t];if(void 0===n){console.warn("THREE.Material: '"+t+"' parameter is undefined.");continue}if("shading"===t){console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead."),this.flatShading=1===n;continue}const i=this[t];void 0!==i?i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[t]=n:console.warn("THREE."+this.type+": '"+t+"' is not a property of this material.")}}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{}});const n={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};function i(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(n.uuid=this.uuid,n.type=this.type,""!==this.name&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),void 0!==this.roughness&&(n.roughness=this.roughness),void 0!==this.metalness&&(n.metalness=this.metalness),void 0!==this.sheen&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity&&1!==this.emissiveIntensity&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(n.shininess=this.shininess),void 0!==this.clearcoat&&(n.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,void 0!==this.combine&&(n.combine=this.combine)),void 0!==this.envMapIntensity&&(n.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(n.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&(n.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(n.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(n.size=this.size),null!==this.shadowSide&&(n.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(n.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(n.blending=this.blending),0!==this.side&&(n.side=this.side),this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),!0===this.transparent&&(n.transparent=this.transparent),n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.stencilWrite=this.stencilWrite,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,this.rotation&&0!==this.rotation&&(n.rotation=this.rotation),!0===this.polygonOffset&&(n.polygonOffset=!0),0!==this.polygonOffsetFactor&&(n.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth&&1!==this.linewidth&&(n.linewidth=this.linewidth),void 0!==this.dashSize&&(n.dashSize=this.dashSize),void 0!==this.gapSize&&(n.gapSize=this.gapSize),void 0!==this.scale&&(n.scale=this.scale),!0===this.dithering&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),!0===this.alphaToCoverage&&(n.alphaToCoverage=this.alphaToCoverage),!0===this.premultipliedAlpha&&(n.premultipliedAlpha=this.premultipliedAlpha),!0===this.wireframe&&(n.wireframe=this.wireframe),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(n.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(n.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(n.flatShading=this.flatShading),!1===this.visible&&(n.visible=!1),!1===this.toneMapped&&(n.toneMapped=!1),"{}"!==JSON.stringify(this.userData)&&(n.userData=this.userData),t){const t=i(e.textures),r=i(e.images);t.length>0&&(n.textures=t),r.length>0&&(n.images=r)}return n}clone(){return(new this.constructor).copy(this)}copy(e){this.name=e.name,this.fog=e.fog,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(null!==t){const e=t.length;n=new Array(e);for(let i=0;i!==e;++i)n[i]=t[i].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}}At.prototype.isMaterial=!0;class Vt extends At{constructor(e){super(),this.type="MeshBasicMaterial",this.color=new ae(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this}}Vt.prototype.isMeshBasicMaterial=!0;const Ht=new me,Rt=new J;class Pt{constructor(e,t,n){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=!0===n,this.usage=k,this.updateRange={offset:0,count:-1},this.version=0}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let i=0,r=this.itemSize;i0&&(e.userData=this.userData),void 0!==this.parameters){const t=this.parameters;for(const n in t)void 0!==t[n]&&(e[n]=t[n]);return e}e.data={attributes:{}};const t=this.index;null!==t&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const t in n){const i=n[t];e.data.attributes[t]=i.toJSON(e.data)}const i={};let r=!1;for(const t in this.morphAttributes){const n=this.morphAttributes[t],a=[];for(let t=0,i=n.length;t0&&(i[t]=a,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));const o=this.boundingSphere;return null!==o&&(e.data.boundingSphere={center:o.center.toArray(),radius:o.radius}),e}clone(){return(new this.constructor).copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;null!==n&&this.setIndex(n.clone(t));const i=e.attributes;for(const e in i){const n=i[e];this.setAttribute(e,n.clone(t))}const r=e.morphAttributes;for(const e in r){const n=[],i=r[e];for(let e=0,r=i.length;e0){const e=t[n[0]];if(void 0!==e){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,n=e.length;t0&&console.error("THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.")}}raycast(e,t){const n=this.geometry,i=this.material,r=this.matrixWorld;if(void 0===i)return;if(null===n.boundingSphere&&n.computeBoundingSphere(),Yt.copy(n.boundingSphere),Yt.applyMatrix4(r),!1===e.ray.intersectsSphere(Yt))return;if(qt.copy(r).invert(),Xt.copy(e.ray).applyMatrix4(qt),null!==n.boundingBox&&!1===Xt.intersectsBox(n.boundingBox))return;let a;if(n.isBufferGeometry){const r=n.index,o=n.attributes.position,s=n.morphAttributes.position,c=n.morphTargetsRelative,l=n.attributes.uv,u=n.attributes.uv2,d=n.groups,h=n.drawRange;if(null!==r)if(Array.isArray(i))for(let n=0,f=d.length;nn.far?null:{distance:l,point:ln.clone(),object:e}}(e,t,n,i,Jt,$t,Kt,cn);if(f){s&&(an.fromBufferAttribute(s,l),on.fromBufferAttribute(s,u),sn.fromBufferAttribute(s,d),f.uv=Tt.getUV(cn,Jt,$t,Kt,an,on,sn,new J)),c&&(an.fromBufferAttribute(c,l),on.fromBufferAttribute(c,u),sn.fromBufferAttribute(c,d),f.uv2=Tt.getUV(cn,Jt,$t,Kt,an,on,sn,new J));const e={a:l,b:u,c:d,normal:new me,materialIndex:0};Tt.getNormal(Jt,$t,Kt,e.normal),f.face=e}return f}un.prototype.isMesh=!0;class hn extends jt{constructor(e=1,t=1,n=1,i=1,r=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:r,depthSegments:a};const o=this;i=Math.floor(i),r=Math.floor(r),a=Math.floor(a);const s=[],c=[],l=[],u=[];let d=0,h=0;function f(e,t,n,i,r,a,f,p,m,g,C){const v=a/m,y=f/g,b=a/2,M=f/2,x=p/2,_=m+1,S=g+1;let w=0,L=0;const E=new me;for(let a=0;a0?1:-1,l.push(E.x,E.y,E.z),u.push(s/m),u.push(1-a/g),w+=1}}for(let e=0;e0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader;const n={};for(const e in this.extensions)!0===this.extensions[e]&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}gn.prototype.isShaderMaterial=!0;class Cn extends Ct{constructor(){super(),this.type="Camera",this.matrixWorldInverse=new qe,this.projectionMatrix=new qe,this.projectionMatrixInverse=new qe}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(-t[8],-t[9],-t[10]).normalize()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}Cn.prototype.isCamera=!0;class vn extends Cn{constructor(e=50,t=1,n=.1,i=2e3){super(),this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=2*W*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*U*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*W*Math.atan(Math.tan(.5*U*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}setViewOffset(e,t,n,i,r,a){this.aspect=e/t,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*U*this.fov)/this.zoom,n=2*t,i=this.aspect*n,r=-.5*i;const a=this.view;if(null!==this.view&&this.view.enabled){const e=a.fullWidth,o=a.fullHeight;r+=a.offsetX*i/e,t-=a.offsetY*n/o,i*=a.width/e,n*=a.height/o}const o=this.filmOffset;0!==o&&(r+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-n,e,this.far),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}vn.prototype.isPerspectiveCamera=!0;const yn=90;class bn extends Ct{constructor(e,t,n){if(super(),this.type="CubeCamera",!0!==n.isWebGLCubeRenderTarget)return void console.error("THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.");this.renderTarget=n;const i=new vn(yn,1,e,t);i.layers=this.layers,i.up.set(0,-1,0),i.lookAt(new me(1,0,0)),this.add(i);const r=new vn(yn,1,e,t);r.layers=this.layers,r.up.set(0,-1,0),r.lookAt(new me(-1,0,0)),this.add(r);const a=new vn(yn,1,e,t);a.layers=this.layers,a.up.set(0,0,1),a.lookAt(new me(0,1,0)),this.add(a);const o=new vn(yn,1,e,t);o.layers=this.layers,o.up.set(0,0,-1),o.lookAt(new me(0,-1,0)),this.add(o);const s=new vn(yn,1,e,t);s.layers=this.layers,s.up.set(0,-1,0),s.lookAt(new me(0,0,1)),this.add(s);const c=new vn(yn,1,e,t);c.layers=this.layers,c.up.set(0,-1,0),c.lookAt(new me(0,0,-1)),this.add(c)}update(e,t){null===this.parent&&this.updateMatrixWorld();const n=this.renderTarget,[i,r,a,o,s,c]=this.children,l=e.xr.enabled,u=e.getRenderTarget();e.xr.enabled=!1;const d=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0),e.render(t,i),e.setRenderTarget(n,1),e.render(t,r),e.setRenderTarget(n,2),e.render(t,a),e.setRenderTarget(n,3),e.render(t,o),e.setRenderTarget(n,4),e.render(t,s),n.texture.generateMipmaps=d,e.setRenderTarget(n,5),e.render(t,c),e.setRenderTarget(u),e.xr.enabled=l,n.texture.needsPMREMUpdate=!0}}class Mn extends le{constructor(e,t,n,i,r,o,s,c,l,u){super(e=void 0!==e?e:[],t=void 0!==t?t:a,n,i,r,o,s,c,l,u),this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}Mn.prototype.isCubeTexture=!0;class xn extends he{constructor(e,t,n){Number.isInteger(t)&&(console.warn("THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )"),t=n),super(e,e,t),t=t||{},this.texture=new Mn(void 0,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.encoding),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==t.generateMipmaps&&t.generateMipmaps,this.texture.minFilter=void 0!==t.minFilter?t.minFilter:h}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.format=b,this.texture.encoding=t.encoding,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n=new hn(5,5,5),i=new gn({name:"CubemapFromEquirect",uniforms:fn({tEquirect:{value:null}}),vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t",side:1,blending:0});i.uniforms.tEquirect.value=t;const r=new un(n,i),a=t.minFilter;return t.minFilter===f&&(t.minFilter=h),new bn(1,10,this).update(e,r),t.minFilter=a,r.geometry.dispose(),r.material.dispose(),this}clear(e,t,n,i){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,n,i);e.setRenderTarget(r)}}xn.prototype.isWebGLCubeRenderTarget=!0;const _n=new me,Sn=new me,wn=new $;class Ln{constructor(e=new me(1,0,0),t=0){this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,i){return this.normal.set(e,t,n),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const i=_n.subVectors(n,t).cross(Sn.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(this.normal).multiplyScalar(-this.distanceToPoint(e)).add(e)}intersectLine(e,t){const n=e.delta(_n),i=this.normal.dot(n);if(0===i)return 0===this.distanceToPoint(e.start)?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:t.copy(n).multiplyScalar(r).add(e.start)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const n=t||wn.getNormalMatrix(e),i=this.coplanarPoint(_n).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return(new this.constructor).copy(this)}}Ln.prototype.isPlane=!0;const En=new Ne,Tn=new me;class zn{constructor(e=new Ln,t=new Ln,n=new Ln,i=new Ln,r=new Ln,a=new Ln){this.planes=[e,t,n,i,r,a]}set(e,t,n,i,r,a){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(i),o[4].copy(r),o[5].copy(a),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e){const t=this.planes,n=e.elements,i=n[0],r=n[1],a=n[2],o=n[3],s=n[4],c=n[5],l=n[6],u=n[7],d=n[8],h=n[9],f=n[10],p=n[11],m=n[12],g=n[13],C=n[14],v=n[15];return t[0].setComponents(o-i,u-s,p-d,v-m).normalize(),t[1].setComponents(o+i,u+s,p+d,v+m).normalize(),t[2].setComponents(o+r,u+c,p+h,v+g).normalize(),t[3].setComponents(o-r,u-c,p-h,v-g).normalize(),t[4].setComponents(o-a,u-l,p-f,v-C).normalize(),t[5].setComponents(o+a,u+l,p+f,v+C).normalize(),this}intersectsObject(e){const t=e.geometry;return null===t.boundingSphere&&t.computeBoundingSphere(),En.copy(t.boundingSphere).applyMatrix4(e.matrixWorld),this.intersectsSphere(En)}intersectsSprite(e){return En.center.set(0,0,0),En.radius=.7071067811865476,En.applyMatrix4(e.matrixWorld),this.intersectsSphere(En)}intersectsSphere(e){const t=this.planes,n=e.center,i=-e.radius;for(let e=0;e<6;e++)if(t[e].distanceToPoint(n)0?e.max.x:e.min.x,Tn.y=i.normal.y>0?e.max.y:e.min.y,Tn.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Tn)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}function An(){let e=null,t=!1,n=null,i=null;function r(t,a){n(t,a),i=e.requestAnimationFrame(r)}return{start:function(){!0!==t&&null!==n&&(i=e.requestAnimationFrame(r),t=!0)},stop:function(){e.cancelAnimationFrame(i),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function Vn(e,t){const n=t.isWebGL2,i=new WeakMap;return{get:function(e){return e.isInterleavedBufferAttribute&&(e=e.data),i.get(e)},remove:function(t){t.isInterleavedBufferAttribute&&(t=t.data);const n=i.get(t);n&&(e.deleteBuffer(n.buffer),i.delete(t))},update:function(t,r){if(t.isGLBufferAttribute){const e=i.get(t);return void((!e||e.version 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif",bumpmap_pars_fragment:"#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif",clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif",common:"#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 ) + 0.5;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\treturn texture2D( envMap, uv ).rgb;\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",encodings_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",encodings_pars_fragment:"vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec;\n\t\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\t\treflectVec = reflect( - viewDir, normal );\n\t\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\t#else\n\t\t\t\treflectVec = refract( - viewDir, normal, refractionRatio );\n\t\t\t#endif\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}",lightmap_fragment:"#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_vertex:"vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry.normal );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry.normal );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointLightInfo( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotLightInfo( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalLightInfo( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry.normal );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif",lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1, 2 ) * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform vec2 morphTargetsTextureSize;\n\t\tvec3 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset, const in int stride ) {\n\t\t\tfloat texelIndex = float( vertexIndex * stride + offset );\n\t\t\tfloat y = floor( texelIndex / morphTargetsTextureSize.x );\n\t\t\tfloat x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tvec3 morphUV = vec3( ( x + 0.5 ) / morphTargetsTextureSize.x, y / morphTargetsTextureSize.y, morphTargetIndex );\n\t\t\treturn texture( morphTargetsTexture, morphUV ).xyz;\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\t#ifndef USE_MORPHNORMALS\n\t\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 1 ) * morphTargetInfluences[ i ];\n\t\t\t#else\n\t\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 2 ) * morphTargetInfluences[ i ];\n\t\t\t#endif\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;",normal_fragment_maps:"#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif",output_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif",shadowmap_pars_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tfloat transmissionAlpha = 1.0;\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationColor, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor );\n\ttransmissionAlpha = mix( transmissionAlpha, transmission.a, transmissionFactor );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif",uv_pars_fragment:"#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif",uv_pars_vertex:"#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif",uv_vertex:"#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif",uv2_pars_fragment:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif",uv2_pars_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif",uv2_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tgl_FragColor = texture2D( t2D, vUv );\n\t#include \n\t#include \n}",cube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"#include \nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include \n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}",depth_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}",distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include